fresh-borzoni commented on code in PR #29952:
URL: https://github.com/apache/flink/pull/29952#discussion_r4747328203


##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/over/RowTimeMultiRangeBoundedPrecedingFunction.java:
##########
@@ -0,0 +1,346 @@
+/*
+ * 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.flink.table.runtime.operators.over;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.functions.RuntimeContext;
+import org.apache.flink.api.common.state.MapState;
+import org.apache.flink.api.common.state.MapStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.typeutils.ListTypeInfo;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.utils.JoinedRowData;
+import org.apache.flink.table.runtime.dataview.PerKeyStateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateListView;
+import org.apache.flink.table.runtime.dataview.StateMapView;
+import org.apache.flink.table.runtime.generated.AggsHandleFunction;
+import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Process function for several event-time bounded RANGE OVER windows that 
share the same partition
+ * and order key but have different preceding offsets.
+ *
+ * <p>E.g.: SELECT SUM(c) OVER (PARTITION BY b ORDER BY rowtime RANGE BETWEEN 
INTERVAL '10' MINUTE
+ * PRECEDING AND CURRENT ROW), SUM(c) OVER (PARTITION BY b ORDER BY rowtime 
RANGE BETWEEN INTERVAL
+ * '30' MINUTE PRECEDING AND CURRENT ROW) FROM T.
+ *
+ * <p>The input rows are stored once and kept for the largest offset. Each 
window keeps its own
+ * accumulators and retracts a row when the row leaves that window's range.
+ */
+public class RowTimeMultiRangeBoundedPrecedingFunction<K>

Review Comment:
   this is mostly a copy of RowTimeRangeBoundedPrecedingFunction. Could we 
extract the common part into a base class, like 
AbstractRowTimeUnboundedPrecedingOver does?



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/over/RowTimeMultiRangeBoundedPrecedingFunction.java:
##########
@@ -0,0 +1,346 @@
+/*
+ * 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.flink.table.runtime.operators.over;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.functions.RuntimeContext;
+import org.apache.flink.api.common.state.MapState;
+import org.apache.flink.api.common.state.MapStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.typeutils.ListTypeInfo;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.utils.JoinedRowData;
+import org.apache.flink.table.runtime.dataview.PerKeyStateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateListView;
+import org.apache.flink.table.runtime.dataview.StateMapView;
+import org.apache.flink.table.runtime.generated.AggsHandleFunction;
+import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Process function for several event-time bounded RANGE OVER windows that 
share the same partition
+ * and order key but have different preceding offsets.
+ *
+ * <p>E.g.: SELECT SUM(c) OVER (PARTITION BY b ORDER BY rowtime RANGE BETWEEN 
INTERVAL '10' MINUTE
+ * PRECEDING AND CURRENT ROW), SUM(c) OVER (PARTITION BY b ORDER BY rowtime 
RANGE BETWEEN INTERVAL
+ * '30' MINUTE PRECEDING AND CURRENT ROW) FROM T.
+ *
+ * <p>The input rows are stored once and kept for the largest offset. Each 
window keeps its own
+ * accumulators and retracts a row when the row leaves that window's range.
+ */
+public class RowTimeMultiRangeBoundedPrecedingFunction<K>
+        extends KeyedProcessFunction<K, RowData, RowData> {
+    private static final long serialVersionUID = 1L;
+
+    private static final Logger LOG =
+            
LoggerFactory.getLogger(RowTimeMultiRangeBoundedPrecedingFunction.class);
+
+    private static final String LATE_ELEMENTS_DROPPED_METRIC_NAME = 
"numLateRecordsDropped";
+
+    private final GeneratedAggsHandleFunction[] genAggsHandlers;
+    private final LogicalType[][] accTypes;
+    private final LogicalType[] inputFieldTypes;
+    private final long[] precedingOffsets;
+    private final long maxPrecedingOffset;
+    private final int rowTimeIdx;
+
+    private transient JoinedRowData output;
+    private transient AggsHandleFunction[] functions;
+    private transient RowData[] aggValues;
+    private transient JoinedRowData[] aggValueJoins;
+
+    private transient ValueState<Long> lastTriggeringTsState;
+    // the last timestamp whose rows have been aggregated and emitted; every 
window has retracted
+    // exactly the rows that were out of its range at that timestamp
+    private transient ValueState<Long> lastProcessedTsState;
+    private transient ValueState<Long> cleanupTsState;
+    private transient List<ValueState<RowData>> accStates;
+    private transient MapState<Long, List<RowData>> inputState;
+
+    private transient Counter numLateRecordsDropped;
+
+    @VisibleForTesting
+    Counter getCounter() {
+        return numLateRecordsDropped;
+    }
+
+    public RowTimeMultiRangeBoundedPrecedingFunction(
+            GeneratedAggsHandleFunction[] genAggsHandlers,
+            LogicalType[][] accTypes,
+            LogicalType[] inputFieldTypes,
+            long[] precedingOffsets,
+            int rowTimeIdx) {
+        Preconditions.checkArgument(genAggsHandlers.length > 0);
+        Preconditions.checkArgument(genAggsHandlers.length == accTypes.length);
+        Preconditions.checkArgument(genAggsHandlers.length == 
precedingOffsets.length);
+        this.genAggsHandlers = genAggsHandlers;
+        this.accTypes = accTypes;
+        this.inputFieldTypes = inputFieldTypes;
+        this.precedingOffsets = precedingOffsets;
+        long max = Long.MIN_VALUE;
+        for (long offset : precedingOffsets) {
+            max = Math.max(max, offset);
+        }
+        this.maxPrecedingOffset = max;
+        this.rowTimeIdx = rowTimeIdx;
+    }
+
+    @Override
+    public void open(OpenContext openContext) throws Exception {
+        final int n = genAggsHandlers.length;
+        final StateDataViewStore store = new 
PerKeyStateDataViewStore(getRuntimeContext());
+        functions = new AggsHandleFunction[n];
+        accStates = new ArrayList<>(n);
+        for (int i = 0; i < n; i++) {
+            functions[i] =
+                    
genAggsHandlers[i].newInstance(getRuntimeContext().getUserCodeClassLoader());
+            // the generated handlers name their data view states from 0 
upwards, so the states of
+            // different windows would clash without a per-window prefix
+            functions[i].open(new PrefixedStateDataViewStore(store, "w" + i + 
"$"));
+            accStates.add(
+                    getRuntimeContext()
+                            .getState(
+                                    new ValueStateDescriptor<>(
+                                            "accState_" + i,
+                                            
InternalTypeInfo.ofFields(accTypes[i]))));
+        }
+        aggValues = new RowData[n];
+        aggValueJoins = new JoinedRowData[n - 1];
+        for (int i = 0; i < n - 1; i++) {
+            aggValueJoins[i] = new JoinedRowData();
+        }
+        output = new JoinedRowData();
+
+        lastTriggeringTsState =
+                getRuntimeContext()
+                        .getState(new 
ValueStateDescriptor<>("lastTriggeringTsState", Types.LONG));
+        lastProcessedTsState =
+                getRuntimeContext()
+                        .getState(new 
ValueStateDescriptor<>("lastProcessedTsState", Types.LONG));
+        cleanupTsState =
+                getRuntimeContext()
+                        .getState(new ValueStateDescriptor<>("cleanupTsState", 
Types.LONG));
+
+        InternalTypeInfo<RowData> inputType = 
InternalTypeInfo.ofFields(inputFieldTypes);
+        inputState =
+                getRuntimeContext()
+                        .getMapState(
+                                new MapStateDescriptor<>(
+                                        "inputState", Types.LONG, new 
ListTypeInfo<>(inputType)));
+
+        numLateRecordsDropped =
+                
getRuntimeContext().getMetricGroup().counter(LATE_ELEMENTS_DROPPED_METRIC_NAME);
+    }
+
+    @Override
+    public void processElement(
+            RowData input,
+            KeyedProcessFunction<K, RowData, RowData>.Context ctx,
+            Collector<RowData> out)
+            throws Exception {
+        long triggeringTs = input.getLong(rowTimeIdx);
+
+        Long lastTriggeringTs = lastTriggeringTsState.value();
+        if (lastTriggeringTs == null) {
+            lastTriggeringTs = 0L;
+        }
+
+        if (triggeringTs > lastTriggeringTs) {
+            List<RowData> data = inputState.get(triggeringTs);
+            if (data == null) {
+                data = new ArrayList<>();
+                ctx.timerService().registerEventTimeTimer(triggeringTs);
+            }
+            data.add(input);
+            inputState.put(triggeringTs, data);
+            registerCleanupTimer(ctx, triggeringTs);
+        } else {
+            numLateRecordsDropped.inc();
+        }
+    }
+
+    private void registerCleanupTimer(
+            KeyedProcessFunction<K, RowData, RowData>.Context ctx, long 
timestamp)
+            throws Exception {
+        long minCleanupTimestamp = timestamp + maxPrecedingOffset + 1;
+        long maxCleanupTimestamp = timestamp + (long) (maxPrecedingOffset * 
1.5) + 1;
+        Long curCleanupTimestamp = cleanupTsState.value();
+        if (curCleanupTimestamp == null || curCleanupTimestamp < 
minCleanupTimestamp) {
+            ctx.timerService().registerEventTimeTimer(maxCleanupTimestamp);
+            cleanupTsState.update(maxCleanupTimestamp);
+        }
+    }
+
+    @Override
+    public void onTimer(
+            long timestamp,
+            KeyedProcessFunction<K, RowData, RowData>.OnTimerContext ctx,
+            Collector<RowData> out)
+            throws Exception {
+        Long cleanupTimestamp = cleanupTsState.value();
+        if (cleanupTimestamp != null && cleanupTimestamp <= timestamp) {
+            inputState.clear();
+            for (int i = 0; i < functions.length; i++) {
+                accStates.get(i).clear();
+                functions[i].cleanup();
+            }
+            lastTriggeringTsState.clear();
+            lastProcessedTsState.clear();
+            cleanupTsState.clear();
+            return;
+        }
+
+        List<RowData> inputs = inputState.get(timestamp);
+        if (inputs != null) {
+            for (int i = 0; i < functions.length; i++) {
+                RowData acc = accStates.get(i).value();
+                functions[i].setAccumulators(acc == null ? 
functions[i].createAccumulators() : acc);
+            }
+
+            // null when no row has been aggregated yet: then no window has 
retracted anything
+            final Long lastProcessedTs = lastProcessedTsState.value();
+            final List<Long> expiredTsList = new ArrayList<>();
+
+            Iterator<Map.Entry<Long, List<RowData>>> iter = 
inputState.entries().iterator();
+            while (iter.hasNext()) {
+                Map.Entry<Long, List<RowData>> entry = iter.next();
+                long dataTs = entry.getKey();
+                long offset = timestamp - dataTs;
+                if (offset <= 0) {
+                    continue;
+                }
+                List<RowData> rows = entry.getValue();
+                if (rows == null) {
+                    LOG.warn(
+                            "The state is cleared because of state ttl. "
+                                    + "This will result in incorrect result. "
+                                    + "You can increase the state ttl to avoid 
this.");
+                    continue;
+                }
+                for (int i = 0; i < functions.length; i++) {
+                    boolean outOfRangeNow = offset > precedingOffsets[i];
+                    boolean inRangeBefore =
+                            lastProcessedTs == null
+                                    || lastProcessedTs - dataTs <= 
precedingOffsets[i];
+                    if (outOfRangeNow && inRangeBefore) {
+                        for (RowData row : rows) {
+                            functions[i].retract(row);
+                        }
+                    }
+                }
+                if (offset > maxPrecedingOffset) {
+                    expiredTsList.add(dataTs);
+                }
+            }
+
+            for (int i = 0; i < functions.length; i++) {
+                for (RowData row : inputs) {
+                    functions[i].accumulate(row);
+                }
+                aggValues[i] = functions[i].getValue();
+            }
+
+            RowData aggValue = concatAggValues();
+            for (RowData row : inputs) {
+                output.replace(row, aggValue);
+                out.collect(output);
+            }
+
+            for (Long ts : expiredTsList) {
+                inputState.remove(ts);
+            }
+            for (int i = 0; i < functions.length; i++) {
+                accStates.get(i).update(functions[i].getAccumulators());
+            }
+            lastProcessedTsState.update(timestamp);
+        }
+        lastTriggeringTsState.update(timestamp);
+    }
+
+    @Override
+    public void close() throws Exception {
+        if (functions != null) {
+            for (AggsHandleFunction function : functions) {
+                if (function != null) {
+                    function.close();
+                }
+            }
+        }
+    }
+
+    /** Concatenates the aggregate values of all windows, in window order. */
+    private RowData concatAggValues() {
+        RowData result = aggValues[0];
+        for (int i = 1; i < aggValues.length; i++) {
+            result = aggValueJoins[i - 1].replace(result, aggValues[i]);
+        }
+        return result;
+    }
+
+    /** Prefixes the names of the data view states of one window. */
+    private static final class PrefixedStateDataViewStore implements 
StateDataViewStore {

Review Comment:
   the prefix becomes part of the state names, so part of the savepoint format, 
one more reason for a restore test.
   Also, why a nested class? Could unique names be generated at codegen instead 
(DataViewUtils#createStateId)?



##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecOverAggregate.java:
##########
@@ -217,7 +214,22 @@ protected Transformation<RowData> translateToPlanInternal(
         final CodeGeneratorContext ctx =
                 new CodeGeneratorContext(config, 
planner.getFlinkContext().getClassLoader());
         final KeyedProcessFunction<RowData, RowData, RowData> 
overProcessFunction;
-        if (group.getLowerBound().isPreceding()
+        if (overSpec.getGroups().size() > 1) {
+            // the physical rule only accepts several windows when all of them 
are bounded
+            // event-time RANGE windows on the same partition and order key
+            if (timeAttribute != TimeAttribute.ROW_TIME) {

Review Comment:
   why do we need it? The rule already guarantees this



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/over/RowTimeMultiRangeBoundedPrecedingFunction.java:
##########
@@ -0,0 +1,346 @@
+/*
+ * 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.flink.table.runtime.operators.over;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.functions.RuntimeContext;
+import org.apache.flink.api.common.state.MapState;
+import org.apache.flink.api.common.state.MapStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.typeutils.ListTypeInfo;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.utils.JoinedRowData;
+import org.apache.flink.table.runtime.dataview.PerKeyStateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateListView;
+import org.apache.flink.table.runtime.dataview.StateMapView;
+import org.apache.flink.table.runtime.generated.AggsHandleFunction;
+import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Process function for several event-time bounded RANGE OVER windows that 
share the same partition
+ * and order key but have different preceding offsets.
+ *
+ * <p>E.g.: SELECT SUM(c) OVER (PARTITION BY b ORDER BY rowtime RANGE BETWEEN 
INTERVAL '10' MINUTE
+ * PRECEDING AND CURRENT ROW), SUM(c) OVER (PARTITION BY b ORDER BY rowtime 
RANGE BETWEEN INTERVAL
+ * '30' MINUTE PRECEDING AND CURRENT ROW) FROM T.
+ *
+ * <p>The input rows are stored once and kept for the largest offset. Each 
window keeps its own
+ * accumulators and retracts a row when the row leaves that window's range.
+ */
+public class RowTimeMultiRangeBoundedPrecedingFunction<K>
+        extends KeyedProcessFunction<K, RowData, RowData> {
+    private static final long serialVersionUID = 1L;
+
+    private static final Logger LOG =
+            
LoggerFactory.getLogger(RowTimeMultiRangeBoundedPrecedingFunction.class);
+
+    private static final String LATE_ELEMENTS_DROPPED_METRIC_NAME = 
"numLateRecordsDropped";
+
+    private final GeneratedAggsHandleFunction[] genAggsHandlers;
+    private final LogicalType[][] accTypes;
+    private final LogicalType[] inputFieldTypes;
+    private final long[] precedingOffsets;
+    private final long maxPrecedingOffset;
+    private final int rowTimeIdx;
+
+    private transient JoinedRowData output;
+    private transient AggsHandleFunction[] functions;
+    private transient RowData[] aggValues;
+    private transient JoinedRowData[] aggValueJoins;
+
+    private transient ValueState<Long> lastTriggeringTsState;
+    // the last timestamp whose rows have been aggregated and emitted; every 
window has retracted
+    // exactly the rows that were out of its range at that timestamp
+    private transient ValueState<Long> lastProcessedTsState;

Review Comment:
   this is needed because stale cleanup timers also advance lastTriggeringTs, 
right? Then it should be in the comment.
   Also none of the harness tests fails if lastTriggeringTsState is used 
instead. Could you add one? e.g. rows at 100 and 1500, wm 1500, row at 3200, wm 
3200, expected (4, 6)



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/over/RowTimeMultiRangeBoundedPrecedingFunction.java:
##########
@@ -0,0 +1,346 @@
+/*
+ * 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.flink.table.runtime.operators.over;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.functions.RuntimeContext;
+import org.apache.flink.api.common.state.MapState;
+import org.apache.flink.api.common.state.MapStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.typeutils.ListTypeInfo;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.utils.JoinedRowData;
+import org.apache.flink.table.runtime.dataview.PerKeyStateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateListView;
+import org.apache.flink.table.runtime.dataview.StateMapView;
+import org.apache.flink.table.runtime.generated.AggsHandleFunction;
+import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Process function for several event-time bounded RANGE OVER windows that 
share the same partition
+ * and order key but have different preceding offsets.
+ *
+ * <p>E.g.: SELECT SUM(c) OVER (PARTITION BY b ORDER BY rowtime RANGE BETWEEN 
INTERVAL '10' MINUTE
+ * PRECEDING AND CURRENT ROW), SUM(c) OVER (PARTITION BY b ORDER BY rowtime 
RANGE BETWEEN INTERVAL
+ * '30' MINUTE PRECEDING AND CURRENT ROW) FROM T.
+ *
+ * <p>The input rows are stored once and kept for the largest offset. Each 
window keeps its own
+ * accumulators and retracts a row when the row leaves that window's range.
+ */
+public class RowTimeMultiRangeBoundedPrecedingFunction<K>
+        extends KeyedProcessFunction<K, RowData, RowData> {
+    private static final long serialVersionUID = 1L;
+
+    private static final Logger LOG =
+            
LoggerFactory.getLogger(RowTimeMultiRangeBoundedPrecedingFunction.class);
+
+    private static final String LATE_ELEMENTS_DROPPED_METRIC_NAME = 
"numLateRecordsDropped";
+
+    private final GeneratedAggsHandleFunction[] genAggsHandlers;
+    private final LogicalType[][] accTypes;
+    private final LogicalType[] inputFieldTypes;
+    private final long[] precedingOffsets;
+    private final long maxPrecedingOffset;
+    private final int rowTimeIdx;
+
+    private transient JoinedRowData output;
+    private transient AggsHandleFunction[] functions;
+    private transient RowData[] aggValues;
+    private transient JoinedRowData[] aggValueJoins;
+
+    private transient ValueState<Long> lastTriggeringTsState;
+    // the last timestamp whose rows have been aggregated and emitted; every 
window has retracted
+    // exactly the rows that were out of its range at that timestamp
+    private transient ValueState<Long> lastProcessedTsState;
+    private transient ValueState<Long> cleanupTsState;
+    private transient List<ValueState<RowData>> accStates;
+    private transient MapState<Long, List<RowData>> inputState;
+
+    private transient Counter numLateRecordsDropped;
+
+    @VisibleForTesting
+    Counter getCounter() {
+        return numLateRecordsDropped;
+    }
+
+    public RowTimeMultiRangeBoundedPrecedingFunction(
+            GeneratedAggsHandleFunction[] genAggsHandlers,
+            LogicalType[][] accTypes,
+            LogicalType[] inputFieldTypes,
+            long[] precedingOffsets,
+            int rowTimeIdx) {
+        Preconditions.checkArgument(genAggsHandlers.length > 0);
+        Preconditions.checkArgument(genAggsHandlers.length == accTypes.length);
+        Preconditions.checkArgument(genAggsHandlers.length == 
precedingOffsets.length);
+        this.genAggsHandlers = genAggsHandlers;
+        this.accTypes = accTypes;
+        this.inputFieldTypes = inputFieldTypes;
+        this.precedingOffsets = precedingOffsets;
+        long max = Long.MIN_VALUE;
+        for (long offset : precedingOffsets) {
+            max = Math.max(max, offset);
+        }
+        this.maxPrecedingOffset = max;
+        this.rowTimeIdx = rowTimeIdx;
+    }
+
+    @Override
+    public void open(OpenContext openContext) throws Exception {
+        final int n = genAggsHandlers.length;
+        final StateDataViewStore store = new 
PerKeyStateDataViewStore(getRuntimeContext());
+        functions = new AggsHandleFunction[n];
+        accStates = new ArrayList<>(n);
+        for (int i = 0; i < n; i++) {
+            functions[i] =
+                    
genAggsHandlers[i].newInstance(getRuntimeContext().getUserCodeClassLoader());
+            // the generated handlers name their data view states from 0 
upwards, so the states of
+            // different windows would clash without a per-window prefix
+            functions[i].open(new PrefixedStateDataViewStore(store, "w" + i + 
"$"));
+            accStates.add(
+                    getRuntimeContext()
+                            .getState(
+                                    new ValueStateDescriptor<>(
+                                            "accState_" + i,
+                                            
InternalTypeInfo.ofFields(accTypes[i]))));
+        }
+        aggValues = new RowData[n];
+        aggValueJoins = new JoinedRowData[n - 1];
+        for (int i = 0; i < n - 1; i++) {
+            aggValueJoins[i] = new JoinedRowData();
+        }
+        output = new JoinedRowData();
+
+        lastTriggeringTsState =
+                getRuntimeContext()
+                        .getState(new 
ValueStateDescriptor<>("lastTriggeringTsState", Types.LONG));
+        lastProcessedTsState =
+                getRuntimeContext()
+                        .getState(new 
ValueStateDescriptor<>("lastProcessedTsState", Types.LONG));
+        cleanupTsState =
+                getRuntimeContext()
+                        .getState(new ValueStateDescriptor<>("cleanupTsState", 
Types.LONG));
+
+        InternalTypeInfo<RowData> inputType = 
InternalTypeInfo.ofFields(inputFieldTypes);
+        inputState =
+                getRuntimeContext()
+                        .getMapState(
+                                new MapStateDescriptor<>(
+                                        "inputState", Types.LONG, new 
ListTypeInfo<>(inputType)));
+
+        numLateRecordsDropped =
+                
getRuntimeContext().getMetricGroup().counter(LATE_ELEMENTS_DROPPED_METRIC_NAME);
+    }
+
+    @Override
+    public void processElement(
+            RowData input,
+            KeyedProcessFunction<K, RowData, RowData>.Context ctx,
+            Collector<RowData> out)
+            throws Exception {
+        long triggeringTs = input.getLong(rowTimeIdx);
+
+        Long lastTriggeringTs = lastTriggeringTsState.value();
+        if (lastTriggeringTs == null) {
+            lastTriggeringTs = 0L;
+        }
+
+        if (triggeringTs > lastTriggeringTs) {
+            List<RowData> data = inputState.get(triggeringTs);
+            if (data == null) {
+                data = new ArrayList<>();
+                ctx.timerService().registerEventTimeTimer(triggeringTs);
+            }
+            data.add(input);
+            inputState.put(triggeringTs, data);
+            registerCleanupTimer(ctx, triggeringTs);
+        } else {
+            numLateRecordsDropped.inc();
+        }
+    }
+
+    private void registerCleanupTimer(
+            KeyedProcessFunction<K, RowData, RowData>.Context ctx, long 
timestamp)
+            throws Exception {
+        long minCleanupTimestamp = timestamp + maxPrecedingOffset + 1;
+        long maxCleanupTimestamp = timestamp + (long) (maxPrecedingOffset * 
1.5) + 1;
+        Long curCleanupTimestamp = cleanupTsState.value();
+        if (curCleanupTimestamp == null || curCleanupTimestamp < 
minCleanupTimestamp) {
+            ctx.timerService().registerEventTimeTimer(maxCleanupTimestamp);
+            cleanupTsState.update(maxCleanupTimestamp);
+        }
+    }
+
+    @Override
+    public void onTimer(
+            long timestamp,
+            KeyedProcessFunction<K, RowData, RowData>.OnTimerContext ctx,
+            Collector<RowData> out)
+            throws Exception {
+        Long cleanupTimestamp = cleanupTsState.value();
+        if (cleanupTimestamp != null && cleanupTimestamp <= timestamp) {
+            inputState.clear();
+            for (int i = 0; i < functions.length; i++) {
+                accStates.get(i).clear();
+                functions[i].cleanup();
+            }
+            lastTriggeringTsState.clear();
+            lastProcessedTsState.clear();
+            cleanupTsState.clear();
+            return;
+        }
+
+        List<RowData> inputs = inputState.get(timestamp);
+        if (inputs != null) {
+            for (int i = 0; i < functions.length; i++) {
+                RowData acc = accStates.get(i).value();
+                functions[i].setAccumulators(acc == null ? 
functions[i].createAccumulators() : acc);
+            }
+
+            // null when no row has been aggregated yet: then no window has 
retracted anything
+            final Long lastProcessedTs = lastProcessedTsState.value();
+            final List<Long> expiredTsList = new ArrayList<>();
+
+            Iterator<Map.Entry<Long, List<RowData>>> iter = 
inputState.entries().iterator();
+            while (iter.hasNext()) {
+                Map.Entry<Long, List<RowData>> entry = iter.next();
+                long dataTs = entry.getKey();
+                long offset = timestamp - dataTs;
+                if (offset <= 0) {
+                    continue;
+                }
+                List<RowData> rows = entry.getValue();

Review Comment:
   nit: entry.getValue() could be called only when a window actually retracts 
the entry



##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecOverAggregate.java:
##########
@@ -572,4 +556,110 @@ private KeyedProcessFunction<RowData, RowData, RowData> 
createBoundedOverProcess
                 throw new TableException("Unsupported bounded operation for 
OVER window.");
         }
     }
+
+    /**
+     * Create a ProcessFunction that evaluates several bounded event-time 
RANGE OVER windows, which
+     * share the partition and order key, and stores the input rows once.
+     */
+    private KeyedProcessFunction<RowData, RowData, RowData>
+            createMultiRangeBoundedOverProcessFunction(
+                    PlannerBase planner,
+                    List<RexLiteral> constants,
+                    RowType aggInputType,
+                    RowType inputType,
+                    int rowTimeIdx,
+                    ExecNodeConfig config) {
+        final List<OverSpec.GroupSpec> groups = overSpec.getGroups();
+        final int n = groups.size();
+        final GeneratedAggsHandleFunction[] genAggsHandlers = new 
GeneratedAggsHandleFunction[n];
+        final LogicalType[][] accTypes = new LogicalType[n][];
+        final long[] precedingOffsets = new long[n];
+        for (int i = 0; i < n; i++) {
+            final OverSpec.GroupSpec group = groups.get(i);
+            final Object boundValue =
+                    OverAggregateUtil.getBoundary(overSpec, 
group.getLowerBound());
+            if (boundValue instanceof BigDecimal) {
+                throw new TableException(
+                        "the specific value is decimal which haven not 
supported yet.");
+            }
+            precedingOffsets[i] = -1 * (long) boundValue;
+            // each handler gets its own context so that the generated classes 
do not share
+            // reusable members
+            final BoundedAggsHandler aggsHandler =
+                    generateBoundedAggsHandler(
+                            new CodeGeneratorContext(
+                                    config, 
planner.getFlinkContext().getClassLoader()),
+                            group.getAggCalls(),
+                            constants,
+                            aggInputType,
+                            inputType,
+                            planner.createRelBuilder(),
+                            planner.getTypeFactory());
+            genAggsHandlers[i] = aggsHandler.genAggsHandler;
+            accTypes[i] = aggsHandler.accTypes;
+        }
+        return new RowTimeMultiRangeBoundedPrecedingFunction<>(
+                genAggsHandlers,
+                accTypes,
+                inputType.getChildren().toArray(new LogicalType[0]),
+                precedingOffsets,
+                rowTimeIdx);
+    }
+
+    private BoundedAggsHandler generateBoundedAggsHandler(

Review Comment:
   fieldTypes is now computed twice, do I miss smth?



##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecOverAggregate.java:
##########
@@ -217,7 +214,22 @@ protected Transformation<RowData> translateToPlanInternal(
         final CodeGeneratorContext ctx =

Review Comment:
   nit: ctx is unused for the multi-window case



##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalOverAggregateRule.scala:
##########
@@ -86,6 +85,35 @@ class StreamPhysicalOverAggregateRule(config: Config) 
extends ConverterRule(conf
 }
 
 object StreamPhysicalOverAggregateRule {
+
+  /**
+   * Several OVER windows are computed by one operator that shares the input 
rows between them,
+   * which requires bounded RANGE windows on the same partition and event-time 
order.
+   */
+  private def validateMultipleWindows(window: FlinkLogicalOverAggregate): Unit 
= {

Review Comment:
   nit: why on the companion object? A private method in the class should be 
enough



##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalOverAggregateRule.scala:
##########
@@ -86,6 +85,35 @@ class StreamPhysicalOverAggregateRule(config: Config) 
extends ConverterRule(conf
 }
 
 object StreamPhysicalOverAggregateRule {
+
+  /**
+   * Several OVER windows are computed by one operator that shares the input 
rows between them,
+   * which requires bounded RANGE windows on the same partition and event-time 
order.
+   */
+  private def validateMultipleWindows(window: FlinkLogicalOverAggregate): Unit 
= {
+    val first = window.groups.get(0)
+    val inputFields = window.getInput.getRowType.getFieldList
+    window.groups.asScala.foreach {
+      group =>
+        val collations = group.orderKeys.getFieldCollations
+        val supported = group.keys == first.keys &&
+          group.orderKeys == first.orderKeys &&
+          collations.size() == 1 &&
+          FlinkTypeFactory.isRowtimeIndicatorType(
+            inputFields.get(collations.get(0).getFieldIndex).getType) &&
+          !group.isRows &&
+          group.lowerBound.isPreceding &&
+          !group.lowerBound.isUnbounded &&
+          group.upperBound.isCurrentRow
+        if (!supported) {
+          throw new TableException(
+            "Over Agg: Unsupported use of OVER windows. " +
+              "All aggregates must be computed on the same window. " +

Review Comment:
   the message is not accurate anymore. Could it say what is supported?



##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/nodes/physical/stream/StreamPhysicalOverAggregateBase.scala:
##########
@@ -68,32 +66,56 @@ abstract class StreamPhysicalOverAggregateBase(
   }
 
   override def explainTerms(pw: RelWriter): RelWriter = {
-    val overWindow: Group = logicWindow.groups.get(0)
+    val firstWindow: Group = logicWindow.groups.get(0)
     val constants: Seq[RexLiteral] = logicWindow.constants.asScala
-    val partitionKeys: Array[Int] = overWindow.keys.toArray
-    val namedAggregates: Seq[CalcitePair[AggregateCall, String]] = 
generateNamedAggregates
+    val partitionKeys: Array[Int] = firstWindow.keys.toArray
 
     val inputRowType = getInput.getRowType
-    super
+    val writer = super
       .explainTerms(pw)
       .itemIf(
         "partitionBy",
         RelExplainUtil.fieldToString(partitionKeys, inputRowType),
         partitionKeys.nonEmpty)
-      .item("orderBy", RelExplainUtil.collationToString(overWindow.orderKeys, 
inputRowType))
-      .item("window", RelExplainUtil.windowRangeToString(logicWindow, 
overWindow))
-      .item(
-        "select",
-        RelExplainUtil
-          .overAggregationToString(inputRowType, outputRowType, constants, 
namedAggregates))
-  }
+      .item("orderBy", RelExplainUtil.collationToString(firstWindow.orderKeys, 
inputRowType))
 
-  private def generateNamedAggregates: Seq[CalcitePair[AggregateCall, String]] 
= {
-    val overWindow: Group = logicWindow.groups.get(0)
+    if (logicWindow.groups.size() == 1) {
+      writer
+        .item("window", RelExplainUtil.windowRangeToString(logicWindow, 
firstWindow))
+        .item(
+          "select",
+          RelExplainUtil.overAggregationToString(
+            inputRowType,
+            outputRowType,
+            constants,
+            generateNamedAggregates(firstWindow, 0)))
+    } else {
+      var offset = inputRowType.getFieldCount
+      logicWindow.groups.asScala.zipWithIndex.foreach {
+        case (group, index) =>
+          val namedAggregates = generateNamedAggregates(group, index)
+          val select = RelExplainUtil.overAggregationToString(
+            inputRowType,
+            outputRowType,
+            constants,
+            namedAggregates,
+            outputInputName = false,
+            rowTypeOffset = offset)
+          offset += namedAggregates.size
+          writer.item(
+            "window#" + index,
+            select + RelExplainUtil.windowRangeToString(logicWindow, group))
+      }
+      writer.item("select", getRowType.getFieldNames.asScala.mkString(", "))
+    }
+  }
 
+  private def generateNamedAggregates(
+      overWindow: Group,
+      windowIndex: Int): Seq[CalcitePair[AggregateCall, String]] = {
     val aggregateCalls = overWindow.getAggregateCalls(logicWindow)
     for (i <- 0 until aggregateCalls.size())
-      yield new CalcitePair[AggregateCall, String](aggregateCalls.get(i), 
"w0$o" + i)
+      yield new CalcitePair[AggregateCall, String](aggregateCalls.get(i), 
s"w$windowIndex$$o$i")

Review Comment:
   why do we need it? The explain output is the same without it



##########
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/over/RowTimeMultiRangeBoundedPrecedingFunctionTest.java:
##########
@@ -0,0 +1,264 @@
+/*
+ * 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.flink.table.runtime.operators.over;
+
+import org.apache.flink.api.common.typeutils.base.LongSerializer;
+import org.apache.flink.runtime.state.AbstractKeyedStateBackend;
+import org.apache.flink.streaming.api.operators.KeyedProcessOperator;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.util.OneInputStreamOperatorTestHarness;
+import org.apache.flink.table.data.GenericRowData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.runtime.dataview.StateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateMapView;
+import org.apache.flink.table.runtime.generated.AggsHandleFunction;
+import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
+import org.apache.flink.table.runtime.util.RowDataHarnessAssertor;
+import org.apache.flink.table.types.logical.BigIntType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.VarCharType;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static 
org.apache.flink.table.runtime.util.StreamRecordUtils.insertRecord;
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Test for {@link RowTimeMultiRangeBoundedPrecedingFunction}. */
+class RowTimeMultiRangeBoundedPrecedingFunctionTest extends 
RowTimeOverWindowTestBase {
+
+    // input row: (key, value, rowtime); one aggregate value per window is 
appended
+    private static final RowDataHarnessAssertor ASSERTOR =
+            new RowDataHarnessAssertor(
+                    new LogicalType[] {
+                        VarCharType.STRING_TYPE,
+                        new BigIntType(),
+                        new BigIntType(),
+                        new BigIntType(),
+                        new BigIntType()
+                    });
+
+    private static final GeneratedAggsHandleFunction DISTINCT_COUNT_HANDLER =
+            new GeneratedAggsHandleFunction("Function", "", new Object[0]) {
+                @Override
+                public AggsHandleFunction newInstance(ClassLoader classLoader) 
{
+                    return new DistinctCountViewAggsHandleFunction(1);
+                }
+            };
+
+    @Test
+    void testEachWindowRetractsAtItsOwnRange() throws Exception {
+        OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
+                createTestHarness(aggsHandleFunction);
+        testHarness.open();
+
+        testHarness.processElement(insertRecord("key", 1L, 100L));
+        testHarness.processElement(insertRecord("key", 2L, 500L));
+        testHarness.processElement(insertRecord("key", 4L, 1200L));
+        testHarness.processWatermark(new Watermark(1500L));
+        // two rows at one timestamp share one result
+        testHarness.processElement(insertRecord("key", 8L, 2100L));
+        testHarness.processElement(insertRecord("key", 32L, 2100L));
+        testHarness.processElement(insertRecord("key", 16L, 3000L));
+        testHarness.processWatermark(new Watermark(3000L));
+
+        // windows: 1000 ms and 2000 ms; the row at 100 leaves the first 
window at 1200 but is
+        // still summed by the second window at 2100, and leaves it at 3000
+        List<Object> expected = new ArrayList<>();
+        expected.add(insertRecord("key", 1L, 100L, 1L, 1L));
+        expected.add(insertRecord("key", 2L, 500L, 3L, 3L));
+        expected.add(insertRecord("key", 4L, 1200L, 6L, 7L));
+        expected.add(new Watermark(1500L));
+        expected.add(insertRecord("key", 8L, 2100L, 44L, 47L));
+        expected.add(insertRecord("key", 32L, 2100L, 44L, 47L));
+        expected.add(insertRecord("key", 16L, 3000L, 56L, 60L));
+        expected.add(new Watermark(3000L));
+        ASSERTOR.assertOutputEquals("result mismatch", expected, 
testHarness.getOutput());
+        testHarness.close();
+    }
+
+    @Test
+    void testDataViewStatesAreSeparatedPerWindow() throws Exception {
+        // both handlers ask for a data view state with the same name; if they 
shared it, the
+        // first window's retraction would remove values the second window 
still counts
+        OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
+                createTestHarness(DISTINCT_COUNT_HANDLER);
+        testHarness.open();
+
+        testHarness.processElement(insertRecord("key", 1L, 100L));
+        testHarness.processElement(insertRecord("key", 2L, 500L));
+        testHarness.processElement(insertRecord("key", 4L, 1200L));
+        testHarness.processElement(insertRecord("key", 8L, 2100L));
+        testHarness.processElement(insertRecord("key", 16L, 3000L));
+        testHarness.processWatermark(new Watermark(3000L));
+
+        List<Object> expected = new ArrayList<>();
+        expected.add(insertRecord("key", 1L, 100L, 1L, 1L));
+        expected.add(insertRecord("key", 2L, 500L, 2L, 2L));
+        expected.add(insertRecord("key", 4L, 1200L, 2L, 3L));
+        expected.add(insertRecord("key", 8L, 2100L, 2L, 4L));
+        expected.add(insertRecord("key", 16L, 3000L, 2L, 3L));
+        expected.add(new Watermark(3000L));
+        ASSERTOR.assertOutputEquals("result mismatch", expected, 
testHarness.getOutput());
+        testHarness.close();
+    }
+
+    @Test
+    void testStateCleanup() throws Exception {
+        RowTimeMultiRangeBoundedPrecedingFunction<RowData> function =
+                createFunction(aggsHandleFunction);
+        KeyedProcessOperator<RowData, RowData, RowData> operator =
+                new KeyedProcessOperator<>(function);
+        OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
+                createTestHarness(operator);
+        testHarness.open();
+
+        AbstractKeyedStateBackend<?> stateBackend =
+                (AbstractKeyedStateBackend<?>) operator.getKeyedStateBackend();
+        assertThat(stateBackend.numKeyValueStateEntries()).isEqualTo(0);
+
+        testHarness.processElement(insertRecord("key", 1L, 100L));
+        testHarness.processElement(insertRecord("key", 1L, 500L));
+        testHarness.processWatermark(new Watermark(1000L));
+        assertThat(stateBackend.numKeyValueStateEntries()).isGreaterThan(0);
+
+        // the cleanup timer is set from the largest range (2000 ms) by the 
first row:
+        // 100 + 2000 * 1.5 + 1; a 1000 ms range would have fired it at 1601
+        testHarness.processWatermark(new Watermark(3100L));
+        assertThat(stateBackend.numKeyValueStateEntries()).isGreaterThan(0);
+        testHarness.processWatermark(new Watermark(3101L));
+        assertThat(stateBackend.numKeyValueStateEntries()).isEqualTo(0);
+        testHarness.close();
+    }
+
+    @Test
+    void testLateRecordMetrics() throws Exception {
+        RowTimeMultiRangeBoundedPrecedingFunction<RowData> function =
+                createFunction(aggsHandleFunction);
+        OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
+                createTestHarness(new KeyedProcessOperator<>(function));
+        testHarness.open();
+
+        testHarness.processElement(insertRecord("key", 1L, 100L));
+        testHarness.processElement(insertRecord("key", 1L, 500L));
+        testHarness.processWatermark(new Watermark(500L));
+        testHarness.processElement(insertRecord("key", 1L, 400L));
+
+        assertThat(function.getCounter().getCount()).isEqualTo(1L);
+        testHarness.close();
+    }
+
+    private RowTimeMultiRangeBoundedPrecedingFunction<RowData> createFunction(
+            GeneratedAggsHandleFunction handler) {
+        return new RowTimeMultiRangeBoundedPrecedingFunction<>(
+                new GeneratedAggsHandleFunction[] {handler, handler},
+                new LogicalType[][] {accTypes, accTypes},
+                inputFieldTypes,
+                new long[] {1000L, 2000L},
+                2);
+    }
+
+    private OneInputStreamOperatorTestHarness<RowData, RowData> 
createTestHarness(
+            GeneratedAggsHandleFunction handler) throws Exception {
+        return createTestHarness(new 
KeyedProcessOperator<>(createFunction(handler)));
+    }
+
+    /**
+     * Counts the distinct values of one field, kept in a data view state 
named like the ones that
+     * the code generator creates for the first aggregate of a handler.
+     */
+    private static class DistinctCountViewAggsHandleFunction implements 
AggsHandleFunction {

Review Comment:
   why do we need it? The ITCase already covers it: MAX(b) in w1 and in w3 both 
request agg1$map



##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/over/RowTimeMultiRangeBoundedPrecedingFunction.java:
##########
@@ -0,0 +1,346 @@
+/*
+ * 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.flink.table.runtime.operators.over;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.api.common.functions.OpenContext;
+import org.apache.flink.api.common.functions.RuntimeContext;
+import org.apache.flink.api.common.state.MapState;
+import org.apache.flink.api.common.state.MapStateDescriptor;
+import org.apache.flink.api.common.state.ValueState;
+import org.apache.flink.api.common.state.ValueStateDescriptor;
+import org.apache.flink.api.common.typeinfo.Types;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.typeutils.ListTypeInfo;
+import org.apache.flink.metrics.Counter;
+import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.utils.JoinedRowData;
+import org.apache.flink.table.runtime.dataview.PerKeyStateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateDataViewStore;
+import org.apache.flink.table.runtime.dataview.StateListView;
+import org.apache.flink.table.runtime.dataview.StateMapView;
+import org.apache.flink.table.runtime.generated.AggsHandleFunction;
+import org.apache.flink.table.runtime.generated.GeneratedAggsHandleFunction;
+import org.apache.flink.table.runtime.typeutils.InternalTypeInfo;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.util.Collector;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Process function for several event-time bounded RANGE OVER windows that 
share the same partition
+ * and order key but have different preceding offsets.
+ *
+ * <p>E.g.: SELECT SUM(c) OVER (PARTITION BY b ORDER BY rowtime RANGE BETWEEN 
INTERVAL '10' MINUTE
+ * PRECEDING AND CURRENT ROW), SUM(c) OVER (PARTITION BY b ORDER BY rowtime 
RANGE BETWEEN INTERVAL
+ * '30' MINUTE PRECEDING AND CURRENT ROW) FROM T.
+ *
+ * <p>The input rows are stored once and kept for the largest offset. Each 
window keeps its own
+ * accumulators and retracts a row when the row leaves that window's range.
+ */
+public class RowTimeMultiRangeBoundedPrecedingFunction<K>
+        extends KeyedProcessFunction<K, RowData, RowData> {
+    private static final long serialVersionUID = 1L;
+
+    private static final Logger LOG =
+            
LoggerFactory.getLogger(RowTimeMultiRangeBoundedPrecedingFunction.class);
+
+    private static final String LATE_ELEMENTS_DROPPED_METRIC_NAME = 
"numLateRecordsDropped";
+
+    private final GeneratedAggsHandleFunction[] genAggsHandlers;
+    private final LogicalType[][] accTypes;
+    private final LogicalType[] inputFieldTypes;
+    private final long[] precedingOffsets;
+    private final long maxPrecedingOffset;
+    private final int rowTimeIdx;
+
+    private transient JoinedRowData output;
+    private transient AggsHandleFunction[] functions;
+    private transient RowData[] aggValues;
+    private transient JoinedRowData[] aggValueJoins;
+
+    private transient ValueState<Long> lastTriggeringTsState;
+    // the last timestamp whose rows have been aggregated and emitted; every 
window has retracted
+    // exactly the rows that were out of its range at that timestamp
+    private transient ValueState<Long> lastProcessedTsState;
+    private transient ValueState<Long> cleanupTsState;
+    private transient List<ValueState<RowData>> accStates;

Review Comment:
   nit: functions is an array, accStates is a List. Could we be consistent?



##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecOverAggregate.java:
##########
@@ -572,4 +556,110 @@ private KeyedProcessFunction<RowData, RowData, RowData> 
createBoundedOverProcess
                 throw new TableException("Unsupported bounded operation for 
OVER window.");
         }
     }
+
+    /**
+     * Create a ProcessFunction that evaluates several bounded event-time 
RANGE OVER windows, which
+     * share the partition and order key, and stores the input rows once.
+     */
+    private KeyedProcessFunction<RowData, RowData, RowData>
+            createMultiRangeBoundedOverProcessFunction(
+                    PlannerBase planner,
+                    List<RexLiteral> constants,
+                    RowType aggInputType,
+                    RowType inputType,
+                    int rowTimeIdx,
+                    ExecNodeConfig config) {
+        final List<OverSpec.GroupSpec> groups = overSpec.getGroups();
+        final int n = groups.size();
+        final GeneratedAggsHandleFunction[] genAggsHandlers = new 
GeneratedAggsHandleFunction[n];
+        final LogicalType[][] accTypes = new LogicalType[n][];
+        final long[] precedingOffsets = new long[n];
+        for (int i = 0; i < n; i++) {
+            final OverSpec.GroupSpec group = groups.get(i);
+            final Object boundValue =
+                    OverAggregateUtil.getBoundary(overSpec, 
group.getLowerBound());
+            if (boundValue instanceof BigDecimal) {
+                throw new TableException(
+                        "the specific value is decimal which haven not 
supported yet.");

Review Comment:
   nit: this is a copy-paste of L257, including the typo. Could we extract a 
method?



##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/plan/rules/physical/stream/StreamPhysicalOverAggregateRule.scala:
##########
@@ -42,18 +44,16 @@ class StreamPhysicalOverAggregateRule(config: Config) 
extends ConverterRule(conf
   override def matches(call: RelOptRuleCall): Boolean = {

Review Comment:
   StreamPhysicalPythonOverAggregateRule#matches still checks only 
groups.get(0). As a result SELECT SUM(a) OVER w1, pandas_agg(a, b) OVER w2 ... 
now fails with CannotPlanException, while before it failed with a proper error 
message. Could you fix it and add a test?



##########
flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/runtime/stream/sql/OverAggregateITCase.scala:
##########
@@ -601,6 +601,92 @@ class OverAggregateITCase(mode: StateBackendMode, 
unboundedOverVersion: Int)
     assertThat(sink.getAppendResults.sorted).isEqualTo(expected.sorted)
   }
 
+  @TestTemplate
+  def testRowTimeBoundedMultipleRangeOver(): Unit = {

Review Comment:
   ITCase is an old-fashioned approach, and Scala is deprecated. Please use a 
TableTestProgram instead.
   Could you also interleave windows in the SELECT, e.g. SUM(v) OVER w30, 
SUM(v) OVER w10, MAX(v) OVER w30?



##########
flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/runtime/stream/sql/OverAggregateITCase.scala:
##########
@@ -601,6 +601,92 @@ class OverAggregateITCase(mode: StateBackendMode, 
unboundedOverVersion: Int)
     assertThat(sink.getAppendResults.sorted).isEqualTo(expected.sorted)
   }
 
+  @TestTemplate
+  def testRowTimeBoundedMultipleRangeOver(): Unit = {
+    val data: Seq[Either[(Long, (Long, Int, String)), Long]] = Seq(
+      Left((1500L, (1L, 15, "Hello"))),
+      Left((1600L, (1L, 16, "Hello"))),
+      Left((1000L, (1L, 1, "Hello"))),
+      Left((2000L, (2L, 2, "Hello"))),
+      Right(1000L),
+      Left((2000L, (2L, 2, "Hello"))),
+      Left((2000L, (2L, 3, "Hello"))),
+      Left((3000L, (3L, 3, "Hello"))),
+      Right(2000L),
+      Left((4000L, (4L, 4, "Hello"))),
+      Right(3000L),
+      Left((5000L, (5L, 5, "Hello"))),
+      Right(5000L),
+      Left((6000L, (6L, 6, "Hello"))),
+      Left((6500L, (6L, 65, "Hello"))),
+      Right(7000L),
+      Left((9000L, (6L, 9, "Hello"))),
+      Left((9500L, (6L, 18, "Hello"))),
+      Left((9000L, (6L, 9, "Hello"))),
+      Right(10000L),
+      Left((10000L, (7L, 7, "Hello World"))),
+      Left((11000L, (7L, 17, "Hello World"))),
+      Left((11000L, (7L, 77, "Hello World"))),
+      Right(12000L),
+      Left((14000L, (7L, 18, "Hello World"))),
+      Right(14000L),
+      Left((15000L, (8L, 8, "Hello World"))),
+      Right(17000L),
+      Left((20000L, (20L, 20, "Hello World"))),
+      Right(19000L)
+    )
+
+    val source = failingDataSource(data)
+    val t1 = source
+      .transform(
+        "TimeAssigner",
+        implicitly[TypeInformation[(Long, Int, String)]],
+        new EventTimeProcessOperator[(Long, Int, String)])
+      .setParallelism(source.getParallelism)
+      .toTable(tEnv, 'a, 'b, 'c, 'rowtime.rowtime)
+    tEnv.createTemporaryView("T1", t1)
+
+    def range(seconds: Int): String =
+      s"PARTITION BY c ORDER BY rowtime " +
+        s"RANGE BETWEEN INTERVAL '$seconds' SECOND PRECEDING AND CURRENT ROW"
+
+    // MAX with retraction and COUNT(DISTINCT) keep data views in state, which 
must not clash
+    // between the windows that share one operator
+    val multiWindowQuery =
+      s"""
+         |SELECT c, b,
+         |  SUM(a) OVER w1, MAX(b) OVER w1,
+         |  SUM(a) OVER w2, COUNT(DISTINCT b) OVER w2,
+         |  AVG(b) OVER w3, MAX(b) OVER w3
+         |FROM T1
+         |WINDOW w1 AS (${range(1)}), w2 AS (${range(2)}), w3 AS (${range(3)})
+         |""".stripMargin
+
+    // the same windows, one per nested query, as users have to write it 
without shared state
+    val nestedQuery =
+      s"""
+         |SELECT c, b, s1, m1, s2, d2,
+         |  AVG(b) OVER (${range(3)}), MAX(b) OVER (${range(3)})
+         |FROM (
+         |  SELECT *, SUM(a) OVER (${range(2)}) AS s2, COUNT(DISTINCT b) OVER 
(${range(2)}) AS d2
+         |  FROM (
+         |    SELECT *, SUM(a) OVER (${range(1)}) AS s1, MAX(b) OVER 
(${range(1)}) AS m1
+         |    FROM T1))
+         |""".stripMargin
+
+    assertThat(tEnv.explainSql(multiWindowQuery)).contains("window#2")

Review Comment:
   could it be a plan test with XML instead?
   Also please add negative cases (proctime, ROWS + RANGE, unbounded + bounded, 
different PARTITION BY) and check the full exception message



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to