This is an automated email from the ASF dual-hosted git repository.
Caideyipi pushed a commit to branch dev/1.3
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/dev/1.3 by this push:
new fb5f91858aa [Pipe] Fix aggregate window statistics (#19326) (#19368)
fb5f91858aa is described below
commit fb5f91858aacad80522d3bdc1cae8954b928edae
Author: Caideyipi <[email protected]>
AuthorDate: Mon Nov 23 16:38:56 2026 +0800
[Pipe] Fix aggregate window statistics (#19326) (#19368)
* [Pipe] Fix aggregate window statistics
* [Pipe] Route aggregate type dispatch through TypeService
* [Pipe] Preserve aggregate window state on recovery
(cherry picked from commit d494b5ec7fef75cd2efa05b603a5263e7d42c4a9)
---
.../apache/iotdb/db/i18n/DataNodePipeMessages.java | 3 +
.../apache/iotdb/db/i18n/DataNodePipeMessages.java | 3 +
.../processor/aggregate/AggregateProcessor.java | 119 +++-
.../aggregate/TimeSeriesRuntimeState.java | 58 +-
.../aggregatedresult/AggregatedResultOperator.java | 8 +
.../standardstatistics/AverageOperator.java | 2 +-
.../ClearanceFactorOperator.java | 16 +-
.../standardstatistics/CrestFactorOperator.java | 2 +-
.../standardstatistics/FormFactorOperator.java | 24 +-
.../standardstatistics/KurtosisOperator.java | 2 +-
.../standardstatistics/PeakOperator.java | 10 +-
.../standardstatistics/PulseFactorOperator.java | 16 +-
.../standardstatistics/RootMeanSquareOperator.java | 2 +-
.../standardstatistics/SkewnessOperator.java | 2 +-
.../standardstatistics/VarianceOperator.java | 4 +-
.../CustomizedReadableIntermediateResults.java | 9 +-
.../IntermediateResultOperator.java | 8 +
.../sametype/numeric/AbsoluteMaxOperator.java | 80 ++-
.../numeric/IntegralPoweredSumOperator.java | 50 +-
.../doubletype/FractionPoweredSumOperator.java | 32 +-
.../specifictype/integertype/CountOperator.java | 15 +-
.../StandardStatisticsOperatorProcessor.java | 2 +
.../window/datastructure/TimeSeriesWindow.java | 67 ++-
.../PipeHistoricalDataRegionTsFileSource.java | 9 +-
.../aggregate/AggregateProcessorTest.java | 612 +++++++++++++++++++++
.../processor/TumblingWindowingProcessorTest.java | 31 ++
.../PipeHistoricalDataRegionTsFileSourceTest.java | 78 +++
.../index/impl/TimeWindowStateProgressIndex.java | 4 +
.../commons/consensus/index/ProgressIndexTest.java | 43 ++
29 files changed, 1207 insertions(+), 104 deletions(-)
diff --git
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
index 129d073180a..887794b6742 100644
---
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
@@ -31,6 +31,9 @@ public final class DataNodePipeMessages {
private DataNodePipeMessages() {}
+ public static final String
EXCEPTION_THE_AGGREGATOR_AND_OUTPUT_NAME_ARG_IS_INVALID_2C76EEE3 =
+ "The aggregator and output name %s is invalid.";
+
public static final String
EXCEPTION_FORCERESIZE_FAILED_AFTER_ARG_RETRIES_TOTAL_ARG_BYTES_USED_ARG_BYTES_USEDTABLETS_ARG_BYTES_USEDTSFILES_ARG_BYTES_TABLETLIMIT_ARG_BYTES_TSFILELIMIT_ARG_BYTES_TABLETANDTSFILELIMIT_ARG_BYTES_PROTECTEDPARSERLIMIT_ARG_BYTES_REQUESTED_ARG_BYTES_311C8C7E
=
"forceResize failed after %d retries: total=%d bytes, used=%d bytes,
"
diff --git
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
index 5dde8a32c49..4a81b5752f0 100644
---
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodePipeMessages.java
@@ -31,6 +31,9 @@ public final class DataNodePipeMessages {
private DataNodePipeMessages() {}
+ public static final String
EXCEPTION_THE_AGGREGATOR_AND_OUTPUT_NAME_ARG_IS_INVALID_2C76EEE3 =
+ "聚合器和输出名称 %s 无效。";
+
public static final String
EXCEPTION_FORCERESIZE_FAILED_AFTER_ARG_RETRIES_TOTAL_ARG_BYTES_USED_ARG_BYTES_USEDTABLETS_ARG_BYTES_USEDTSFILES_ARG_BYTES_TABLETLIMIT_ARG_BYTES_TSFILELIMIT_ARG_BYTES_TABLETANDTSFILELIMIT_ARG_BYTES_PROTECTEDPARSERLIMIT_ARG_BYTES_REQUESTED_ARG_BYTES_311C8C7E
=
"forceResize 重试 %d 次后仍无法分配内存:total=%d bytes,used=%d bytes,"
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/AggregateProcessor.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/AggregateProcessor.java
index 183247dd678..7fc9ee0b8cb 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/AggregateProcessor.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/AggregateProcessor.java
@@ -30,6 +30,7 @@ import
org.apache.iotdb.commons.pipe.agent.task.meta.PipeTaskMeta;
import
org.apache.iotdb.commons.pipe.config.plugin.env.PipeTaskProcessorRuntimeEnvironment;
import org.apache.iotdb.commons.pipe.event.EnrichedEvent;
import org.apache.iotdb.commons.utils.PathUtils;
+import org.apache.iotdb.db.i18n.DataNodePipeMessages;
import org.apache.iotdb.db.pipe.agent.PipeDataNodeAgent;
import
org.apache.iotdb.db.pipe.agent.plugin.dataregion.PipeDataRegionPluginAgent;
import org.apache.iotdb.db.pipe.event.common.row.PipeResetTabletRow;
@@ -75,11 +76,13 @@ import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
@@ -143,6 +146,15 @@ public class AggregateProcessor implements PipeProcessor {
String.format("The parameter %s must not be empty.",
PROCESSOR_OPERATORS_KEY),
parameters.getStringOrDefault(
PROCESSOR_OPERATORS_KEY, PROCESSOR_OPERATORS_DEFAULT_VALUE))
+ .validate(
+ arg -> areUniqueOperatorNames((String) arg),
+ String.format(
+ DataNodePipeMessages
+
.EXCEPTION_THE_AGGREGATOR_AND_OUTPUT_NAME_ARG_IS_INVALID_2C76EEE3,
+ parameters.getStringOrDefault(
+ PROCESSOR_OPERATORS_KEY,
PROCESSOR_OPERATORS_DEFAULT_VALUE)),
+ parameters.getStringOrDefault(
+ PROCESSOR_OPERATORS_KEY, PROCESSOR_OPERATORS_DEFAULT_VALUE))
.validate(
arg -> !((String) arg).isEmpty(),
String.format("The parameter %s must not be empty.",
PROCESSOR_WINDOWING_STRATEGY_KEY),
@@ -158,9 +170,10 @@ public class AggregateProcessor implements PipeProcessor {
PROCESSOR_OUTPUT_DATABASE_KEY,
PROCESSOR_OUTPUT_DATABASE_DEFAULT_VALUE))
.validate(
arg ->
- ((String) arg).isEmpty()
- || Arrays.stream(((String) arg).replace(" ",
"").split(","))
- .allMatch(this::isLegalMeasurement),
+ areLegalOutputMeasurements(
+ (String) arg,
+ parameters.getStringOrDefault(
+ PROCESSOR_OPERATORS_KEY,
PROCESSOR_OPERATORS_DEFAULT_VALUE)),
String.format(
"The output measurements %s contains illegal measurements, the
measurements must be the last level of a legal path",
parameters.getStringOrDefault(
@@ -170,6 +183,44 @@ public class AggregateProcessor implements PipeProcessor {
PROCESSOR_OUTPUT_MEASUREMENTS_KEY,
PROCESSOR_OUTPUT_MEASUREMENTS_DEFAULT_VALUE));
}
+ private boolean areUniqueOperatorNames(final String operatorString) {
+ final String[] operatorNames = operatorString.replace(" ", "").split(",",
-1);
+ final Set<String> uniqueOperatorNames = new HashSet<>();
+ return Arrays.stream(operatorNames)
+ .allMatch(
+ operatorName ->
+ !operatorName.isEmpty()
+ &&
uniqueOperatorNames.add(operatorName.toLowerCase(Locale.ROOT)));
+ }
+
+ private boolean areLegalOutputMeasurements(
+ final String outputMeasurementString, final String operatorString) {
+ if (outputMeasurementString.isEmpty()) {
+ return true;
+ }
+
+ final String[] outputMeasurementNames =
+ Arrays.stream(outputMeasurementString.replace(" ", "").split(",", -1))
+ .toArray(String[]::new);
+ final String[] operatorNames = operatorString.replace(" ", "").split(",",
-1);
+ if (outputMeasurementNames.length > operatorNames.length) {
+ return false;
+ }
+
+ final Set<String> uniqueOutputMeasurementNames = new HashSet<>();
+ for (int index = 0; index < operatorNames.length; ++index) {
+ final String outputMeasurementName =
+ index < outputMeasurementNames.length
+ ? outputMeasurementNames[index]
+ : operatorNames[index];
+ if ((index < outputMeasurementNames.length &&
!isLegalMeasurement(outputMeasurementName))
+ || !uniqueOutputMeasurementNames.add(outputMeasurementName)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
private boolean isLegalMeasurement(final String measurement) {
try {
PathUtils.isLegalPath("root." + measurement);
@@ -209,12 +260,14 @@ public class AggregateProcessor implements PipeProcessor {
// The output max delay milliseconds must be set to at least 1
// to guarantee the correctness of the CAS in last receive time
outputMaxDelayMilliseconds =
- outputMaxDelaySeconds < 0 ? Long.MAX_VALUE :
Math.max(outputMaxDelaySeconds * 1000, 1);
+ outputMaxDelaySeconds < 0
+ ? Long.MAX_VALUE
+ : Math.max(secondsToMilliseconds(outputMaxDelaySeconds), 1);
outputMinReportIntervalMilliseconds =
- parameters.getLongOrDefault(
+ secondsToMilliseconds(
+ parameters.getLongOrDefault(
PROCESSOR_OUTPUT_MIN_REPORT_INTERVAL_SECONDS_KEY,
- PROCESSOR_OUTPUT_MIN_REPORT_INTERVAL_SECONDS_DEFAULT_VALUE)
- * 1000;
+ PROCESSOR_OUTPUT_MIN_REPORT_INTERVAL_SECONDS_DEFAULT_VALUE));
outputDatabase =
parameters.getStringOrDefault(
PROCESSOR_OUTPUT_DATABASE_KEY,
PROCESSOR_OUTPUT_DATABASE_DEFAULT_VALUE);
@@ -243,10 +296,10 @@ public class AggregateProcessor implements PipeProcessor {
for (int i = 0; i < operatorNameList.size(); ++i) {
if (i < outputMeasurementNameList.size()) {
aggregatorName2OutputNameMap.put(
- operatorNameList.get(i).toLowerCase(),
outputMeasurementNameList.get(i));
+ operatorNameList.get(i).toLowerCase(Locale.ROOT),
outputMeasurementNameList.get(i));
} else {
aggregatorName2OutputNameMap.put(
- operatorNameList.get(i).toLowerCase(), operatorNameList.get(i));
+ operatorNameList.get(i).toLowerCase(Locale.ROOT),
operatorNameList.get(i));
}
}
@@ -264,11 +317,13 @@ public class AggregateProcessor implements PipeProcessor {
operatorProcessor.getAggregatorOperatorSet().stream()
.filter(
operator ->
-
aggregatorName2OutputNameMap.containsKey(operator.getName().toLowerCase()))
+ aggregatorName2OutputNameMap.containsKey(
+ operator.getName().toLowerCase(Locale.ROOT)))
.forEach(
operator -> {
outputName2OperatorMap.put(
-
aggregatorName2OutputNameMap.get(operator.getName().toLowerCase()), operator);
+
aggregatorName2OutputNameMap.get(operator.getName().toLowerCase(Locale.ROOT)),
+ operator);
declaredIntermediateResultSet.addAll(operator.getDeclaredIntermediateValueNames());
});
@@ -428,7 +483,7 @@ public class AggregateProcessor implements PipeProcessor {
final String timeSeries =
(outputDatabaseWithPathSeparator.isEmpty()
? row.getDeviceId()
- : row.getDeviceId().replaceFirst(databaseWithPathSeparator,
""))
+ : stripDatabasePrefix(row.getDeviceId(),
databaseWithPathSeparator))
+ TsFileConstant.PATH_SEPARATOR
+ row.getColumnName(index);
@@ -605,6 +660,16 @@ public class AggregateProcessor implements PipeProcessor {
}
}
+ static String stripDatabasePrefix(final String deviceId, final String
databaseWithPathSeparator) {
+ return deviceId.startsWith(databaseWithPathSeparator)
+ ? deviceId.substring(databaseWithPathSeparator.length())
+ : deviceId;
+ }
+
+ static long secondsToMilliseconds(final long seconds) {
+ return TimeUnit.SECONDS.toMillis(seconds);
+ }
+
/**
* Collect {@link WindowOutput}s of a single timeSeries in one turn. The
{@link TSDataType}s shall
* be the same because the {@link AggregatedResultOperator}s shall return
the same value for the
@@ -620,19 +685,7 @@ public class AggregateProcessor implements PipeProcessor {
if (Objects.isNull(outputs) || outputs.isEmpty()) {
return;
}
- // Sort and same timestamps removal
- outputs.sort(Comparator.comparingLong(WindowOutput::getTimestamp));
-
- final AtomicLong lastValue = new AtomicLong(Long.MIN_VALUE);
- final List<WindowOutput> distinctOutputs = new ArrayList<>();
- outputs.forEach(
- output -> {
- final long timeStamp = output.getTimestamp();
- if (timeStamp != lastValue.get()) {
- lastValue.set(timeStamp);
- distinctOutputs.add(output);
- }
- });
+ final List<WindowOutput> distinctOutputs =
sortAndDeduplicateOutputs(outputs);
final MeasurementSchema[] measurementSchemaList =
new MeasurementSchema[columnNameStringList.length];
@@ -833,6 +886,22 @@ public class AggregateProcessor implements PipeProcessor {
}
}
+ static List<WindowOutput> sortAndDeduplicateOutputs(final List<WindowOutput>
outputs) {
+ outputs.sort(Comparator.comparingLong(WindowOutput::getTimestamp));
+
+ final List<WindowOutput> distinctOutputs = new ArrayList<>(outputs.size());
+ long lastTimestamp = 0;
+ boolean hasLastTimestamp = false;
+ for (final WindowOutput output : outputs) {
+ if (!hasLastTimestamp || output.getTimestamp() != lastTimestamp) {
+ distinctOutputs.add(output);
+ lastTimestamp = output.getTimestamp();
+ hasLastTimestamp = true;
+ }
+ }
+ return distinctOutputs;
+ }
+
@Override
public void close() throws Exception {
boolean isLastReference = false;
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/TimeSeriesRuntimeState.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/TimeSeriesRuntimeState.java
index 2cb9a414690..c0950cdd201 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/TimeSeriesRuntimeState.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/TimeSeriesRuntimeState.java
@@ -57,6 +57,7 @@ public class TimeSeriesRuntimeState {
// Outer set values
private long lastReportTimeStamp = Long.MIN_VALUE;
+ private boolean hasReportedTimeStamp;
private final List<TimeSeriesWindow> currentOpeningWindows = new
ArrayList<>();
// Variables to avoid "new" operation
@@ -80,7 +81,7 @@ public class TimeSeriesRuntimeState {
throws IOException {
Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> output = null;
- if (timestamp <= lastReportTimeStamp) {
+ if (hasReportedTimeStamp && timestamp <= lastReportTimeStamp) {
return null;
}
final Set<TimeSeriesWindow> addedWindows =
@@ -104,8 +105,7 @@ public class TimeSeriesRuntimeState {
if (stateWindowOutputPair.getLeft().isEmit()
&& Objects.nonNull(stateWindowOutputPair.getRight())) {
outputList.add(stateWindowOutputPair.getRight());
- lastReportTimeStamp =
- Math.max(lastReportTimeStamp,
stateWindowOutputPair.getRight().getProgressTime());
+
updateLastReportTimeStamp(stateWindowOutputPair.getRight().getProgressTime());
}
if (stateWindowOutputPair.getLeft().isPurge()) {
windowIterator.remove();
@@ -126,7 +126,7 @@ public class TimeSeriesRuntimeState {
throws IOException {
Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> output = null;
- if (timestamp <= lastReportTimeStamp) {
+ if (hasReportedTimeStamp && timestamp <= lastReportTimeStamp) {
return null;
}
final Set<TimeSeriesWindow> addedWindows =
@@ -150,8 +150,7 @@ public class TimeSeriesRuntimeState {
if (stateWindowOutputPair.getLeft().isEmit()
&& Objects.nonNull(stateWindowOutputPair.getRight())) {
outputList.add(stateWindowOutputPair.getRight());
- lastReportTimeStamp =
- Math.max(lastReportTimeStamp,
stateWindowOutputPair.getRight().getProgressTime());
+
updateLastReportTimeStamp(stateWindowOutputPair.getRight().getProgressTime());
}
if (stateWindowOutputPair.getLeft().isPurge()) {
windowIterator.remove();
@@ -172,7 +171,7 @@ public class TimeSeriesRuntimeState {
throws IOException {
Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> output = null;
- if (timestamp <= lastReportTimeStamp) {
+ if (hasReportedTimeStamp && timestamp <= lastReportTimeStamp) {
return null;
}
final Set<TimeSeriesWindow> addedWindows =
@@ -196,8 +195,7 @@ public class TimeSeriesRuntimeState {
if (stateWindowOutputPair.getLeft().isEmit()
&& Objects.nonNull(stateWindowOutputPair.getRight())) {
outputList.add(stateWindowOutputPair.getRight());
- lastReportTimeStamp =
- Math.max(lastReportTimeStamp,
stateWindowOutputPair.getRight().getProgressTime());
+
updateLastReportTimeStamp(stateWindowOutputPair.getRight().getProgressTime());
}
if (stateWindowOutputPair.getLeft().isPurge()) {
windowIterator.remove();
@@ -218,7 +216,7 @@ public class TimeSeriesRuntimeState {
throws IOException {
Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> output = null;
- if (timestamp <= lastReportTimeStamp) {
+ if (hasReportedTimeStamp && timestamp <= lastReportTimeStamp) {
return null;
}
final Set<TimeSeriesWindow> addedWindows =
@@ -242,8 +240,7 @@ public class TimeSeriesRuntimeState {
if (stateWindowOutputPair.getLeft().isEmit()
&& Objects.nonNull(stateWindowOutputPair.getRight())) {
outputList.add(stateWindowOutputPair.getRight());
- lastReportTimeStamp =
- Math.max(lastReportTimeStamp,
stateWindowOutputPair.getRight().getProgressTime());
+
updateLastReportTimeStamp(stateWindowOutputPair.getRight().getProgressTime());
}
if (stateWindowOutputPair.getLeft().isPurge()) {
windowIterator.remove();
@@ -264,7 +261,7 @@ public class TimeSeriesRuntimeState {
throws IOException {
Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> output = null;
- if (timestamp <= lastReportTimeStamp) {
+ if (hasReportedTimeStamp && timestamp <= lastReportTimeStamp) {
return null;
}
final Set<TimeSeriesWindow> addedWindows =
@@ -288,8 +285,7 @@ public class TimeSeriesRuntimeState {
if (stateWindowOutputPair.getLeft().isEmit()
&& Objects.nonNull(stateWindowOutputPair.getRight())) {
outputList.add(stateWindowOutputPair.getRight());
- lastReportTimeStamp =
- Math.max(lastReportTimeStamp,
stateWindowOutputPair.getRight().getProgressTime());
+
updateLastReportTimeStamp(stateWindowOutputPair.getRight().getProgressTime());
}
if (stateWindowOutputPair.getLeft().isPurge()) {
windowIterator.remove();
@@ -310,7 +306,7 @@ public class TimeSeriesRuntimeState {
throws IOException {
Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> output = null;
- if (timestamp <= lastReportTimeStamp) {
+ if (hasReportedTimeStamp && timestamp <= lastReportTimeStamp) {
return null;
}
final Set<TimeSeriesWindow> addedWindows =
@@ -334,8 +330,7 @@ public class TimeSeriesRuntimeState {
if (stateWindowOutputPair.getLeft().isEmit()
&& Objects.nonNull(stateWindowOutputPair.getRight())) {
outputList.add(stateWindowOutputPair.getRight());
- lastReportTimeStamp =
- Math.max(lastReportTimeStamp,
stateWindowOutputPair.getRight().getProgressTime());
+
updateLastReportTimeStamp(stateWindowOutputPair.getRight().getProgressTime());
}
if (stateWindowOutputPair.getLeft().isPurge()) {
windowIterator.remove();
@@ -356,7 +351,7 @@ public class TimeSeriesRuntimeState {
throws IOException {
Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> output = null;
- if (timestamp <= lastReportTimeStamp) {
+ if (hasReportedTimeStamp && timestamp <= lastReportTimeStamp) {
return null;
}
final Set<TimeSeriesWindow> addedWindows =
@@ -380,8 +375,7 @@ public class TimeSeriesRuntimeState {
if (stateWindowOutputPair.getLeft().isEmit()
&& Objects.nonNull(stateWindowOutputPair.getRight())) {
outputList.add(stateWindowOutputPair.getRight());
- lastReportTimeStamp =
- Math.max(lastReportTimeStamp,
stateWindowOutputPair.getRight().getProgressTime());
+
updateLastReportTimeStamp(stateWindowOutputPair.getRight().getProgressTime());
}
if (stateWindowOutputPair.getLeft().isPurge()) {
windowIterator.remove();
@@ -402,7 +396,7 @@ public class TimeSeriesRuntimeState {
throws IOException {
Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> output = null;
- if (timestamp <= lastReportTimeStamp) {
+ if (hasReportedTimeStamp && timestamp <= lastReportTimeStamp) {
return null;
}
final Set<TimeSeriesWindow> addedWindows =
@@ -426,8 +420,7 @@ public class TimeSeriesRuntimeState {
if (stateWindowOutputPair.getLeft().isEmit()
&& Objects.nonNull(stateWindowOutputPair.getRight())) {
outputList.add(stateWindowOutputPair.getRight());
- lastReportTimeStamp =
- Math.max(lastReportTimeStamp,
stateWindowOutputPair.getRight().getProgressTime());
+
updateLastReportTimeStamp(stateWindowOutputPair.getRight().getProgressTime());
}
if (stateWindowOutputPair.getLeft().isPurge()) {
windowIterator.remove();
@@ -449,6 +442,11 @@ public class TimeSeriesRuntimeState {
.collect(Collectors.toList());
}
+ private void updateLastReportTimeStamp(final long timestamp) {
+ lastReportTimeStamp = Math.max(lastReportTimeStamp, timestamp);
+ hasReportedTimeStamp = true;
+ }
+
// A runtime state with window buffer shall be reported after at least
output min report
// interval time to avoid frequent serialization
// Return null if this should not report
@@ -476,14 +474,20 @@ public class TimeSeriesRuntimeState {
public void restoreTimestampAndWindows(final Pair<Long, ByteBuffer>
timestampWindowBufferPair)
throws IOException {
- if (timestampWindowBufferPair.getLeft() <= lastReportTimeStamp) {
+ if (hasReportedTimeStamp && timestampWindowBufferPair.getLeft() <=
lastReportTimeStamp) {
// The runtime state may be initialized by different processorSubtasks
on one DataNode
// Only the subtask with the largest timestamp wins
return;
}
this.lastReportTimeStamp = timestampWindowBufferPair.getLeft();
+ hasReportedTimeStamp = true;
+ currentOpeningWindows.clear();
final ByteBuffer buffer = timestampWindowBufferPair.getRight();
- final int size = ReadWriteIOUtils.readInt(buffer);
+ if (buffer == null) {
+ return;
+ }
+ final ByteBuffer readBuffer = buffer.duplicate();
+ final int size = ReadWriteIOUtils.readInt(readBuffer);
for (int i = 0; i < size; ++i) {
// The runtime value will be deserialized if exists
final TimeSeriesWindow currentWindow = new
TimeSeriesWindow(windowingProcessor, null);
@@ -491,7 +495,7 @@ public class TimeSeriesRuntimeState {
intermediateResultName2OperatorSupplierMap,
aggregatorOutputName2OperatorMap,
systemParameters);
- currentWindow.deserialize(buffer);
+ currentWindow.deserialize(readBuffer);
currentOpeningWindows.add(currentWindow);
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/AggregatedResultOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/AggregatedResultOperator.java
index a792bc0d393..751372bd591 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/AggregatedResultOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/AggregatedResultOperator.java
@@ -54,6 +54,14 @@ public interface AggregatedResultOperator {
/** Get the needed intermediate value names of this aggregate result. */
Set<String> getDeclaredIntermediateValueNames();
+ default boolean supportsLegacyIntermediateResults() {
+ return false;
+ }
+
+ default Set<String> getLegacyIntermediateValueNames() {
+ return getDeclaredIntermediateValueNames();
+ }
+
/**
* terminateWindow receives a Map to get intermediate results by its names,
and produce a
* characteristic value of this window.
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/AverageOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/AverageOperator.java
index 226893acaec..7dcfa2c1ff4 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/AverageOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/AverageOperator.java
@@ -52,6 +52,6 @@ public class AverageOperator implements
AggregatedResultOperator {
TSDataType measurementDataType, CustomizedReadableIntermediateResults
intermediateResults) {
return new Pair<>(
TSDataType.DOUBLE,
- intermediateResults.getDouble("sum_x1") /
intermediateResults.getInt("count"));
+ intermediateResults.getDouble("sum_x1") /
intermediateResults.getLong("count"));
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/ClearanceFactorOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/ClearanceFactorOperator.java
index d77e49bf3f2..309d0e0c00e 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/ClearanceFactorOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/ClearanceFactorOperator.java
@@ -44,6 +44,17 @@ public class ClearanceFactorOperator implements
AggregatedResultOperator {
@Override
public Set<String> getDeclaredIntermediateValueNames() {
+ return Collections.unmodifiableSet(
+ new HashSet<>(Arrays.asList("abs_max", "sum_x0.5", "sum_abs_x0.5",
"count")));
+ }
+
+ @Override
+ public boolean supportsLegacyIntermediateResults() {
+ return true;
+ }
+
+ @Override
+ public Set<String> getLegacyIntermediateValueNames() {
return Collections.unmodifiableSet(
new HashSet<>(Arrays.asList("abs_max", "sum_x0.5", "count")));
}
@@ -51,11 +62,14 @@ public class ClearanceFactorOperator implements
AggregatedResultOperator {
@Override
public Pair<TSDataType, Object> terminateWindow(
TSDataType measurementDataType, CustomizedReadableIntermediateResults
intermediateResults) {
+ final String averageSquareRootAbsoluteValueName =
+ intermediateResults.isLegacyStatisticsFormula() ? "sum_x0.5" :
"sum_abs_x0.5";
return new Pair<>(
TSDataType.DOUBLE,
intermediateResults.getDouble("abs_max")
/ Math.pow(
- intermediateResults.getDouble("sum_x0.5") /
intermediateResults.getInt("count"),
+
intermediateResults.getDouble(averageSquareRootAbsoluteValueName)
+ / intermediateResults.getLong("count"),
2));
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/CrestFactorOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/CrestFactorOperator.java
index 53710e1e326..f0ee250a00c 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/CrestFactorOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/CrestFactorOperator.java
@@ -54,7 +54,7 @@ public class CrestFactorOperator implements
AggregatedResultOperator {
TSDataType.DOUBLE,
intermediateResults.getDouble("abs_max")
/ Math.pow(
- intermediateResults.getDouble("sum_x2") /
intermediateResults.getInt("count"),
+ intermediateResults.getDouble("sum_x2") /
intermediateResults.getLong("count"),
0.5));
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/FormFactorOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/FormFactorOperator.java
index a0e8cac3b9e..b834e954be5 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/FormFactorOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/FormFactorOperator.java
@@ -44,15 +44,35 @@ public class FormFactorOperator implements
AggregatedResultOperator {
@Override
public Set<String> getDeclaredIntermediateValueNames() {
+ return Collections.unmodifiableSet(
+ new HashSet<>(Arrays.asList("sum_x2", "sum_x1", "sum_abs_x1",
"count")));
+ }
+
+ @Override
+ public boolean supportsLegacyIntermediateResults() {
+ return true;
+ }
+
+ @Override
+ public Set<String> getLegacyIntermediateValueNames() {
return Collections.unmodifiableSet(new HashSet<>(Arrays.asList("sum_x2",
"sum_x1", "count")));
}
@Override
public Pair<TSDataType, Object> terminateWindow(
TSDataType measurementDataType, CustomizedReadableIntermediateResults
intermediateResults) {
+ if (intermediateResults.isLegacyStatisticsFormula()) {
+ return new Pair<>(
+ TSDataType.DOUBLE,
+ Math.pow(
+ intermediateResults.getDouble("sum_x2") /
intermediateResults.getLong("count"),
+ 0.5)
+ / (intermediateResults.getDouble("sum_x1") /
intermediateResults.getLong("count")));
+ }
return new Pair<>(
TSDataType.DOUBLE,
- Math.pow(intermediateResults.getDouble("sum_x2") /
intermediateResults.getInt("count"), 0.5)
- / (intermediateResults.getDouble("sum_x1") /
intermediateResults.getInt("count")));
+ Math.pow(
+ intermediateResults.getDouble("sum_x2") /
intermediateResults.getLong("count"), 0.5)
+ / (intermediateResults.getDouble("sum_abs_x1") /
intermediateResults.getLong("count")));
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/KurtosisOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/KurtosisOperator.java
index efd3025cf5c..452d72fae13 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/KurtosisOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/KurtosisOperator.java
@@ -55,7 +55,7 @@ public class KurtosisOperator implements
AggregatedResultOperator {
double sumX3 = intermediateResults.getDouble("sum_x3");
double sumX2 = intermediateResults.getDouble("sum_x2");
double sumX1 = intermediateResults.getDouble("sum_x1");
- int count = intermediateResults.getInt("count");
+ long count = intermediateResults.getLong("count");
return new Pair<>(
TSDataType.DOUBLE,
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/PeakOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/PeakOperator.java
index 55f60523e0d..cade1202a25 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/PeakOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/PeakOperator.java
@@ -48,6 +48,14 @@ public class PeakOperator implements
AggregatedResultOperator {
@Override
public Pair<TSDataType, Object> terminateWindow(
TSDataType measurementDataType, CustomizedReadableIntermediateResults
intermediateResults) {
- return new Pair<>(measurementDataType,
intermediateResults.getObject("abs_max"));
+ final Object absoluteMaximum =
+ switch (measurementDataType) {
+ case INT32 -> intermediateResults.getInt("abs_max");
+ case INT64 -> intermediateResults.getLong("abs_max");
+ case FLOAT -> intermediateResults.getFloat("abs_max");
+ case DOUBLE -> intermediateResults.getDouble("abs_max");
+ default -> intermediateResults.getObject("abs_max");
+ };
+ return new Pair<>(measurementDataType, absoluteMaximum);
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/PulseFactorOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/PulseFactorOperator.java
index aae68777728..aab040b0547 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/PulseFactorOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/PulseFactorOperator.java
@@ -44,15 +44,29 @@ public class PulseFactorOperator implements
AggregatedResultOperator {
@Override
public Set<String> getDeclaredIntermediateValueNames() {
+ return Collections.unmodifiableSet(
+ new HashSet<>(Arrays.asList("abs_max", "sum_x1", "sum_abs_x1",
"count")));
+ }
+
+ @Override
+ public boolean supportsLegacyIntermediateResults() {
+ return true;
+ }
+
+ @Override
+ public Set<String> getLegacyIntermediateValueNames() {
return Collections.unmodifiableSet(new HashSet<>(Arrays.asList("abs_max",
"sum_x1", "count")));
}
@Override
public Pair<TSDataType, Object> terminateWindow(
TSDataType measurementDataType, CustomizedReadableIntermediateResults
intermediateResults) {
+ final String averageAbsoluteValueName =
+ intermediateResults.isLegacyStatisticsFormula() ? "sum_x1" :
"sum_abs_x1";
return new Pair<>(
TSDataType.DOUBLE,
intermediateResults.getDouble("abs_max")
- / (intermediateResults.getDouble("sum_x1") /
intermediateResults.getInt("count")));
+ / (intermediateResults.getDouble(averageAbsoluteValueName)
+ / intermediateResults.getLong("count")));
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/RootMeanSquareOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/RootMeanSquareOperator.java
index 2937072946c..9f89052a632 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/RootMeanSquareOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/RootMeanSquareOperator.java
@@ -53,6 +53,6 @@ public class RootMeanSquareOperator implements
AggregatedResultOperator {
return new Pair<>(
TSDataType.DOUBLE,
Math.pow(
- intermediateResults.getDouble("sum_x2") /
intermediateResults.getInt("count"), 0.5));
+ intermediateResults.getDouble("sum_x2") /
intermediateResults.getLong("count"), 0.5));
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/SkewnessOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/SkewnessOperator.java
index 1fd61727e5f..823d4010ef1 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/SkewnessOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/SkewnessOperator.java
@@ -54,7 +54,7 @@ public class SkewnessOperator implements
AggregatedResultOperator {
double sumX3 = intermediateResults.getDouble("sum_x3");
double sumX2 = intermediateResults.getDouble("sum_x2");
double sumX1 = intermediateResults.getDouble("sum_x1");
- int count = intermediateResults.getInt("count");
+ long count = intermediateResults.getLong("count");
return new Pair<>(
TSDataType.DOUBLE,
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/VarianceOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/VarianceOperator.java
index 386618df635..c3edb6bd2f4 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/VarianceOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/aggregatedresult/standardstatistics/VarianceOperator.java
@@ -53,8 +53,8 @@ public class VarianceOperator implements
AggregatedResultOperator {
TSDataType measurementDataType, CustomizedReadableIntermediateResults
intermediateResults) {
return new Pair<>(
TSDataType.DOUBLE,
- intermediateResults.getDouble("sum_x2") /
intermediateResults.getInt("count")
+ intermediateResults.getDouble("sum_x2") /
intermediateResults.getLong("count")
- Math.pow(
- intermediateResults.getDouble("sum_x1") /
intermediateResults.getInt("count"), 2));
+ intermediateResults.getDouble("sum_x1") /
intermediateResults.getLong("count"), 2));
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/CustomizedReadableIntermediateResults.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/CustomizedReadableIntermediateResults.java
index c915bcbc174..a1c189443f3 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/CustomizedReadableIntermediateResults.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/CustomizedReadableIntermediateResults.java
@@ -34,10 +34,17 @@ import java.util.Map;
public class CustomizedReadableIntermediateResults {
private final Map<String, Pair<TSDataType, Object>> intermediateResults;
+ private final boolean legacyStatisticsFormula;
public CustomizedReadableIntermediateResults(
- final Map<String, Pair<TSDataType, Object>> intermediateResults) {
+ final Map<String, Pair<TSDataType, Object>> intermediateResults,
+ final boolean legacyStatisticsFormula) {
this.intermediateResults = intermediateResults;
+ this.legacyStatisticsFormula = legacyStatisticsFormula;
+ }
+
+ public boolean isLegacyStatisticsFormula() {
+ return legacyStatisticsFormula;
}
public boolean getBoolean(final String key) {
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/IntermediateResultOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/IntermediateResultOperator.java
index 95e1a9cb0d1..e5043bb0615 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/IntermediateResultOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/IntermediateResultOperator.java
@@ -43,6 +43,9 @@ import java.util.Map;
*/
public interface IntermediateResultOperator {
+ int LEGACY_STATE_FORMAT_VERSION = 0;
+ int CURRENT_STATE_FORMAT_VERSION = 1;
+
/**
* Return the name of the operator, the name shall be in lower case
*
@@ -121,4 +124,9 @@ public interface IntermediateResultOperator {
/** Deserialize the object from byteBuffer to allow shutdown restart */
void deserialize(final ByteBuffer byteBuffer) throws IOException;
+
+ default void deserialize(final ByteBuffer byteBuffer, final int
stateFormatVersion)
+ throws IOException {
+ deserialize(byteBuffer);
+ }
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/sametype/numeric/AbsoluteMaxOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/sametype/numeric/AbsoluteMaxOperator.java
index b121e4c9951..410eba1f02b 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/sametype/numeric/AbsoluteMaxOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/sametype/numeric/AbsoluteMaxOperator.java
@@ -19,6 +19,11 @@
package
org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.sametype.numeric;
+import org.apache.tsfile.enums.TSDataType;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
public class AbsoluteMaxOperator extends AbstractSameTypeNumericOperator {
@Override
public String getName() {
@@ -27,36 +32,64 @@ public class AbsoluteMaxOperator extends
AbstractSameTypeNumericOperator {
@Override
public boolean initAndGetIsSupport(final int initialInput, final long
initialTimestamp) {
- intValue = Math.abs(initialInput);
- return super.initAndGetIsSupport(initialInput, initialTimestamp);
+ if (initialInput == Integer.MIN_VALUE) {
+ doubleValue = -(double) initialInput;
+ outPutDataType = TSDataType.DOUBLE;
+ } else {
+ intValue = Math.abs(initialInput);
+ outPutDataType = TSDataType.INT32;
+ }
+ return true;
}
@Override
public boolean initAndGetIsSupport(final long initialInput, final long
initialTimestamp) {
- longValue = Math.abs(initialInput);
- return super.initAndGetIsSupport(initialInput, initialTimestamp);
+ if (initialInput == Long.MIN_VALUE) {
+ doubleValue = -(double) initialInput;
+ outPutDataType = TSDataType.DOUBLE;
+ } else {
+ longValue = Math.abs(initialInput);
+ outPutDataType = TSDataType.INT64;
+ }
+ return true;
}
@Override
public boolean initAndGetIsSupport(final float initialInput, final long
initialTimestamp) {
floatValue = Math.abs(initialInput);
- return super.initAndGetIsSupport(initialInput, initialTimestamp);
+ outPutDataType = TSDataType.FLOAT;
+ return true;
}
@Override
public boolean initAndGetIsSupport(final double initialInput, final long
initialTimestamp) {
doubleValue = Math.abs(initialInput);
- return super.initAndGetIsSupport(initialInput, initialTimestamp);
+ outPutDataType = TSDataType.DOUBLE;
+ return true;
}
@Override
public void updateValue(final int input, final long timestamp) {
- intValue = Math.max(intValue, Math.abs(input));
+ if (outPutDataType == TSDataType.DOUBLE) {
+ doubleValue = Math.max(doubleValue, Math.abs((double) input));
+ } else if (input == Integer.MIN_VALUE) {
+ doubleValue = -(double) input;
+ outPutDataType = TSDataType.DOUBLE;
+ } else {
+ intValue = Math.max(intValue, Math.abs(input));
+ }
}
@Override
public void updateValue(final long input, final long timestamp) {
- longValue = Math.max(longValue, Math.abs(input));
+ if (outPutDataType == TSDataType.DOUBLE) {
+ doubleValue = Math.max(doubleValue, Math.abs((double) input));
+ } else if (input == Long.MIN_VALUE) {
+ doubleValue = -(double) input;
+ outPutDataType = TSDataType.DOUBLE;
+ } else {
+ longValue = Math.max(longValue, Math.abs(input));
+ }
}
@Override
@@ -68,4 +101,35 @@ public class AbsoluteMaxOperator extends
AbstractSameTypeNumericOperator {
public void updateValue(final double input, final long timestamp) {
doubleValue = Math.max(doubleValue, Math.abs(input));
}
+
+ @Override
+ public void deserialize(final ByteBuffer byteBuffer) throws IOException {
+ super.deserialize(byteBuffer);
+ switch (outPutDataType) {
+ case INT32:
+ if (intValue == Integer.MIN_VALUE) {
+ doubleValue = -(double) intValue;
+ outPutDataType = TSDataType.DOUBLE;
+ } else {
+ intValue = Math.abs(intValue);
+ }
+ break;
+ case INT64:
+ if (longValue == Long.MIN_VALUE) {
+ doubleValue = -(double) longValue;
+ outPutDataType = TSDataType.DOUBLE;
+ } else {
+ longValue = Math.abs(longValue);
+ }
+ break;
+ case FLOAT:
+ floatValue = Math.abs(floatValue);
+ break;
+ case DOUBLE:
+ doubleValue = Math.abs(doubleValue);
+ break;
+ default:
+ throw new IOException();
+ }
+ }
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/sametype/numeric/IntegralPoweredSumOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/sametype/numeric/IntegralPoweredSumOperator.java
index f5b532319c1..00fe119d1e4 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/sametype/numeric/IntegralPoweredSumOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/sametype/numeric/IntegralPoweredSumOperator.java
@@ -19,6 +19,11 @@
package
org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.sametype.numeric;
+import org.apache.tsfile.enums.TSDataType;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
public class IntegralPoweredSumOperator extends
AbstractSameTypeNumericOperator {
private final transient int power;
@@ -33,45 +38,70 @@ public class IntegralPoweredSumOperator extends
AbstractSameTypeNumericOperator
@Override
public boolean initAndGetIsSupport(int initialInput, long initialTimestamp) {
- intValue = (int) Math.pow(initialInput, power);
- return super.initAndGetIsSupport(initialInput, initialTimestamp);
+ doubleValue = Math.pow(initialInput, power);
+ outPutDataType = TSDataType.DOUBLE;
+ return true;
}
@Override
public boolean initAndGetIsSupport(long initialInput, long initialTimestamp)
{
- longValue = (long) Math.pow(initialInput, power);
- return super.initAndGetIsSupport(initialInput, initialTimestamp);
+ doubleValue = Math.pow(initialInput, power);
+ outPutDataType = TSDataType.DOUBLE;
+ return true;
}
@Override
public boolean initAndGetIsSupport(float initialInput, long
initialTimestamp) {
- floatValue = (float) Math.pow(initialInput, power);
- return super.initAndGetIsSupport(initialInput, initialTimestamp);
+ doubleValue = Math.pow(initialInput, power);
+ outPutDataType = TSDataType.DOUBLE;
+ return true;
}
@Override
public boolean initAndGetIsSupport(double initialInput, long
initialTimestamp) {
doubleValue = Math.pow(initialInput, power);
- return super.initAndGetIsSupport(initialInput, initialTimestamp);
+ outPutDataType = TSDataType.DOUBLE;
+ return true;
}
@Override
public void updateValue(int input, long timestamp) {
- intValue += (int) Math.pow(input, power);
+ doubleValue += Math.pow(input, power);
}
@Override
public void updateValue(long input, long timestamp) {
- longValue += (long) Math.pow(input, power);
+ doubleValue += Math.pow(input, power);
}
@Override
public void updateValue(float input, long timestamp) {
- floatValue += (float) Math.pow(input, power);
+ doubleValue += Math.pow(input, power);
}
@Override
public void updateValue(double input, long timestamp) {
doubleValue += Math.pow(input, power);
}
+
+ @Override
+ public void deserialize(final ByteBuffer byteBuffer) throws IOException {
+ super.deserialize(byteBuffer);
+ switch (outPutDataType) {
+ case INT32:
+ doubleValue = intValue;
+ break;
+ case INT64:
+ doubleValue = longValue;
+ break;
+ case FLOAT:
+ doubleValue = floatValue;
+ break;
+ case DOUBLE:
+ break;
+ default:
+ throw new IOException();
+ }
+ outPutDataType = TSDataType.DOUBLE;
+ }
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/specifictype/doubletype/FractionPoweredSumOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/specifictype/doubletype/FractionPoweredSumOperator.java
index a49d90c6ede..3fbdc4a502b 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/specifictype/doubletype/FractionPoweredSumOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/specifictype/doubletype/FractionPoweredSumOperator.java
@@ -35,6 +35,7 @@ import java.util.Map;
public class FractionPoweredSumOperator implements IntermediateResultOperator {
private double sum;
private final transient double power;
+ private final transient boolean absolute;
/**
* Warning: Do not use fraction values like "1/3" to initiate the operator,
unless you know what
@@ -44,12 +45,25 @@ public class FractionPoweredSumOperator implements
IntermediateResultOperator {
* @param power the power to use
*/
public FractionPoweredSumOperator(final double power) {
+ this(power, false);
+ }
+
+ public FractionPoweredSumOperator(final double power, final boolean
absolute) {
this.power = power;
+ this.absolute = absolute;
}
@Override
public String getName() {
- return "sum_x" + power;
+ return "sum_" + (absolute ? "abs_" : "") + "x" + formatPower(power);
+ }
+
+ private static String formatPower(final double power) {
+ return power == (int) power ? Integer.toString((int) power) :
Double.toString(power);
+ }
+
+ private double poweredValue(final double value) {
+ return Math.pow(absolute ? Math.abs(value) : value, power);
}
@Override
@@ -64,7 +78,7 @@ public class FractionPoweredSumOperator implements
IntermediateResultOperator {
@Override
public boolean initAndGetIsSupport(final int initialInput, final long
initialTimestamp) {
- sum = Math.pow(initialInput, power);
+ sum = poweredValue(initialInput);
return true;
}
@@ -75,19 +89,19 @@ public class FractionPoweredSumOperator implements
IntermediateResultOperator {
@Override
public boolean initAndGetIsSupport(final long initialInput, final long
initialTimestamp) {
- sum = Math.pow(initialInput, power);
+ sum = poweredValue(initialInput);
return true;
}
@Override
public boolean initAndGetIsSupport(final float initialInput, final long
initialTimestamp) {
- sum = Math.pow(initialInput, power);
+ sum = poweredValue(initialInput);
return true;
}
@Override
public boolean initAndGetIsSupport(final double initialInput, final long
initialTimestamp) {
- sum = Math.pow(initialInput, power);
+ sum = poweredValue(initialInput);
return true;
}
@@ -109,7 +123,7 @@ public class FractionPoweredSumOperator implements
IntermediateResultOperator {
@Override
public void updateValue(final int input, final long timestamp) {
- sum += Math.pow(input, power);
+ sum += poweredValue(input);
}
@Override
@@ -120,17 +134,17 @@ public class FractionPoweredSumOperator implements
IntermediateResultOperator {
@Override
public void updateValue(final long input, final long timestamp) {
- sum += Math.pow(input, power);
+ sum += poweredValue(input);
}
@Override
public void updateValue(final float input, final long timestamp) {
- sum += Math.pow(input, power);
+ sum += poweredValue(input);
}
@Override
public void updateValue(final double input, final long timestamp) {
- sum += Math.pow(input, power);
+ sum += poweredValue(input);
}
@Override
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/specifictype/integertype/CountOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/specifictype/integertype/CountOperator.java
index a42dfa17942..e895921c517 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/specifictype/integertype/CountOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/intermediateresult/specifictype/integertype/CountOperator.java
@@ -33,7 +33,7 @@ import java.time.LocalDate;
import java.util.Map;
public class CountOperator implements IntermediateResultOperator {
- private int count;
+ private long count;
@Override
public String getName() {
@@ -135,7 +135,7 @@ public class CountOperator implements
IntermediateResultOperator {
@Override
public Pair<TSDataType, Object> getResult() {
- return new Pair<>(TSDataType.INT32, count);
+ return new Pair<>(TSDataType.INT64, count);
}
@Override
@@ -145,6 +145,15 @@ public class CountOperator implements
IntermediateResultOperator {
@Override
public void deserialize(final ByteBuffer byteBuffer) throws IOException {
- count = ReadWriteIOUtils.readInt(byteBuffer);
+ count = ReadWriteIOUtils.readLong(byteBuffer);
+ }
+
+ @Override
+ public void deserialize(final ByteBuffer byteBuffer, final int
stateFormatVersion)
+ throws IOException {
+ count =
+ stateFormatVersion == LEGACY_STATE_FORMAT_VERSION
+ ? ReadWriteIOUtils.readInt(byteBuffer)
+ : ReadWriteIOUtils.readLong(byteBuffer);
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/processor/StandardStatisticsOperatorProcessor.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/processor/StandardStatisticsOperatorProcessor.java
index 3d3250088f8..4c92a6387e9 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/processor/StandardStatisticsOperatorProcessor.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/operator/processor/StandardStatisticsOperatorProcessor.java
@@ -73,6 +73,8 @@ public class StandardStatisticsOperatorProcessor extends
AbstractOperatorProcess
Arrays.asList(
AbsoluteMaxOperator::new,
CountOperator::new,
+ () -> new FractionPoweredSumOperator(1, true),
+ () -> new FractionPoweredSumOperator(0.5, true),
() -> new FractionPoweredSumOperator(0.5),
() -> new IntegralPoweredSumOperator(1),
() -> new IntegralPoweredSumOperator(2),
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/window/datastructure/TimeSeriesWindow.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/window/datastructure/TimeSeriesWindow.java
index 6cd046fb594..6309c1b5f79 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/window/datastructure/TimeSeriesWindow.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/processor/aggregate/window/datastructure/TimeSeriesWindow.java
@@ -37,18 +37,24 @@ import java.nio.ByteBuffer;
import java.time.LocalDate;
import java.util.Collections;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
+import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class TimeSeriesWindow {
private static final Logger LOGGER =
LoggerFactory.getLogger(TimeSeriesWindow.class);
+ private static final int STATE_FORMAT_MARKER = -1;
+ private static final int PREVIOUS_STATE_FORMAT_VERSION = 1;
+ private static final int CURRENT_STATE_FORMAT_VERSION = 2;
// A window is typically with a timestamp. We define it here to avoid
// boxing/unboxing and simplify the logics.
private long timestamp = 0;
+ private boolean legacyStatisticsFormula;
private Map<String, AggregatedResultOperator>
aggregatedOutputName2OperatorMap;
private final Map<String, Pair<TSDataType, IntermediateResultOperator>>
intermediateResultName2tsTypeAndOperatorMap = new HashMap<>();
@@ -566,8 +572,20 @@ public class TimeSeriesWindow {
intermediateResultName2tsTypeAndOperatorMap.entrySet().stream()
.collect(
Collectors.toMap(
- Map.Entry::getKey, entry ->
entry.getValue().getRight().getResult())));
+ Map.Entry::getKey, entry ->
entry.getValue().getRight().getResult())),
+ legacyStatisticsFormula);
return aggregatedOutputName2OperatorMap.entrySet().stream()
+ .filter(
+ entry -> {
+ final AggregatedResultOperator operator = entry.getValue();
+ final Set<String> requiredIntermediateResultNames =
+ legacyStatisticsFormula &&
operator.supportsLegacyIntermediateResults()
+ ? operator.getLegacyIntermediateValueNames()
+ : operator.getDeclaredIntermediateValueNames();
+ return intermediateResultName2tsTypeAndOperatorMap
+ .keySet()
+ .containsAll(requiredIntermediateResultNames);
+ })
.collect(
Collectors.toMap(
Map.Entry::getKey,
@@ -578,6 +596,9 @@ public class TimeSeriesWindow {
public void serialize(final DataOutputStream outputStream) throws
IOException {
ReadWriteIOUtils.write(timestamp, outputStream);
+ ReadWriteIOUtils.write(STATE_FORMAT_MARKER, outputStream);
+ ReadWriteIOUtils.write(CURRENT_STATE_FORMAT_VERSION, outputStream);
+ ReadWriteIOUtils.write(legacyStatisticsFormula ? 1 : 0, outputStream);
ReadWriteIOUtils.write(intermediateResultName2tsTypeAndOperatorMap.size(),
outputStream);
for (final Map.Entry<String, Pair<TSDataType, IntermediateResultOperator>>
entry :
intermediateResultName2tsTypeAndOperatorMap.entrySet()) {
@@ -596,15 +617,51 @@ public class TimeSeriesWindow {
// processor, only adding intermediate values is permitted.
public void deserialize(final ByteBuffer byteBuffer) throws IOException {
timestamp = ReadWriteIOUtils.readLong(byteBuffer);
- final int size = ReadWriteIOUtils.readInt(byteBuffer);
+ final int sizeOrFormatMarker = ReadWriteIOUtils.readInt(byteBuffer);
+ final int stateFormatVersion;
+ final int size;
+ if (sizeOrFormatMarker == STATE_FORMAT_MARKER) {
+ final int windowStateFormatVersion =
ReadWriteIOUtils.readInt(byteBuffer);
+ if (windowStateFormatVersion == PREVIOUS_STATE_FORMAT_VERSION) {
+ legacyStatisticsFormula = true;
+ stateFormatVersion =
IntermediateResultOperator.CURRENT_STATE_FORMAT_VERSION;
+ size = ReadWriteIOUtils.readInt(byteBuffer);
+ } else if (windowStateFormatVersion == CURRENT_STATE_FORMAT_VERSION) {
+ final int legacyStatisticsFormulaFlag =
ReadWriteIOUtils.readInt(byteBuffer);
+ if (legacyStatisticsFormulaFlag != 0 && legacyStatisticsFormulaFlag !=
1) {
+ throw new IOException();
+ }
+ legacyStatisticsFormula = legacyStatisticsFormulaFlag == 1;
+ stateFormatVersion =
IntermediateResultOperator.CURRENT_STATE_FORMAT_VERSION;
+ size = ReadWriteIOUtils.readInt(byteBuffer);
+ } else {
+ throw new IOException();
+ }
+ } else if (sizeOrFormatMarker >= 0) {
+ legacyStatisticsFormula = true;
+ stateFormatVersion =
IntermediateResultOperator.LEGACY_STATE_FORMAT_VERSION;
+ size = sizeOrFormatMarker;
+ } else {
+ throw new IOException();
+ }
+ final Set<String> restoredIntermediateResultNames = new HashSet<>();
for (int i = 0; i < size; i++) {
final String intermediateResultName =
ReadWriteIOUtils.readString(byteBuffer);
final Pair<TSDataType, IntermediateResultOperator>
initializedAndOperatorPair =
intermediateResultName2tsTypeAndOperatorMap.get(intermediateResultName);
- if (Objects.nonNull(initializedAndOperatorPair)) {
-
initializedAndOperatorPair.setLeft(TSDataType.deserializeFrom(byteBuffer));
- initializedAndOperatorPair.getRight().deserialize(byteBuffer);
+ if (Objects.isNull(initializedAndOperatorPair)) {
+ throw new IOException();
}
+ restoredIntermediateResultNames.add(intermediateResultName);
+
initializedAndOperatorPair.setLeft(TSDataType.deserializeFrom(byteBuffer));
+ initializedAndOperatorPair.getRight().deserialize(byteBuffer,
stateFormatVersion);
+ }
+ if (legacyStatisticsFormula) {
+ intermediateResultName2tsTypeAndOperatorMap
+ .keySet()
+ .removeIf(
+ intermediateResultName ->
+
!restoredIntermediateResultNames.contains(intermediateResultName));
}
processor.deserializeCustomizedAttributes(this, byteBuffer);
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileSource.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileSource.java
index 9943db71b80..a28e726772b 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileSource.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileSource.java
@@ -567,7 +567,7 @@ public class PipeHistoricalDataRegionTsFileSource
implements PipeHistoricalDataR
resourceList.sort(
(o1, o2) ->
- getInnerProgressIndex(startIndex) instanceof
TimeWindowStateProgressIndex
+ getTimeWindowStateProgressIndex(startIndex) != null
? Long.compare(o1.getFileStartTime(), o2.getFileStartTime())
:
o1.getMaxProgressIndex().topologicalCompareTo(o2.getMaxProgressIndex()));
}
@@ -649,10 +649,11 @@ public class PipeHistoricalDataRegionTsFileSource
implements PipeHistoricalDataR
private boolean mayTsFileContainUnprocessedData(final TsFileResource
resource) {
final ProgressIndex innerStartIndex = getInnerProgressIndex(startIndex);
- if (innerStartIndex instanceof TimeWindowStateProgressIndex) {
+ final TimeWindowStateProgressIndex timeWindowStateProgressIndex =
+ getTimeWindowStateProgressIndex(startIndex);
+ if (Objects.nonNull(timeWindowStateProgressIndex)) {
// The resource is closed thus the TsFileResource#getFileEndTime() is
safe to use
- return ((TimeWindowStateProgressIndex) innerStartIndex).getMinTime()
- <= resource.getFileEndTime();
+ return timeWindowStateProgressIndex.getMinTime() <=
resource.getFileEndTime();
}
final ProgressIndex resourceProgressIndex = resource.getMaxProgressIndex();
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/aggregate/AggregateProcessorTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/aggregate/AggregateProcessorTest.java
new file mode 100644
index 00000000000..69bbd24c8e0
--- /dev/null
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/aggregate/AggregateProcessorTest.java
@@ -0,0 +1,612 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.iotdb.db.pipe.processor.aggregate;
+
+import org.apache.iotdb.commons.consensus.index.ProgressIndex;
+import org.apache.iotdb.commons.consensus.index.ProgressIndexType;
+import
org.apache.iotdb.commons.consensus.index.impl.TimeWindowStateProgressIndex;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.aggregatedresult.AggregatedResultOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.aggregatedresult.standardstatistics.AverageOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.aggregatedresult.standardstatistics.ClearanceFactorOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.aggregatedresult.standardstatistics.FormFactorOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.aggregatedresult.standardstatistics.PeakOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.aggregatedresult.standardstatistics.PulseFactorOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.CustomizedReadableIntermediateResults;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.IntermediateResultOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.sametype.numeric.AbsoluteMaxOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.sametype.numeric.IntegralPoweredSumOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.specifictype.doubletype.FractionPoweredSumOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.operator.intermediateresult.specifictype.integertype.CountOperator;
+import
org.apache.iotdb.db.pipe.processor.aggregate.window.datastructure.TimeSeriesWindow;
+import
org.apache.iotdb.db.pipe.processor.aggregate.window.datastructure.WindowOutput;
+import
org.apache.iotdb.db.pipe.processor.aggregate.window.processor.TumblingWindowingProcessor;
+import org.apache.iotdb.db.utils.TimestampPrecisionUtils;
+import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameterValidator;
+import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameters;
+import org.apache.iotdb.pipe.api.exception.PipeParameterNotValidException;
+
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.utils.Pair;
+import org.apache.tsfile.utils.PublicBAOS;
+import org.apache.tsfile.utils.ReadWriteIOUtils;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+
+import static
org.apache.iotdb.commons.pipe.config.constant.PipeProcessorConstant.PROCESSOR_OPERATORS_KEY;
+import static
org.apache.iotdb.commons.pipe.config.constant.PipeProcessorConstant.PROCESSOR_OUTPUT_MEASUREMENTS_KEY;
+import static
org.apache.iotdb.commons.pipe.config.constant.PipeProcessorConstant.PROCESSOR_SLIDING_BOUNDARY_TIME_KEY;
+import static
org.apache.iotdb.commons.pipe.config.constant.PipeProcessorConstant.PROCESSOR_SLIDING_SECONDS_KEY;
+
+public class AggregateProcessorTest {
+
+ @Test(expected = PipeParameterNotValidException.class)
+ public void testRejectsDuplicateOperatorNamesIgnoringCase() throws Exception
{
+ validate("avg,AVG", "");
+ }
+
+ @Test(expected = PipeParameterNotValidException.class)
+ public void testRejectsEmptyOperatorNames() throws Exception {
+ validate("avg,", "");
+ }
+
+ @Test(expected = PipeParameterNotValidException.class)
+ public void testRejectsDuplicateOutputMeasurements() throws Exception {
+ validate("avg,max", "result,result");
+ }
+
+ @Test(expected = PipeParameterNotValidException.class)
+ public void testRejectsOutputMeasurementCollidingWithDefaultName() throws
Exception {
+ validate("avg,max", "max");
+ }
+
+ @Test(expected = PipeParameterNotValidException.class)
+ public void testRejectsEmptyOutputMeasurements() throws Exception {
+ validate("avg,max", "result,");
+ }
+
+ @Test(expected = PipeParameterNotValidException.class)
+ public void testRejectsMoreOutputMeasurementsThanOperators() throws
Exception {
+ validate("avg,max", "avg,max,extra");
+ }
+
+ @Test
+ public void testStripDatabasePrefixTreatsRegexCharactersLiterally() {
+ Assert.assertEquals(
+ "device", AggregateProcessor.stripDatabasePrefix("root.db$.device",
"root.db$."));
+ Assert.assertEquals(
+ "root.dbx.device",
AggregateProcessor.stripDatabasePrefix("root.dbx.device", "root.db$."));
+ }
+
+ @Test
+ public void testStripDatabasePrefixOnlyAtTheBeginning() {
+ Assert.assertEquals(
+ "device.root.db.device",
+ AggregateProcessor.stripDatabasePrefix("device.root.db.device",
"root.db."));
+ }
+
+ @Test
+ public void testSecondsToMillisecondsSaturatesOnOverflow() {
+ Assert.assertEquals(Long.MAX_VALUE,
AggregateProcessor.secondsToMilliseconds(Long.MAX_VALUE));
+ Assert.assertEquals(Long.MIN_VALUE,
AggregateProcessor.secondsToMilliseconds(Long.MIN_VALUE));
+ }
+
+ @Test
+ public void testDeduplicatesMinimumTimestamp() {
+ final List<WindowOutput> outputs =
+ new ArrayList<>(
+ Arrays.asList(
+ new WindowOutput().setTimestamp(Long.MIN_VALUE),
+ new WindowOutput().setTimestamp(Long.MIN_VALUE),
+ new WindowOutput().setTimestamp(0)));
+
+ final List<WindowOutput> distinctOutputs =
+ AggregateProcessor.sortAndDeduplicateOutputs(outputs);
+
+ Assert.assertEquals(2, distinctOutputs.size());
+ Assert.assertEquals(Long.MIN_VALUE, distinctOutputs.get(0).getTimestamp());
+ Assert.assertEquals(0L, distinctOutputs.get(1).getTimestamp());
+ }
+
+ @Test
+ public void testMinimumTimestampCreatesFirstWindow() throws Exception {
+ final TumblingWindowingProcessor windowingProcessor =
+ createWindowingProcessor(Long.MIN_VALUE, 1);
+ final TimeSeriesRuntimeState state =
+ new TimeSeriesRuntimeState(
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ windowingProcessor);
+
+ state.updateWindows(Long.MIN_VALUE, 1, 0);
+
+ final List<WindowOutput> outputs = state.forceOutput();
+ Assert.assertEquals(1, outputs.size());
+ Assert.assertEquals(Long.MIN_VALUE, outputs.get(0).getTimestamp());
+ }
+
+ @Test
+ public void testLegacyWindowStatePromotesCountAndMomentSums() throws
Exception {
+ final TumblingWindowingProcessor windowingProcessor =
createWindowingProcessor(0, 1);
+ final Map<String, Supplier<IntermediateResultOperator>>
intermediateOperators = new HashMap<>();
+ intermediateOperators.put("count", CountOperator::new);
+ intermediateOperators.put("sum_x1", () -> new
IntegralPoweredSumOperator(1));
+ final Map<String, AggregatedResultOperator> aggregatedOperators =
+ Collections.singletonMap("avg", new AverageOperator());
+ final TimeSeriesWindow window = new TimeSeriesWindow(windowingProcessor,
null);
+ window.initWindow(intermediateOperators, aggregatedOperators,
Collections.emptyMap());
+ final ByteBuffer legacyState = serializeLegacyWindow(0, Integer.MAX_VALUE,
Integer.MAX_VALUE);
+ final ByteBuffer legacyStateReader = legacyState.duplicate();
+ Assert.assertEquals(0L, ReadWriteIOUtils.readLong(legacyStateReader));
+ Assert.assertEquals(2, ReadWriteIOUtils.readInt(legacyStateReader));
+ Assert.assertEquals("count",
ReadWriteIOUtils.readString(legacyStateReader));
+ Assert.assertEquals(TSDataType.INT32,
TSDataType.deserializeFrom(legacyStateReader));
+ final CountOperator countOperator = new CountOperator();
+ countOperator.deserialize(
+ legacyStateReader,
IntermediateResultOperator.LEGACY_STATE_FORMAT_VERSION);
+ Assert.assertEquals(
+ Integer.MAX_VALUE, ((Number)
countOperator.getResult().getRight()).longValue());
+ Assert.assertEquals("sum_x1",
ReadWriteIOUtils.readString(legacyStateReader));
+ Assert.assertEquals(TSDataType.INT32,
TSDataType.deserializeFrom(legacyStateReader));
+ final IntegralPoweredSumOperator sumOperator = new
IntegralPoweredSumOperator(1);
+ sumOperator.deserialize(legacyStateReader);
+ Assert.assertEquals(
+ (double) Integer.MAX_VALUE, (double)
sumOperator.getResult().getRight(), 0.0);
+ window.deserialize(legacyState);
+
+ window.updateIntermediateResult(1, 1);
+ Assert.assertEquals(
+ 1.0, (double)
window.forceOutput().getAggregatedResults().get("avg").getRight(), 0.0);
+
+ final ByteBuffer currentState;
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ window.serialize(outputStream);
+ currentState = ByteBuffer.wrap(output.getBuf(), 0, output.size());
+ }
+ final TimeSeriesWindow restoredWindow = new
TimeSeriesWindow(windowingProcessor, null);
+ restoredWindow.initWindow(intermediateOperators, aggregatedOperators,
Collections.emptyMap());
+ restoredWindow.deserialize(currentState);
+ Assert.assertEquals(
+ 1.0,
+ (double)
restoredWindow.forceOutput().getAggregatedResults().get("avg").getRight(),
+ 0.0);
+ }
+
+ @Test
+ public void testMagnitudeFactorsHandleNegativeValues() throws Exception {
+ final TumblingWindowingProcessor windowingProcessor =
createWindowingProcessor(0, 1);
+ final TimeSeriesWindow window = new TimeSeriesWindow(windowingProcessor,
null);
+ window.initWindow(
+ createFactorIntermediateOperators(),
+ createFactorAggregatedOperators(),
+ Collections.emptyMap());
+
+ window.updateIntermediateResult(0, -2);
+ window.updateIntermediateResult(1, 4);
+
+ final Map<String, Pair<TSDataType, Object>> results =
+ window.forceOutput().getAggregatedResults();
+ Assert.assertEquals(Math.sqrt(10) / 3, (double)
results.get("ff").getRight(), 1e-12);
+ Assert.assertEquals(4.0 / 3, (double) results.get("pf").getRight(), 1e-12);
+ Assert.assertEquals(
+ 4.0 / Math.pow((Math.sqrt(2) + 2) / 2, 2), (double)
results.get("ce").getRight(), 1e-12);
+ }
+
+ @Test
+ public void testLegacyFactorWindowKeepsFormulaAcrossRestore() throws
Exception {
+ final TumblingWindowingProcessor windowingProcessor =
createWindowingProcessor(0, 1);
+ final Map<String, Supplier<IntermediateResultOperator>>
intermediateOperators =
+ createFactorIntermediateOperators();
+ final Map<String, AggregatedResultOperator> aggregatedOperators =
+ createFactorAggregatedOperators();
+ final List<String> requiredIntermediateResultNames =
+ aggregatedOperators.values().stream()
+ .flatMap(operator ->
operator.getDeclaredIntermediateValueNames().stream())
+ .collect(Collectors.toList());
+ intermediateOperators.keySet().retainAll(requiredIntermediateResultNames);
+ final TimeSeriesWindow window = new TimeSeriesWindow(windowingProcessor,
null);
+ window.initWindow(intermediateOperators, aggregatedOperators,
Collections.emptyMap());
+ window.deserialize(serializeLegacyFactorWindow());
+ Assert.assertTrue(
+ "Expected the legacy clearance factor to be NaN immediately after
restore, got "
+ + window.forceOutput().getAggregatedResults().get("ce").getRight(),
+ Double.isNaN((double)
window.forceOutput().getAggregatedResults().get("ce").getRight()));
+
+ window.updateIntermediateResult(2, 5);
+ final Map<String, Pair<TSDataType, Object>> results =
+ window.forceOutput().getAggregatedResults();
+ Assert.assertEquals(Math.sqrt(15) / (7.0 / 3), (double)
results.get("ff").getRight(), 1e-12);
+ Assert.assertEquals(15.0 / 7, (double) results.get("pf").getRight(),
1e-12);
+ Assert.assertTrue(
+ "Expected the legacy clearance factor to remain NaN, got " +
results.get("ce").getRight(),
+ Double.isNaN((double) results.get("ce").getRight()));
+
+ final ByteBuffer currentState;
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ window.serialize(outputStream);
+ currentState = ByteBuffer.wrap(output.getBuf(), 0, output.size());
+ }
+ final TimeSeriesWindow restoredWindow = new
TimeSeriesWindow(windowingProcessor, null);
+ restoredWindow.initWindow(intermediateOperators, aggregatedOperators,
Collections.emptyMap());
+ restoredWindow.deserialize(currentState);
+ Assert.assertEquals(
+ 15.0 / 7,
+ (double)
restoredWindow.forceOutput().getAggregatedResults().get("pf").getRight(),
+ 1e-12);
+ }
+
+ @Test
+ public void testLegacyFactorWindowSkipsAggregatorsWithoutRestoredInputs()
throws Exception {
+ final TumblingWindowingProcessor windowingProcessor =
createWindowingProcessor(0, 1);
+ final TimeSeriesWindow window = new TimeSeriesWindow(windowingProcessor,
null);
+ window.initWindow(
+ createFactorIntermediateOperators(),
+ createFactorAggregatedOperators(),
+ Collections.emptyMap());
+ window.deserialize(serializeLegacyCountWindow());
+
+ Assert.assertTrue(window.forceOutput().getAggregatedResults().isEmpty());
+ }
+
+ @Test(expected = IOException.class)
+ public void testLegacyWindowStateRejectsRemovedIntermediateResult() throws
Exception {
+ final TumblingWindowingProcessor windowingProcessor =
createWindowingProcessor(0, 1);
+ final TimeSeriesWindow window = new TimeSeriesWindow(windowingProcessor,
null);
+ window.initWindow(
+ Collections.singletonMap("count", CountOperator::new),
+ Collections.emptyMap(),
+ Collections.emptyMap());
+
+ window.deserialize(serializeLegacyWindow(0, 1, 1));
+ }
+
+ @Test
+ public void testIntegralPoweredSumAvoidsIntegerOverflow() {
+ final IntegralPoweredSumOperator sumOfSquares = new
IntegralPoweredSumOperator(2);
+ Assert.assertTrue(sumOfSquares.initAndGetIsSupport(50_000, 0));
+ sumOfSquares.updateValue(50_000, 1);
+
+ Assert.assertEquals(5_000_000_000.0, (double)
sumOfSquares.getResult().getRight(), 0.0);
+ }
+
+ @Test
+ public void testAbsoluteMaxHandlesMinimumIntegerAndLegacyState() throws
IOException {
+ final AbsoluteMaxOperator absoluteMaxOperator = new AbsoluteMaxOperator();
+
Assert.assertTrue(absoluteMaxOperator.initAndGetIsSupport(Integer.MIN_VALUE,
0));
+ Assert.assertEquals(TSDataType.DOUBLE,
absoluteMaxOperator.getResult().getLeft());
+ Assert.assertEquals(2_147_483_648.0, (double)
absoluteMaxOperator.getResult().getRight(), 0.0);
+
+ final ByteBuffer legacyState;
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ TSDataType.INT32.serializeTo(outputStream);
+ ReadWriteIOUtils.write(Integer.MIN_VALUE, outputStream);
+ legacyState = ByteBuffer.wrap(output.getBuf(), 0, output.size());
+ }
+ absoluteMaxOperator.deserialize(legacyState);
+ Assert.assertEquals(2_147_483_648.0, (double)
absoluteMaxOperator.getResult().getRight(), 0.0);
+ }
+
+ @Test
+ public void testPeakPreservesInputTypeAndIntegerPrecision() throws
IOException {
+ final AbsoluteMaxOperator intAbsoluteMax = new AbsoluteMaxOperator();
+ Assert.assertTrue(intAbsoluteMax.initAndGetIsSupport(-17, 0));
+ Assert.assertEquals(17, intAbsoluteMax.getResult().getRight());
+ final Pair<TSDataType, Object> intPeak = terminatePeak(TSDataType.INT32,
intAbsoluteMax);
+ Assert.assertEquals(TSDataType.INT32, intPeak.getLeft());
+ Assert.assertEquals(17, intPeak.getRight());
+
+ final AbsoluteMaxOperator minimumIntAbsoluteMax = new
AbsoluteMaxOperator();
+
Assert.assertTrue(minimumIntAbsoluteMax.initAndGetIsSupport(Integer.MIN_VALUE,
0));
+ final Pair<TSDataType, Object> minimumIntPeak =
+ terminatePeak(TSDataType.INT32, minimumIntAbsoluteMax);
+ Assert.assertEquals(TSDataType.INT32, minimumIntPeak.getLeft());
+ Assert.assertEquals(Integer.MAX_VALUE, minimumIntPeak.getRight());
+
+ final long largeLongValue = Long.MAX_VALUE - 1024;
+ final AbsoluteMaxOperator longAbsoluteMax = new AbsoluteMaxOperator();
+ Assert.assertTrue(longAbsoluteMax.initAndGetIsSupport(-largeLongValue, 0));
+ Assert.assertEquals(TSDataType.INT64,
longAbsoluteMax.getResult().getLeft());
+
+ final ByteBuffer serializedState;
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ longAbsoluteMax.serialize(outputStream);
+ serializedState = ByteBuffer.wrap(output.getBuf(), 0, output.size());
+ }
+ final AbsoluteMaxOperator restoredLongAbsoluteMax = new
AbsoluteMaxOperator();
+ restoredLongAbsoluteMax.deserialize(serializedState);
+ final Pair<TSDataType, Object> longPeak =
+ terminatePeak(TSDataType.INT64, restoredLongAbsoluteMax);
+ Assert.assertEquals(TSDataType.INT64, longPeak.getLeft());
+ Assert.assertEquals(largeLongValue, longPeak.getRight());
+ }
+
+ @Test
+ public void testPeakSaturatesLongMinimumAfterCheckpointRestore() throws
IOException {
+ final AbsoluteMaxOperator absoluteMaxOperator = new AbsoluteMaxOperator();
+ Assert.assertTrue(absoluteMaxOperator.initAndGetIsSupport(Long.MIN_VALUE,
0));
+ Assert.assertEquals(
+ 9_223_372_036_854_775_808.0, (double)
absoluteMaxOperator.getResult().getRight(), 0.0);
+
+ final ByteBuffer serializedState;
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ absoluteMaxOperator.serialize(outputStream);
+ serializedState = ByteBuffer.wrap(output.getBuf(), 0, output.size());
+ }
+ final AbsoluteMaxOperator restoredAbsoluteMaxOperator = new
AbsoluteMaxOperator();
+ restoredAbsoluteMaxOperator.deserialize(serializedState);
+ Assert.assertEquals(TSDataType.DOUBLE,
restoredAbsoluteMaxOperator.getResult().getLeft());
+ Assert.assertEquals(
+ 9_223_372_036_854_775_808.0,
+ (double) restoredAbsoluteMaxOperator.getResult().getRight(),
+ 0.0);
+ restoredAbsoluteMaxOperator.updateValue(Long.MAX_VALUE, 1);
+
+ final Pair<TSDataType, Object> peak =
+ terminatePeak(TSDataType.INT64, restoredAbsoluteMaxOperator);
+ Assert.assertEquals(TSDataType.INT64, peak.getLeft());
+ Assert.assertEquals(Long.MAX_VALUE, peak.getRight());
+ }
+
+ @Test
+ public void testNewerRestoredStateReplacesOlderWindows() throws IOException {
+ final TumblingWindowingProcessor windowingProcessor = new
TumblingWindowingProcessor();
+ final TimeSeriesRuntimeState state =
+ new TimeSeriesRuntimeState(
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ windowingProcessor);
+
+ state.restoreTimestampAndWindows(new Pair<>(10L,
serializeWindow(windowingProcessor, 100L)));
+ state.restoreTimestampAndWindows(new Pair<>(20L,
serializeWindow(windowingProcessor, 200L)));
+
+ final List<WindowOutput> outputs = state.forceOutput();
+ Assert.assertEquals(1, outputs.size());
+ Assert.assertEquals(200L, outputs.get(0).getTimestamp());
+ }
+
+ @Test
+ public void testNewerRestoredStateWithoutBufferClearsOlderWindows() throws
IOException {
+ final TumblingWindowingProcessor windowingProcessor = new
TumblingWindowingProcessor();
+ final TimeSeriesRuntimeState state =
+ new TimeSeriesRuntimeState(
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ Collections.emptyMap(),
+ windowingProcessor);
+
+ state.restoreTimestampAndWindows(new Pair<>(10L,
serializeWindow(windowingProcessor, 100L)));
+ state.restoreTimestampAndWindows(new Pair<>(20L, null));
+
+ Assert.assertTrue(state.forceOutput().isEmpty());
+ }
+
+ @Test
+ public void
testReportedWindowProgressIndexRestoresOpenWindowAfterSerialization()
+ throws Exception {
+ final long interval = TimestampPrecisionUtils.convertToCurrPrecision(1,
TimeUnit.SECONDS);
+ final TumblingWindowingProcessor windowingProcessor =
createWindowingProcessor(0, 1);
+ final Map<String, Supplier<IntermediateResultOperator>>
intermediateOperators = new HashMap<>();
+ intermediateOperators.put("count", CountOperator::new);
+ intermediateOperators.put("sum_x1", () -> new
IntegralPoweredSumOperator(1));
+ final Map<String, AggregatedResultOperator> aggregatedOperators =
+ Collections.singletonMap("avg", new AverageOperator());
+ final TimeSeriesRuntimeState runtimeState =
+ new TimeSeriesRuntimeState(
+ aggregatedOperators, intermediateOperators,
Collections.emptyMap(), windowingProcessor);
+
+ Assert.assertNull(runtimeState.updateWindows(0, 10, 0));
+ final Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> reportedState =
+ runtimeState.updateWindows(interval, 20, 0);
+ Assert.assertNotNull(reportedState);
+ Assert.assertEquals(
+ 10.0,
+ (double)
reportedState.getLeft().get(0).getAggregatedResults().get("avg").getRight(),
+ 0.0);
+ Assert.assertNotNull(reportedState.getRight());
+ Assert.assertEquals(interval, (long) reportedState.getRight().getLeft());
+
+ final TimeWindowStateProgressIndex reportedProgressIndex =
+ new TimeWindowStateProgressIndex(
+ Collections.singletonMap("root.sg.d.s", reportedState.getRight()));
+ final ProgressIndex restoredProgressIndex =
roundTripProgressIndex(reportedProgressIndex);
+ final TimeWindowStateProgressIndex restoredWindowProgressIndex =
+ restoredProgressIndex
+ .getProgressIndexByType(TimeWindowStateProgressIndex.class)
+ .orElse(null);
+ Assert.assertNotNull(restoredWindowProgressIndex);
+
+ final Pair<Long, ByteBuffer> restoredState =
+
restoredWindowProgressIndex.getTimeSeries2TimestampWindowBufferPairMap().get("root.sg.d.s");
+ Assert.assertNotNull(restoredState);
+
+ for (int restoration = 0; restoration < 2; ++restoration) {
+ final TimeSeriesRuntimeState restoredRuntimeState =
+ new TimeSeriesRuntimeState(
+ aggregatedOperators,
+ intermediateOperators,
+ Collections.emptyMap(),
+ windowingProcessor);
+ restoredRuntimeState.restoreTimestampAndWindows(restoredState);
+ Assert.assertNull(restoredRuntimeState.updateWindows(interval, 100, 0));
+ Assert.assertNull(restoredRuntimeState.updateWindows(interval + 1, 30,
0));
+
+ final Pair<List<WindowOutput>, Pair<Long, ByteBuffer>> resumedOutput =
+ restoredRuntimeState.updateWindows(interval * 2, 40, 0);
+ Assert.assertNotNull(resumedOutput);
+ Assert.assertEquals(1, resumedOutput.getLeft().size());
+ Assert.assertEquals(
+ 25.0,
+ (double)
resumedOutput.getLeft().get(0).getAggregatedResults().get("avg").getRight(),
+ 0.0);
+ Assert.assertNotNull(resumedOutput.getRight());
+ Assert.assertEquals(interval * 2, (long)
resumedOutput.getRight().getLeft());
+ }
+ }
+
+ private static ByteBuffer serializeWindow(
+ final TumblingWindowingProcessor windowingProcessor, final long
timestamp)
+ throws IOException {
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ ReadWriteIOUtils.write(1, outputStream);
+ final TimeSeriesWindow window = new TimeSeriesWindow(windowingProcessor,
null);
+ window.setTimestamp(timestamp);
+ window.serialize(outputStream);
+ return ByteBuffer.wrap(output.getBuf(), 0, output.size());
+ }
+ }
+
+ private static ProgressIndex roundTripProgressIndex(final ProgressIndex
progressIndex)
+ throws IOException {
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ progressIndex.serialize(outputStream);
+ return
ProgressIndexType.deserializeFrom(ByteBuffer.wrap(output.getBuf(), 0,
output.size()));
+ }
+ }
+
+ private static ByteBuffer serializeLegacyWindow(
+ final long timestamp, final int count, final int sum) throws IOException
{
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ ReadWriteIOUtils.write(timestamp, outputStream);
+ ReadWriteIOUtils.write(2, outputStream);
+ ReadWriteIOUtils.write("count", outputStream);
+ TSDataType.INT32.serializeTo(outputStream);
+ ReadWriteIOUtils.write(count, outputStream);
+ ReadWriteIOUtils.write("sum_x1", outputStream);
+ TSDataType.INT32.serializeTo(outputStream);
+ TSDataType.INT32.serializeTo(outputStream);
+ ReadWriteIOUtils.write(sum, outputStream);
+ return ByteBuffer.wrap(output.getBuf(), 0, output.size());
+ }
+ }
+
+ private static ByteBuffer serializeLegacyFactorWindow() throws IOException {
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ ReadWriteIOUtils.write(0L, outputStream);
+ ReadWriteIOUtils.write(5, outputStream);
+ writeLegacyIntermediate(outputStream, "abs_max", TSDataType.INT32, 4,
true);
+ writeLegacyIntermediate(outputStream, "count", TSDataType.INT32, 2,
false);
+ writeLegacyIntermediate(outputStream, "sum_x1", TSDataType.INT32, 2,
true);
+ writeLegacyIntermediate(outputStream, "sum_x2", TSDataType.INT32, 20,
true);
+ ReadWriteIOUtils.write("sum_x0.5", outputStream);
+ TSDataType.INT32.serializeTo(outputStream);
+ ReadWriteIOUtils.write(Double.NaN, outputStream);
+ return ByteBuffer.wrap(output.getBuf(), 0, output.size());
+ }
+ }
+
+ private static ByteBuffer serializeLegacyCountWindow() throws IOException {
+ try (final PublicBAOS output = new PublicBAOS();
+ final DataOutputStream outputStream = new DataOutputStream(output)) {
+ ReadWriteIOUtils.write(0L, outputStream);
+ ReadWriteIOUtils.write(1, outputStream);
+ ReadWriteIOUtils.write("count", outputStream);
+ TSDataType.INT32.serializeTo(outputStream);
+ ReadWriteIOUtils.write(2, outputStream);
+ return ByteBuffer.wrap(output.getBuf(), 0, output.size());
+ }
+ }
+
+ private static void writeLegacyIntermediate(
+ final DataOutputStream outputStream,
+ final String name,
+ final TSDataType measurementDataType,
+ final int value,
+ final boolean operatorStateHasDataType)
+ throws IOException {
+ ReadWriteIOUtils.write(name, outputStream);
+ measurementDataType.serializeTo(outputStream);
+ if (operatorStateHasDataType) {
+ measurementDataType.serializeTo(outputStream);
+ }
+ ReadWriteIOUtils.write(value, outputStream);
+ }
+
+ private static Map<String, Supplier<IntermediateResultOperator>>
+ createFactorIntermediateOperators() {
+ final Map<String, Supplier<IntermediateResultOperator>>
intermediateOperators = new HashMap<>();
+ intermediateOperators.put("abs_max", AbsoluteMaxOperator::new);
+ intermediateOperators.put("count", CountOperator::new);
+ intermediateOperators.put("sum_abs_x0.5", () -> new
FractionPoweredSumOperator(0.5, true));
+ intermediateOperators.put("sum_abs_x1", () -> new
FractionPoweredSumOperator(1, true));
+ intermediateOperators.put("sum_x0.5", () -> new
FractionPoweredSumOperator(0.5));
+ intermediateOperators.put("sum_x1", () -> new
IntegralPoweredSumOperator(1));
+ intermediateOperators.put("sum_x2", () -> new
IntegralPoweredSumOperator(2));
+ return intermediateOperators;
+ }
+
+ private static Map<String, AggregatedResultOperator>
createFactorAggregatedOperators() {
+ final Map<String, AggregatedResultOperator> aggregatedOperators = new
HashMap<>();
+ aggregatedOperators.put("ff", new FormFactorOperator());
+ aggregatedOperators.put("pf", new PulseFactorOperator());
+ aggregatedOperators.put("ce", new ClearanceFactorOperator());
+ return aggregatedOperators;
+ }
+
+ private static Pair<TSDataType, Object> terminatePeak(
+ final TSDataType measurementDataType, final AbsoluteMaxOperator
absoluteMaxOperator) {
+ return new PeakOperator()
+ .terminateWindow(
+ measurementDataType,
+ new CustomizedReadableIntermediateResults(
+ Collections.singletonMap("abs_max",
absoluteMaxOperator.getResult()), false));
+ }
+
+ private static TumblingWindowingProcessor createWindowingProcessor(
+ final long boundaryTime, final long slidingSeconds) throws Exception {
+ final Map<String, String> attributes = new HashMap<>();
+ attributes.put(PROCESSOR_SLIDING_BOUNDARY_TIME_KEY,
Long.toString(boundaryTime));
+ attributes.put(PROCESSOR_SLIDING_SECONDS_KEY,
Long.toString(slidingSeconds));
+ final PipeParameters parameters = new PipeParameters(attributes);
+ final TumblingWindowingProcessor processor = new
TumblingWindowingProcessor();
+ processor.validate(new PipeParameterValidator(parameters));
+ processor.customize(parameters, () -> null);
+ return processor;
+ }
+
+ private static void validate(final String operators, final String
outputMeasurements)
+ throws Exception {
+ final Map<String, String> attributes = new HashMap<>();
+ attributes.put(PROCESSOR_OPERATORS_KEY, operators);
+ attributes.put(PROCESSOR_OUTPUT_MEASUREMENTS_KEY, outputMeasurements);
+ new AggregateProcessor().validate(new PipeParameterValidator(new
PipeParameters(attributes)));
+ }
+}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/aggregate/window/processor/TumblingWindowingProcessorTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/aggregate/window/processor/TumblingWindowingProcessorTest.java
index 7d4e8d07cf0..2b6ee8e2366 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/aggregate/window/processor/TumblingWindowingProcessorTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/processor/aggregate/window/processor/TumblingWindowingProcessorTest.java
@@ -42,6 +42,37 @@ import static
org.apache.iotdb.commons.pipe.config.constant.PipeProcessorConstan
public class TumblingWindowingProcessorTest {
+ @Test
+ public void testWindowUsesHalfOpenTimeRange() throws Exception {
+ final TumblingWindowingProcessor processor = createProcessor(0, 1);
+ final long interval = TimestampPrecisionUtils.convertToCurrPrecision(1,
TimeUnit.SECONDS);
+ final TimeSeriesWindow window = new TimeSeriesWindow(processor, null);
+ window.setTimestamp(0);
+
+ final Pair<WindowState, WindowOutput> beforeEnd =
+ processor.updateAndMaySetWindowState(window, interval - 1);
+ final Pair<WindowState, WindowOutput> atEnd =
+ processor.updateAndMaySetWindowState(window, interval);
+
+ Assert.assertEquals(WindowState.COMPUTE, beforeEnd.getLeft());
+ Assert.assertNull(beforeEnd.getRight());
+ Assert.assertEquals(WindowState.EMIT_AND_PURGE_WITHOUT_COMPUTE,
atEnd.getLeft());
+ Assert.assertEquals(0L, atEnd.getRight().getTimestamp());
+ Assert.assertEquals(interval, atEnd.getRight().getProgressTime());
+ }
+
+ @Test
+ public void testNegativeTimestampAlignsFromNegativeBoundary() throws
Exception {
+ final long interval = TimestampPrecisionUtils.convertToCurrPrecision(1,
TimeUnit.SECONDS);
+ final long boundary = -(interval + interval / 2);
+ final long timestamp = -(interval * 2 / 5);
+ final TumblingWindowingProcessor processor = createProcessor(boundary, 1);
+ final List<TimeSeriesWindow> windows = new ArrayList<>();
+
+ Assert.assertEquals(1, processor.mayAddWindow(windows, timestamp).size());
+ Assert.assertEquals(boundary + interval, windows.get(0).getTimestamp());
+ }
+
@Test
public void testMayAddWindowAlignsExtremeRangeWithoutOverflow() throws
Exception {
final TumblingWindowingProcessor processor =
createProcessor(Long.MIN_VALUE, 1);
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileSourceTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileSourceTest.java
index 0f33640fec1..b8fa1c570ed 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileSourceTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/source/dataregion/historical/PipeHistoricalDataRegionTsFileSourceTest.java
@@ -25,8 +25,11 @@ import
org.apache.iotdb.commons.consensus.index.impl.IoTProgressIndex;
import org.apache.iotdb.commons.consensus.index.impl.MinimumProgressIndex;
import org.apache.iotdb.commons.consensus.index.impl.RecoverProgressIndex;
import org.apache.iotdb.commons.consensus.index.impl.SimpleProgressIndex;
+import org.apache.iotdb.commons.consensus.index.impl.StateProgressIndex;
import
org.apache.iotdb.commons.consensus.index.impl.TimePartitionProgressIndex;
+import
org.apache.iotdb.commons.consensus.index.impl.TimeWindowStateProgressIndex;
import org.apache.iotdb.commons.path.PartialPath;
+import org.apache.iotdb.commons.pipe.agent.task.meta.PipeRuntimeMetaVersion;
import org.apache.iotdb.commons.pipe.agent.task.meta.PipeTaskMeta;
import org.apache.iotdb.commons.pipe.config.constant.PipeSourceConstant;
import org.apache.iotdb.commons.pipe.config.constant.SystemConstant;
@@ -51,6 +54,8 @@ import org.apache.iotdb.pipe.api.event.Event;
import org.apache.iotdb.pipe.api.exception.PipeException;
import org.apache.tsfile.file.metadata.PlainDeviceID;
+import org.apache.tsfile.utils.Pair;
+import org.apache.tsfile.utils.PublicBAOS;
import org.junit.Assert;
import org.junit.Test;
@@ -58,6 +63,7 @@ import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
+import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -726,6 +732,70 @@ public class PipeHistoricalDataRegionTsFileSourceTest {
}
}
+ @Test
+ public void testFilterAndSortTsFilesUsingRestoredWindowStateProgressIndex()
throws Exception {
+ final File tempDir =
Files.createTempDirectory("pipeHistoricalWindowStateOrder").toFile();
+
+ try {
+ final TimeWindowStateProgressIndex windowStateProgressIndex =
+ new TimeWindowStateProgressIndex(
+ Map.of(
+ "root.sg.d.completed", new Pair<Long, ByteBuffer>(100L,
null),
+ "root.sg.d.open", new Pair<>(200L, ByteBuffer.wrap(new
byte[] {1}))));
+ final ProgressIndex wrappedProgressIndex =
+ new StateProgressIndex(
+ 1L,
+ Collections.emptyMap(),
+ hybridProgressIndex(windowStateProgressIndex, new
SimpleProgressIndex(0, 10)));
+ final PipeTaskMeta restoredTaskMeta =
+ roundTripTaskMeta(new PipeTaskMeta(wrappedProgressIndex, 1));
+
+ final TsFileResource beforeWatermark =
+ createClosedTsFileResource(tempDir, "50-1-0-0.tsfile", new
SimpleProgressIndex(0, 11));
+ final TsFileResource atWatermark =
+ createClosedTsFileResource(tempDir, "90-1-0-0.tsfile", new
SimpleProgressIndex(0, 2));
+ final TsFileResource afterWatermark =
+ createClosedTsFileResource(tempDir, "95-1-0-0.tsfile", new
SimpleProgressIndex(0, 1));
+ final PlainDeviceID device = new PlainDeviceID("root.sg.d");
+ beforeWatermark.updateStartTime(device, 50L);
+ beforeWatermark.updateEndTime(device, 99L);
+ atWatermark.updateStartTime(device, 90L);
+ atWatermark.updateEndTime(device, 100L);
+ afterWatermark.updateStartTime(device, 95L);
+ afterWatermark.updateEndTime(device, 101L);
+
+ final PipeHistoricalDataRegionTsFileSource source =
+ new PipeHistoricalDataRegionTsFileSource();
+ final PipeParameters parameters =
+ new PipeParameters(
+ Map.of(
+ PipeSourceConstant.SOURCE_INCLUSION_KEY,
+ "data.insert",
+
PipeSourceConstant.SOURCE_HISTORY_TSFILE_ORDER_BY_QUERY_PRIORITY_KEY,
+ "false"));
+ source.validate(new PipeParameterValidator(parameters));
+ source.customize(
+ parameters, () -> new PipeTaskSourceRuntimeEnvironment("test", 123,
1, restoredTaskMeta));
+ final ProgressIndex restoredStartIndex =
+ (ProgressIndex) getPrivateField(source, "startIndex");
+ Assert.assertNotNull(
+ restoredStartIndex
+ .getProgressIndexByType(TimeWindowStateProgressIndex.class)
+ .orElse(null));
+
+ assertMayTsFileContainUnprocessedData(restoredStartIndex,
beforeWatermark, false);
+ assertMayTsFileContainUnprocessedData(restoredStartIndex, atWatermark,
true);
+ assertMayTsFileContainUnprocessedData(restoredStartIndex,
afterWatermark, true);
+ final List<TsFileResource> resources =
+ new ArrayList<>(Arrays.asList(afterWatermark, atWatermark));
+ sortExtractedResources(source, resources);
+
+ Assert.assertEquals(Arrays.asList(atWatermark, afterWatermark),
resources);
+ } finally {
+ FileUtils.deleteFileOrDirectory(tempDir);
+ }
+ }
+
@Test
public void testMissingTsFileResourceDoesNotBlockHistoricalExtraction()
throws Exception {
final File tempDir =
Files.createTempDirectory("pipeHistoricalMissingResource").toFile();
@@ -882,6 +952,14 @@ public class PipeHistoricalDataRegionTsFileSourceTest {
return result;
}
+ private static PipeTaskMeta roundTripTaskMeta(final PipeTaskMeta taskMeta)
throws IOException {
+ try (final PublicBAOS output = new PublicBAOS()) {
+ taskMeta.serialize(output);
+ return PipeTaskMeta.deserialize(
+ PipeRuntimeMetaVersion.VERSION_2, ByteBuffer.wrap(output.getBuf(),
0, output.size()));
+ }
+ }
+
private static IoTProgressIndex iotProgressIndex(
final int firstPeerId, final long firstSearchIndex, final long...
peerIdAndSearchIndexPairs) {
final Map<Integer, Long> peerId2SearchIndex = new HashMap<>();
diff --git
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/consensus/index/impl/TimeWindowStateProgressIndex.java
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/consensus/index/impl/TimeWindowStateProgressIndex.java
index f98a3a1e512..ff162d1c390 100644
---
a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/consensus/index/impl/TimeWindowStateProgressIndex.java
+++
b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/consensus/index/impl/TimeWindowStateProgressIndex.java
@@ -264,6 +264,8 @@ public class TimeWindowStateProgressIndex extends
ProgressIndex {
final long timestamp = ReadWriteIOUtils.readLong(byteBuffer);
final int length = ReadWriteIOUtils.readInt(byteBuffer);
if (length < 0) {
+
timeWindowStateProgressIndex.timeSeries2TimestampWindowBufferPairMap.put(
+ timeSeries, new Pair<>(timestamp, null));
continue;
}
final byte[] body = new byte[length];
@@ -286,6 +288,8 @@ public class TimeWindowStateProgressIndex extends
ProgressIndex {
final long timestamp = ReadWriteIOUtils.readLong(stream);
final int length = ReadWriteIOUtils.readInt(stream);
if (length < 0) {
+
timeWindowStateProgressIndex.timeSeries2TimestampWindowBufferPairMap.put(
+ timeSeries, new Pair<>(timestamp, null));
continue;
}
final byte[] body = new byte[length];
diff --git
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/consensus/index/ProgressIndexTest.java
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/consensus/index/ProgressIndexTest.java
index 07ee3ef268e..1706a14f2d5 100644
---
a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/consensus/index/ProgressIndexTest.java
+++
b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/consensus/index/ProgressIndexTest.java
@@ -25,10 +25,17 @@ import
org.apache.iotdb.commons.consensus.index.impl.SimpleProgressIndex;
import org.apache.iotdb.commons.consensus.index.impl.StateProgressIndex;
import
org.apache.iotdb.commons.consensus.index.impl.TimeWindowStateProgressIndex;
+import org.apache.tsfile.utils.Pair;
import org.junit.Assert;
import org.junit.Test;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
public class ProgressIndexTest {
@@ -79,4 +86,40 @@ public class ProgressIndexTest {
timeWindowStateProgressIndex);
Assert.assertEquals(blendedProgressIndex, reverseBlendedProgressIndex);
}
+
+ @Test
+ public void
testTimeWindowStateProgressIndexPreservesNullWindowBuffersAfterRestore()
+ throws IOException {
+ final Map<String, Pair<Long, ByteBuffer>> timeSeries2WindowState = new
HashMap<>();
+ timeSeries2WindowState.put("root.sg.d.completed", new Pair<>(10L, null));
+ timeSeries2WindowState.put(
+ "root.sg.d.open", new Pair<>(20L, ByteBuffer.wrap(new byte[] {1, 2,
3})));
+ final TimeWindowStateProgressIndex progressIndex =
+ new TimeWindowStateProgressIndex(timeSeries2WindowState);
+
+ final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ progressIndex.serialize(outputStream);
+ final byte[] serialized = outputStream.toByteArray();
+
+
assertRestoredWindowStates(ProgressIndexType.deserializeFrom(ByteBuffer.wrap(serialized)));
+ assertRestoredWindowStates(
+ ProgressIndexType.deserializeFrom(new
ByteArrayInputStream(serialized)));
+ }
+
+ private void assertRestoredWindowStates(final ProgressIndex
restoredProgressIndex) {
+ final TimeWindowStateProgressIndex restored =
+ restoredProgressIndex
+ .getProgressIndexByType(TimeWindowStateProgressIndex.class)
+ .orElse(null);
+ Assert.assertNotNull(restored);
+
+ final Map<String, Pair<Long, ByteBuffer>> restoredStates =
+ restored.getTimeSeries2TimestampWindowBufferPairMap();
+ Assert.assertEquals(2, restoredStates.size());
+ Assert.assertEquals(Long.valueOf(10L),
restoredStates.get("root.sg.d.completed").getLeft());
+ Assert.assertNull(restoredStates.get("root.sg.d.completed").getRight());
+ Assert.assertEquals(Long.valueOf(20L),
restoredStates.get("root.sg.d.open").getLeft());
+ Assert.assertArrayEquals(
+ new byte[] {1, 2, 3},
restoredStates.get("root.sg.d.open").getRight().array());
+ }
}