xintongsong commented on code in PR #23521:
URL: https://github.com/apache/flink/pull/23521#discussion_r1406042500


##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/streamrecord/RecordAttributes.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.streaming.runtime.streamrecord;
+
+import org.apache.flink.annotation.Experimental;
+
+import java.util.Objects;
+
+/**
+ * A RecordAttributes element provides stream task with information that can 
be used to optimize the
+ * stream task's performance.
+ */
+@Experimental
+public class RecordAttributes extends StreamElement {
+    private final boolean backlog;

Review Comment:
   Minor: I'd suggest the name `isBacklog`.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/source/event/BacklogEvent.java:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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.runtime.source.event;
+
+import org.apache.flink.runtime.operators.coordination.OperatorEvent;
+
+import java.util.Objects;
+
+/** A source event that notify the source operator of the backlog status. */
+public class BacklogEvent implements OperatorEvent {
+
+    private static final long serialVersionUID = 1L;
+    private final boolean backlog;
+
+    public BacklogEvent(boolean backlog) {
+        this.backlog = backlog;
+    }
+
+    public boolean isBacklog() {
+        return backlog;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        final BacklogEvent that = (BacklogEvent) o;
+        return Objects.equals(backlog, that.backlog);
+    }

Review Comment:
   It would be a good practice to always implement the `hashCode()` together 
with `equals`, in case the class is accidentally used for a hash-map/set.



##########
flink-runtime/src/test/java/org/apache/flink/runtime/source/coordinator/SourceCoordinatorContextTest.java:
##########
@@ -261,4 +262,26 @@ private List<ReaderInfo> registerReaders() {
 
         return infos;
     }
+
+    @Test
+    void testSetIsProcessingBacklog() throws Exception {
+        sourceReady();
+        registerReader(0, 0);
+        context.setIsProcessingBacklog(true);
+
+        Thread.sleep(10); // sleep a little for the coordinator to handle 
reader register event.

Review Comment:
   Such sleep-based approach is usually problematic. If the time is too short, 
this could become a source of instability. If the time is too long, it slows 
down the entire CI.
   
   I'd suggest to keep checking whether the expected condition is reached with 
a short interval, and to fail if the condition is not reached within a relative 
long timeout.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/streamrecord/RecordAttributes.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.streaming.runtime.streamrecord;
+
+import org.apache.flink.annotation.Experimental;
+
+import java.util.Objects;
+
+/**
+ * A RecordAttributes element provides stream task with information that can 
be used to optimize the
+ * stream task's performance.
+ */

Review Comment:
   The semantic here is a bit vague. Given the name `RecordAttributes`, this 
class should provide information about some records. The question is which 
records it describes? IIUC, the information for RA_i should apply to all 
records received between RA_i and RA_i+1. This should be explicitly explained 
as part of the class JavaDoc.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/source/event/BacklogEvent.java:
##########
@@ -0,0 +1,54 @@
+/*
+ * 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.runtime.source.event;
+
+import org.apache.flink.runtime.operators.coordination.OperatorEvent;
+
+import java.util.Objects;
+
+/** A source event that notify the source operator of the backlog status. */
+public class BacklogEvent implements OperatorEvent {
+
+    private static final long serialVersionUID = 1L;
+    private final boolean backlog;

Review Comment:
   Minor: I'd name this field (and corresponding method arguments) 
`isProcessingBacklog`.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SourceOperator.java:
##########
@@ -569,6 +571,14 @@ public void handleOperatorEvent(OperatorEvent event) {
             sourceReader.handleSourceEvents(((SourceEventWrapper) 
event).getSourceEvent());
         } else if (event instanceof NoMoreSplitsEvent) {
             sourceReader.notifyNoMoreSplits();
+        } else if (event instanceof BacklogEvent) {
+            if (eventTimeLogic != null) {
+                eventTimeLogic.triggerPeriodicEmit(System.currentTimeMillis());
+            }

Review Comment:
   IIUC, this is to always trigger an emit of watermark upon changing of 
`isBacklog`? I think it was fine with the method `triggerPeriodicEmit` when the 
method is private to `ProgressiveTimestampsAndWatermarks` and is only used for 
`scheduleWithFixedDelay`. However, when it turns into a public method, the name 
becomes confusing. How could a PERIODIC thing being manually triggered in a 
non-periodical way? It might make sense to simply rename this method to 
something like `emitImmediateWatermark`.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/Output.java:
##########
@@ -55,4 +57,13 @@ public interface Output<T> extends Collector<T> {
     <X> void collect(OutputTag<X> outputTag, StreamRecord<X> record);
 
     void emitLatencyMarker(LatencyMarker latencyMarker);
+
+    /**
+     * Emits a {@link RecordAttributes} from an operator. This element is 
broadcast to all
+     * downstream operators.
+     */
+    @Experimental
+    default void emitRecordAttributes(RecordAttributes recordAttributes) {
+        throw new UnsupportedOperationException();
+    }

Review Comment:
   I think an `Output` is meant to be called by users, but should never be 
implemented by users. You might need to double-check on this, because I'm not 
100% sure.
   
   I'm bringing this up because, if this is never implemented by users, we 
don't need to provide such a default implementation that only throws an error. 
Otherwise, if there are chances that this is implemented by users, then this is 
a breaking change because the method can be called by framework and thus the 
error will be thrown anyway.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/sort/SortingDataInput.java:
##########
@@ -183,6 +184,9 @@ public void emitWatermarkStatus(WatermarkStatus 
watermarkStatus) {}
 
         @Override
         public void emitLatencyMarker(LatencyMarker latencyMarker) {}
+
+        @Override
+        public void emitRecordAttributes(RecordAttributes recordAttributes) {}

Review Comment:
   Just trying to understand. Is it possible that a `SortingDataInput` or a 
`MultiInputSortingDataInput` receive a `RecordAttributes`? If yes, what happens 
given that we are not forwarding it? If not, we may consider adding some sanity 
checks.



##########
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/sort/CollectionDataInput.java:
##########
@@ -53,6 +53,10 @@ public DataInputStatus emitNext(DataOutput<E> output) throws 
Exception {
                 output.emitRecord(streamElement.asRecord());
             } else if (streamElement instanceof Watermark) {
                 output.emitWatermark(streamElement.asWatermark());
+            } else if (streamElement.isRecordAttributes()) {
+                
output.emitRecordAttributes(streamElement.asRecordAttributes());
+            } else if (streamElement.isWatermarkStatus()) {
+                output.emitWatermarkStatus(streamElement.asWatermarkStatus());

Review Comment:
   How does this relate to this PR? Is this a fix of a previous bug? If yes, 
this should be placed in a separate hotfix commit before other commits.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/RecordAttributesValve.java:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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.streaming.runtime.io;
+
+import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput.DataOutput;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributesBuilder;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+
+/**
+ * RecordAttributesValve combine RecordAttributes from different input 
channels. If any of the input
+ * channels is non backlog, the combined RecordAttributes is non backlog.
+ *
+ * <p>Currently, we only support switching the backlog status from null to 
backlog and backlog to
+ * non-backlog. Switching from non-backlog to backlog is not support at the 
moment, and it will be
+ * ignored.
+ */
+public class RecordAttributesValve {

Review Comment:
   1. The name doesn't really reflect what the class does. I'd suggest 
something like `RecordAttributesCombiner`.
   2. Note that `RecordAttributes` is a general-purpose class for carrying not 
only `isBacklog` but more possible attributes in future. Therefore, the 
class-wise JavaDoc should be more focused on how in general `RecordAttributes` 
are combined. The detailed strategy for combining individual attributes can be 
documented elsewhere, e.g. a dedicated private method.



##########
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/io/StreamTaskNetworkInputTest.java:
##########
@@ -318,6 +320,56 @@ public void testBatchProcessingRecordsCanBeInterrupted() 
throws Exception {
         
assertThat(output.getNumberOfEmittedRecords()).isEqualTo(expectedElementCount * 
2);
     }
 
+    @Test
+    public void testProcessRecordAttributes() throws Exception {
+        int numInputChannels = 2;
+        LongSerializer inSerializer = LongSerializer.INSTANCE;
+        StreamTestSingleInputGate<Long> inputGate =
+                new StreamTestSingleInputGate<>(numInputChannels, 0, 
inSerializer, 1024);
+        StreamTaskNetworkInput<Long> input =
+                new StreamTaskNetworkInput<>(
+                        createCheckpointedInputGate(inputGate.getInputGate()),
+                        inSerializer,
+                        ioManager,
+                        new StatusWatermarkValve(numInputChannels),
+                        0,
+                        () -> true);
+
+        final CollectingDataOutput<Long> output = new CollectingDataOutput<>();
+
+        inputGate.sendElement(
+                new 
RecordAttributesBuilder(Collections.emptyList()).setBacklog(true).build(), 0);
+        input.emitNext(output);
+        assertThat(output.getEvents()).isEmpty();
+
+        inputGate.sendElement(new StreamRecord<>(0L, 0), 1);
+        inputGate.sendElement(
+                new 
RecordAttributesBuilder(Collections.emptyList()).setBacklog(true).build(), 1);
+        inputGate.sendElement(new StreamRecord<>(1L, 1), 1);
+        inputGate.sendElement(new StreamRecord<>(2L, 2), 1);
+        input.emitNext(output);
+        assertThat(output.getEvents())
+                .containsExactly(
+                        new StreamRecord<>(0L, 0),
+                        new RecordAttributesBuilder(Collections.emptyList())
+                                .setBacklog(true)
+                                .build());

Review Comment:
   Minor:
   I'd suggest to make these StreamRecord / RecordAttributes local variables, 
rather that creating duplicated objects for `sendElement` and assertions.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/TimestampsAndWatermarks.java:
##########
@@ -80,6 +80,9 @@ ReaderOutput<T> createMainOutput(
     /** Stops emitting periodic watermarks. */
     void stopPeriodicWatermarkEmits();
 
+    /** Trigger a periodicEmit immediately. */
+    default void triggerPeriodicEmit(long wallClockTimestamp) {}

Review Comment:
   Why providing a default implementation?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/sort/SortingBacklogDataInput.java:
##########
@@ -0,0 +1,330 @@
+/*
+ * 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.streaming.api.operators.sort;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.api.common.typeutils.TypeComparator;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.AlgorithmOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.memory.DataOutputSerializer;
+import org.apache.flink.runtime.checkpoint.CheckpointException;
+import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter;
+import org.apache.flink.runtime.io.AvailabilityProvider;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable;
+import org.apache.flink.runtime.memory.MemoryAllocationException;
+import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.operators.sort.ExternalSorter;
+import org.apache.flink.runtime.operators.sort.PushSorter;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.runtime.io.DataInputStatus;
+import org.apache.flink.streaming.runtime.io.StreamTaskInput;
+import 
org.apache.flink.streaming.runtime.streamrecord.InternalRecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributesBuilder;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.streaming.runtime.tasks.StreamTask;
+import org.apache.flink.streaming.runtime.watermarkstatus.WatermarkStatus;
+import org.apache.flink.util.ExceptionUtils;
+import org.apache.flink.util.MutableObjectIterator;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nonnull;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.concurrent.CompletableFuture;
+
+/**
+ * SortingBacklogDataInput forwards the input records to output util it switch 
to backlog
+ * processing. During backlog processing, it buffers and sorts the input 
records and outputs the
+ * sorted records to the downstream when switching to non backlog processing.
+ */
+@Internal
+public class SortingBacklogDataInput<T, K> implements StreamTaskInput<T> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SortingBacklogDataInput.class);
+
+    private final StreamTaskInput<T> wrappedInput;
+    private final PushSorter<Tuple2<byte[], StreamRecord<T>>> sorter;
+    private final KeySelector<T, K> keySelector;
+    private final TypeSerializer<K> keySerializer;
+    private final DataOutputSerializer dataOutputSerializer;

Review Comment:
   Minor: These fields can be inner to `SortingDataOutput`.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/RecordAttributesValve.java:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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.streaming.runtime.io;
+
+import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput.DataOutput;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributesBuilder;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+
+/**
+ * RecordAttributesValve combine RecordAttributes from different input 
channels. If any of the input
+ * channels is non backlog, the combined RecordAttributes is non backlog.
+ *
+ * <p>Currently, we only support switching the backlog status from null to 
backlog and backlog to
+ * non-backlog. Switching from non-backlog to backlog is not support at the 
moment, and it will be
+ * ignored.
+ */
+public class RecordAttributesValve {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(RecordAttributesValve.class);
+
+    private final int numInputChannels;
+    private final RecordAttributes[] allChannelRecordAttributes;
+
+    private int backlogChannelsCnt = 0;
+    private RecordAttributes lastOutputAttributes = null;
+
+    public RecordAttributesValve(int numInputChannels) {
+        this.numInputChannels = numInputChannels;
+        this.allChannelRecordAttributes = new 
RecordAttributes[numInputChannels];
+    }
+
+    public void inputRecordAttributes(
+            RecordAttributes recordAttributes, int channelIdx, DataOutput<?> 
output)
+            throws Exception {
+        LOG.debug("RecordAttributes: {} from channel idx: {}", 
recordAttributes, channelIdx);
+        RecordAttributes lastChannelRecordAttributes = 
allChannelRecordAttributes[channelIdx];
+        allChannelRecordAttributes[channelIdx] = recordAttributes;
+
+        if (lastChannelRecordAttributes == null) {
+            lastChannelRecordAttributes =
+                    new 
RecordAttributesBuilder(Collections.emptyList()).build();
+        }
+
+        if (lastChannelRecordAttributes.isBacklog() == 
recordAttributes.isBacklog()) {
+            return;
+        }
+
+        if (recordAttributes.isBacklog()) {
+            backlogChannelsCnt += 1;
+        } else {
+            backlogChannelsCnt -= 1;
+        }
+
+        if (lastOutputAttributes == null && backlogChannelsCnt != 
numInputChannels) {
+            return;
+        }
+
+        final RecordAttributesBuilder builder =
+                new RecordAttributesBuilder(Collections.emptyList());
+        builder.setBacklog(backlogChannelsCnt >= numInputChannels);

Review Comment:
   This means iff all input channels are in `isBacklog=true` status will the 
task see `isBacklog=true`. Why is that? Did I missed anything from the FLIP?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/translators/BacklogUtils.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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.streaming.runtime.translators;
+
+import org.apache.flink.api.dag.Transformation;
+import org.apache.flink.configuration.ExecutionOptions;
+import org.apache.flink.configuration.ReadableConfig;
+import org.apache.flink.core.memory.ManagedMemoryUseCase;
+import org.apache.flink.streaming.api.graph.StreamConfig;
+import org.apache.flink.streaming.api.graph.StreamNode;
+import org.apache.flink.streaming.api.graph.TransformationTranslator;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import static 
org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions.CHECKPOINTING_INTERVAL_DURING_BACKLOG;
+
+/** A utility class for applying sorting inputs during backlog processing. */
+public class BacklogUtils {
+    public static boolean isCheckpointDisableDuringBacklog(
+            TransformationTranslator.Context context) {
+        return 
context.getGraphGeneratorConfig().get(CHECKPOINTING_INTERVAL_DURING_BACKLOG) != 
null
+                && context.getGraphGeneratorConfig()
+                        .get(CHECKPOINTING_INTERVAL_DURING_BACKLOG)
+                        .isZero();
+    }
+
+    public static void applyBacklogProcessingSettings(
+            Transformation<?> transformation,
+            TransformationTranslator.Context context,
+            StreamNode node) {
+        node.addInputRequirement(0, 
StreamConfig.InputRequirement.SORTED_DURING_BACKLOG);
+        Map<ManagedMemoryUseCase, Integer> operatorScopeUseCaseWeights = new 
HashMap<>();
+        Integer operatorMemoryWeights =
+                transformation
+                        .getManagedMemoryOperatorScopeUseCaseWeights()
+                        .get(ManagedMemoryUseCase.OPERATOR);
+        operatorScopeUseCaseWeights.put(
+                ManagedMemoryUseCase.OPERATOR,
+                operatorMemoryWeights == null
+                        ? deriveMemoryWeight(context.getGraphGeneratorConfig())
+                        : operatorMemoryWeights);

Review Comment:
   Does this mean if the operator is already configured with some managed 
memory, we will not require more memory for the sorter? Then what if both the 
operator and the sorting input needs managed memory? How do they share the 
memory?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/graph/StreamGraphGenerator.java:
##########
@@ -415,6 +417,12 @@ private void configureStreamGraphStreaming(final 
StreamGraph graph) {
         graph.setCheckpointStorage(checkpointStorage);
         graph.setSavepointDirectory(savepointDir);
         
graph.setGlobalStreamExchangeMode(deriveGlobalStreamExchangeModeStreaming());
+
+        if (Duration.ZERO.equals(
+                configuration.get(
+                        
ExecutionCheckpointingOptions.CHECKPOINTING_INTERVAL_DURING_BACKLOG))) {

Review Comment:
   Same here for deciding whether to enable the mixed mode.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/InternalBacklogAwareTimerServiceImpl.java:
##########
@@ -0,0 +1,138 @@
+/*
+ * 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.streaming.api.operators;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.util.function.BiConsumerWithException;
+
+/**
+ * InternalBacklogAwareTimerServiceImpl is the implementation of 
InternalTimerService that manages
+ * event time timers differently under different backlog status. It manages 
the processing time
+ * timers in the same way as the {@link InternalTimerServiceImpl}.
+ *
+ * <p>The backlog status is false at the beginning. When backlog status is 
false, the timer services
+ * is the same as the {@link InternalTimerServiceImpl}, where event time 
timers are triggered as the
+ * watermark advancing.
+ *
+ * <p>When backlog status switch to true, the timer service manages event time 
timer with a single
+ * active key at a time. When the active key changed, all the event time 
timers of the last key are
+ * triggered up to the maximum watermark during backlog processing.
+ *
+ * <p>When the backlog status switch from true to false, all the event time 
timers of the last key
+ * are triggered up to the maximum watermark during backlog processing. And 
the current watermark of
+ * the timer service will be the maximum watermark during backlog processing.
+ */
+@Internal
+public class InternalBacklogAwareTimerServiceImpl<K, N> implements 
InternalTimerService<N> {

Review Comment:
   TBH, I'm not a big fan of inherit. The problem is that, by directly 
accessing protected fields of the superclass from the subclasses, the contract 
between the classes becomes obscure. As subclass can see internals of the 
superclass, changes to the superclass can easily break things that subclasses 
depend on thus cause problems, and such issues are very hard to avoid.
   
   In many cases, an inherit approach can be replaced by an equivalent approach 
based on composition, which has clearer contracts between classes. But 
admittedly it's no always possible and sometimes gets costly.
   
   For the classes below, I guess I haven't spent enough time to explore 
whether it's possible to switch to a composition based approach. Do you think 
it's feasible?
   - `BacklogTimeService`
   - `BatchExecutionInternalTimeService`
   - `InternalBacklogAwareTimerServiceManagerImpl`
   - `InternalTimeServiceManagerImpl`



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/streamrecord/RecordAttributesBuilder.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.streaming.runtime.streamrecord;
+
+import org.apache.flink.annotation.Experimental;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+
+/** The builder class for {@link RecordAttributes}. */
+@Experimental
+public class RecordAttributesBuilder {
+    private static final Logger LOG = 
LoggerFactory.getLogger(RecordAttributesBuilder.class);
+    private final List<RecordAttributes> lastRecordAttributesOfInputs;
+    @Nullable private Boolean backlog = null;
+
+    /**
+     * This constructor takes a list of the last recordAttributes received 
from each of the
+     * operator's inputs. When this list is not empty, it will be used to 
determine the default

Review Comment:
   By "each of the operator's input", does this mean logical or physical 
inputs? Asked differently, is the list size corresponds to number of input 
edges of the job graph or execution graph?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/InternalTimerServiceImpl.java:
##########
@@ -396,6 +396,10 @@ public int numEventTimeTimers(N namespace) {
         return countTimersInNamespaceInternal(namespace, eventTimeTimersQueue);
     }
 
+    public KeyGroupedInternalPriorityQueue<TimerHeapInternalTimer<K, N>> 
getEventTimeTimersQueue() {
+        return eventTimeTimersQueue;
+    }

Review Comment:
   It feels hacky to expose an internal queue from one component and use it to 
construct another component. If the queue is meant to be shared, I think the 
correct way is to create the queue out side the two components and pass it in 
as constructor arguments.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/BacklogTimeService.java:
##########
@@ -0,0 +1,91 @@
+/*
+ * 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.streaming.api.operators;
+
+import org.apache.flink.runtime.state.KeyGroupedInternalPriorityQueue;
+import 
org.apache.flink.streaming.api.operators.sorted.state.BatchExecutionInternalTimeService;
+import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * An implementation of a {@link InternalTimerService} that manages timers 
with a single active key
+ * at a time. This is used by {@link
+ * 
org.apache.flink.streaming.api.operators.InternalBacklogAwareTimerServiceImpl} 
during backlog
+ * processing.
+ */
+class BacklogTimeService<K, N> extends BatchExecutionInternalTimeService<K, N> 
{
+    private long maxWatermarkDuringBacklog;
+
+    public BacklogTimeService(
+            ProcessingTimeService processingTimeService,
+            Triggerable<K, N> triggerTarget,
+            KeyGroupedInternalPriorityQueue<TimerHeapInternalTimer<K, N>> 
eventTimeTimersQueue) {
+        super(processingTimeService, triggerTarget, eventTimeTimersQueue, 
null);
+    }
+
+    @Override
+    public void registerProcessingTimeTimer(N namespace, long time) {
+        throw new UnsupportedOperationException(
+                "BacklogTimeService does not support registering processing 
timer.");
+    }
+
+    @Override
+    public void deleteProcessingTimeTimer(N namespace, long time) {
+        throw new UnsupportedOperationException(
+                "BacklogTimeService does not support deleting processing 
timer.");
+    }
+
+    /**
+     * Set the current key of the time service. If the new key is different 
from the last key, all
+     * the event time timers of the last key whose timestamp is less than or 
equal to the max
+     * watermark during backlog are triggered.
+     */
+    public void setCurrentKey(K newKey) throws Exception {
+        if (newKey != null && newKey.equals(currentKey)) {
+            return;
+        }
+
+        TimerHeapInternalTimer<K, N> timer;
+        List<TimerHeapInternalTimer<K, N>> skippedTimers = new LinkedList<>();
+        if (currentKey != null) {
+            while ((timer = eventTimeTimersQueue.peek()) != null
+                    && timer.getTimestamp() <= maxWatermarkDuringBacklog) {
+                eventTimeTimersQueue.poll();
+
+                if (timer.getKey() != currentKey) {
+                    skippedTimers.add(timer);
+                } else {
+                    triggerTarget.onEventTime(timer);
+                }
+            }
+            eventTimeTimersQueue.addAll(skippedTimers);
+        }
+
+        if (newKey == null) {
+            currentWatermark = maxWatermarkDuringBacklog;
+        }

Review Comment:
   What does `newKey == null` mean? And why we need to update the current 
watermark under such condition?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/streamrecord/RecordAttributesBuilder.java:
##########
@@ -0,0 +1,77 @@
+/*
+ * 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.streaming.runtime.streamrecord;
+
+import org.apache.flink.annotation.Experimental;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.List;
+
+/** The builder class for {@link RecordAttributes}. */
+@Experimental
+public class RecordAttributesBuilder {
+    private static final Logger LOG = 
LoggerFactory.getLogger(RecordAttributesBuilder.class);
+    private final List<RecordAttributes> lastRecordAttributesOfInputs;
+    @Nullable private Boolean backlog = null;
+
+    /**
+     * This constructor takes a list of the last recordAttributes received 
from each of the
+     * operator's inputs. When this list is not empty, it will be used to 
determine the default

Review Comment:
   Either way, it would be better to clearly explain this in JavaDoc.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/RecordAttributesValve.java:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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.streaming.runtime.io;
+
+import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput.DataOutput;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributesBuilder;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+
+/**
+ * RecordAttributesValve combine RecordAttributes from different input 
channels. If any of the input
+ * channels is non backlog, the combined RecordAttributes is non backlog.
+ *
+ * <p>Currently, we only support switching the backlog status from null to 
backlog and backlog to
+ * non-backlog. Switching from non-backlog to backlog is not support at the 
moment, and it will be
+ * ignored.
+ */
+public class RecordAttributesValve {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(RecordAttributesValve.class);
+
+    private final int numInputChannels;
+    private final RecordAttributes[] allChannelRecordAttributes;
+
+    private int backlogChannelsCnt = 0;
+    private RecordAttributes lastOutputAttributes = null;
+
+    public RecordAttributesValve(int numInputChannels) {
+        this.numInputChannels = numInputChannels;
+        this.allChannelRecordAttributes = new 
RecordAttributes[numInputChannels];
+    }
+
+    public void inputRecordAttributes(
+            RecordAttributes recordAttributes, int channelIdx, DataOutput<?> 
output)
+            throws Exception {
+        LOG.debug("RecordAttributes: {} from channel idx: {}", 
recordAttributes, channelIdx);
+        RecordAttributes lastChannelRecordAttributes = 
allChannelRecordAttributes[channelIdx];
+        allChannelRecordAttributes[channelIdx] = recordAttributes;
+
+        if (lastChannelRecordAttributes == null) {
+            lastChannelRecordAttributes =
+                    new 
RecordAttributesBuilder(Collections.emptyList()).build();
+        }
+
+        if (lastChannelRecordAttributes.isBacklog() == 
recordAttributes.isBacklog()) {
+            return;
+        }
+
+        if (recordAttributes.isBacklog()) {
+            backlogChannelsCnt += 1;
+        } else {
+            backlogChannelsCnt -= 1;
+        }
+
+        if (lastOutputAttributes == null && backlogChannelsCnt != 
numInputChannels) {
+            return;
+        }
+
+        final RecordAttributesBuilder builder =
+                new RecordAttributesBuilder(Collections.emptyList());
+        builder.setBacklog(backlogChannelsCnt >= numInputChannels);
+        final RecordAttributes outputAttribute = builder.build();
+        if (lastOutputAttributes == null
+                || lastOutputAttributes.isBacklog() != 
outputAttribute.isBacklog()) {
+            if (lastOutputAttributes != null && 
!lastOutputAttributes.isBacklog()) {
+                LOG.warn(
+                        "Switching from non-backlog to backlog is currently 
not supported. Backlog status remains.");
+                return;
+            }

Review Comment:
   The warning can easily get ignored. I'd suggest to fail fast.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/source/ProgressiveTimestampsAndWatermarks.java:
##########
@@ -152,7 +152,7 @@ public void stopPeriodicWatermarkEmits() {
         }
     }
 
-    void triggerPeriodicEmit(@SuppressWarnings("unused") long 
wallClockTimestamp) {
+    public void triggerPeriodicEmit(@SuppressWarnings("unused") long 
wallClockTimestamp) {

Review Comment:
   `@Override`



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/sort/SortingBacklogDataInput.java:
##########
@@ -0,0 +1,330 @@
+/*
+ * 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.streaming.api.operators.sort;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.api.common.typeutils.TypeComparator;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.AlgorithmOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.memory.DataOutputSerializer;
+import org.apache.flink.runtime.checkpoint.CheckpointException;
+import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter;
+import org.apache.flink.runtime.io.AvailabilityProvider;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable;
+import org.apache.flink.runtime.memory.MemoryAllocationException;
+import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.operators.sort.ExternalSorter;
+import org.apache.flink.runtime.operators.sort.PushSorter;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.runtime.io.DataInputStatus;
+import org.apache.flink.streaming.runtime.io.StreamTaskInput;
+import 
org.apache.flink.streaming.runtime.streamrecord.InternalRecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributesBuilder;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.streaming.runtime.tasks.StreamTask;
+import org.apache.flink.streaming.runtime.watermarkstatus.WatermarkStatus;
+import org.apache.flink.util.ExceptionUtils;
+import org.apache.flink.util.MutableObjectIterator;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nonnull;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.concurrent.CompletableFuture;
+
+/**
+ * SortingBacklogDataInput forwards the input records to output util it switch 
to backlog
+ * processing. During backlog processing, it buffers and sorts the input 
records and outputs the
+ * sorted records to the downstream when switching to non backlog processing.
+ */
+@Internal
+public class SortingBacklogDataInput<T, K> implements StreamTaskInput<T> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SortingBacklogDataInput.class);
+
+    private final StreamTaskInput<T> wrappedInput;
+    private final PushSorter<Tuple2<byte[], StreamRecord<T>>> sorter;
+    private final KeySelector<T, K> keySelector;
+    private final TypeSerializer<K> keySerializer;
+    private final DataOutputSerializer dataOutputSerializer;
+    private final SortingDataOutput sortingDataOutput;
+    private final StreamTask.CanEmitBatchOfRecordsChecker 
canEmitBatchOfRecords;
+    private MutableObjectIterator<Tuple2<byte[], StreamRecord<T>>> sortedInput 
= null;
+    private long watermarkSeenDuringBacklog = Long.MIN_VALUE;
+    private WatermarkStatus lastWatermarkStatusDuringBacklog = null;
+    private volatile OperatingMode mode = OperatingMode.PROCESSING_REALTIME;
+
+    private enum OperatingMode {
+
+        // We are processing realtime data, all the input data pass through 
immediately.

Review Comment:
   Minor: Use JavaDoc, so that IDE prompts the documents when the cursor stays 
over a enum value.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/streamrecord/InternalRecordAttributes.java:
##########
@@ -0,0 +1,67 @@
+/*
+ * 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.streaming.runtime.streamrecord;
+
+import org.apache.flink.annotation.Internal;
+
+import java.util.Objects;
+
+/** The RecordAttributes that contains extra information to be used 
internally. */
+@Internal
+public class InternalRecordAttributes extends RecordAttributes {
+    private final long maxWatermarkDuringBacklog;
+
+    public InternalRecordAttributes(boolean backlog, long 
maxWatermarkDuringBacklog) {
+        super(backlog);
+        this.maxWatermarkDuringBacklog = maxWatermarkDuringBacklog;
+    }
+
+    public long getMaxWatermarkDuringBacklog() {
+        return maxWatermarkDuringBacklog;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        if (!super.equals(o)) {
+            return false;
+        }
+        InternalRecordAttributes that = (InternalRecordAttributes) o;
+        return maxWatermarkDuringBacklog == that.maxWatermarkDuringBacklog;
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(super.hashCode(), maxWatermarkDuringBacklog);
+    }
+
+    @Override
+    public String toString() {
+        return "InternalRecordAttributes{"
+                + "backlog="
+                + isBacklog()

Review Comment:
   This is fragile because when updating the superclass developers may not 
notice they need to also change the subclass.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/sort/SortingBacklogDataInput.java:
##########
@@ -0,0 +1,330 @@
+/*
+ * 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.streaming.api.operators.sort;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.api.common.ExecutionConfig;
+import org.apache.flink.api.common.typeutils.TypeComparator;
+import org.apache.flink.api.common.typeutils.TypeSerializer;
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.api.java.tuple.Tuple2;
+import org.apache.flink.configuration.AlgorithmOptions;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.core.memory.DataOutputSerializer;
+import org.apache.flink.runtime.checkpoint.CheckpointException;
+import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter;
+import org.apache.flink.runtime.io.AvailabilityProvider;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+import org.apache.flink.runtime.jobgraph.tasks.TaskInvokable;
+import org.apache.flink.runtime.memory.MemoryAllocationException;
+import org.apache.flink.runtime.memory.MemoryManager;
+import org.apache.flink.runtime.operators.sort.ExternalSorter;
+import org.apache.flink.runtime.operators.sort.PushSorter;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.runtime.io.DataInputStatus;
+import org.apache.flink.streaming.runtime.io.StreamTaskInput;
+import 
org.apache.flink.streaming.runtime.streamrecord.InternalRecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.LatencyMarker;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributesBuilder;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.streaming.runtime.tasks.StreamTask;
+import org.apache.flink.streaming.runtime.watermarkstatus.WatermarkStatus;
+import org.apache.flink.util.ExceptionUtils;
+import org.apache.flink.util.MutableObjectIterator;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nonnull;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.concurrent.CompletableFuture;
+
+/**
+ * SortingBacklogDataInput forwards the input records to output util it switch 
to backlog
+ * processing. During backlog processing, it buffers and sorts the input 
records and outputs the
+ * sorted records to the downstream when switching to non backlog processing.
+ */
+@Internal
+public class SortingBacklogDataInput<T, K> implements StreamTaskInput<T> {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(SortingBacklogDataInput.class);
+
+    private final StreamTaskInput<T> wrappedInput;
+    private final PushSorter<Tuple2<byte[], StreamRecord<T>>> sorter;
+    private final KeySelector<T, K> keySelector;
+    private final TypeSerializer<K> keySerializer;
+    private final DataOutputSerializer dataOutputSerializer;
+    private final SortingDataOutput sortingDataOutput;
+    private final StreamTask.CanEmitBatchOfRecordsChecker 
canEmitBatchOfRecords;
+    private MutableObjectIterator<Tuple2<byte[], StreamRecord<T>>> sortedInput 
= null;
+    private long watermarkSeenDuringBacklog = Long.MIN_VALUE;
+    private WatermarkStatus lastWatermarkStatusDuringBacklog = null;
+    private volatile OperatingMode mode = OperatingMode.PROCESSING_REALTIME;
+
+    private enum OperatingMode {
+
+        // We are processing realtime data, all the input data pass through 
immediately.
+        PROCESSING_REALTIME,
+
+        // We are processing backlog data, all the input data are put in the 
sorter.
+        SORTING_BACKLOG,
+
+        // We are switching from backlog processing to realtime processing, 
the data input the
+        // sorter are flushing to the downstream.
+        FLUSHING_BACKLOG

Review Comment:
   Trying to understand this. The reason we have a mode for switching from 
backlog to realtime but not for the other way around is that, switching from 
realtime to backlog is expected to be completed immediately, while switching 
from backlog to realtime takes time for emitting the buffered / sorted results. 
Is that correct?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/RecordAttributesValve.java:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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.streaming.runtime.io;
+
+import org.apache.flink.streaming.runtime.io.PushingAsyncDataInput.DataOutput;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributes;
+import org.apache.flink.streaming.runtime.streamrecord.RecordAttributesBuilder;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+
+/**
+ * RecordAttributesValve combine RecordAttributes from different input 
channels. If any of the input
+ * channels is non backlog, the combined RecordAttributes is non backlog.
+ *
+ * <p>Currently, we only support switching the backlog status from null to 
backlog and backlog to
+ * non-backlog. Switching from non-backlog to backlog is not support at the 
moment, and it will be
+ * ignored.
+ */
+public class RecordAttributesValve {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(RecordAttributesValve.class);
+
+    private final int numInputChannels;
+    private final RecordAttributes[] allChannelRecordAttributes;
+
+    private int backlogChannelsCnt = 0;
+    private RecordAttributes lastOutputAttributes = null;
+
+    public RecordAttributesValve(int numInputChannels) {
+        this.numInputChannels = numInputChannels;
+        this.allChannelRecordAttributes = new 
RecordAttributes[numInputChannels];
+    }
+
+    public void inputRecordAttributes(
+            RecordAttributes recordAttributes, int channelIdx, DataOutput<?> 
output)
+            throws Exception {
+        LOG.debug("RecordAttributes: {} from channel idx: {}", 
recordAttributes, channelIdx);
+        RecordAttributes lastChannelRecordAttributes = 
allChannelRecordAttributes[channelIdx];
+        allChannelRecordAttributes[channelIdx] = recordAttributes;
+
+        if (lastChannelRecordAttributes == null) {
+            lastChannelRecordAttributes =
+                    new 
RecordAttributesBuilder(Collections.emptyList()).build();
+        }

Review Comment:
   Minor:
   1. Why not initialize the array with empty record-attributes, so that we 
avoid this if-statement for each incoming record-attributes?
   2. It seems `new RecordAttributesBuilder(Collections.emptyList()).build()` 
is used a lot. We may consider introduce a static singleton instance, to avoid 
unnecessary object creations.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/translators/OneInputTransformationTranslator.java:
##########
@@ -62,12 +63,19 @@ public Collection<Integer> translateForBatchInternal(
     @Override
     public Collection<Integer> translateForStreamingInternal(
             final OneInputTransformation<IN, OUT> transformation, final 
Context context) {
-        return translateInternal(
-                transformation,
-                transformation.getOperatorFactory(),
-                transformation.getInputType(),
-                transformation.getStateKeySelector(),
-                transformation.getStateKeyType(),
-                context);
+        final KeySelector<IN, ?> keySelector = 
transformation.getStateKeySelector();
+        final Collection<Integer> ids =
+                translateInternal(
+                        transformation,
+                        transformation.getOperatorFactory(),
+                        transformation.getInputType(),
+                        keySelector,
+                        transformation.getStateKeyType(),
+                        context);
+        final StreamNode node = 
context.getStreamGraph().getStreamNode(transformation.getId());
+        if (keySelector != null && 
BacklogUtils.isCheckpointDisableDuringBacklog(context)) {
+            BacklogUtils.applyBacklogProcessingSettings(transformation, 
context, node);
+        }

Review Comment:
   I'd suggest to decouple whether to enable mixed mode from the 
checkpoint-during-backlog as much as possible. As I suggested in the FLIP 
discussion, it is only a current strategy to enable the mixed mode when 
checkpointing.interval-during-backlog == 0 (&& runtime-mode == streaming). 
However, this may change in future. It would be nice to have a centralized 
position to decide whether to enable the mixed mode (from whatever inputs it 
needs), and just read the result from everywhere else.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/io/AbstractStreamTaskNetworkInput.java:
##########
@@ -141,19 +145,34 @@ public DataInputStatus emitNext(DataOutput<T> output) 
throws Exception {
         }
     }
 
-    private void processElement(StreamElement recordOrMark, DataOutput<T> 
output) throws Exception {
-        if (recordOrMark.isRecord()) {
-            output.emitRecord(recordOrMark.asRecord());
-        } else if (recordOrMark.isWatermark()) {
+    /**
+     * Process the given stream element and returns whether to continue 
processing the next stream
+     * element without returning from the emitNext method.
+     */
+    private boolean processElement(StreamElement streamElement, DataOutput<T> 
output)
+            throws Exception {
+        if (streamElement.isRecord()) {
+            output.emitRecord(streamElement.asRecord());
+            return true;
+        } else if (streamElement.isWatermark()) {
             statusWatermarkValve.inputWatermark(
-                    recordOrMark.asWatermark(), 
flattenedChannelIndices.get(lastChannel), output);
-        } else if (recordOrMark.isLatencyMarker()) {
-            output.emitLatencyMarker(recordOrMark.asLatencyMarker());
-        } else if (recordOrMark.isWatermarkStatus()) {
+                    streamElement.asWatermark(), 
flattenedChannelIndices.get(lastChannel), output);
+            return true;
+        } else if (streamElement.isLatencyMarker()) {
+            output.emitLatencyMarker(streamElement.asLatencyMarker());
+            return true;
+        } else if (streamElement.isWatermarkStatus()) {
             statusWatermarkValve.inputWatermarkStatus(
-                    recordOrMark.asWatermarkStatus(),
+                    streamElement.asWatermarkStatus(),
                     flattenedChannelIndices.get(lastChannel),
                     output);
+            return true;
+        } else if (streamElement.isRecordAttributes()) {
+            recordAttributesValve.inputRecordAttributes(
+                    streamElement.asRecordAttributes(),
+                    flattenedChannelIndices.get(lastChannel),
+                    output);
+            return false;

Review Comment:
   IIUC, the purpose here is to break the record processing and provide 
operators a chance to change their behavior right after the record-attribute 
(i.e. change of the isBacklog status).
   
   To make this easier to understand, I'd suggest:
   - Update the JavaDoc for this method, explain why we would want to stop 
processing and return from the emitNext method.
   - rename the local variable `canContinue` in `emitNext` to something like 
`breakBatchRecordEmitting`.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/BacklogTimeService.java:
##########
@@ -0,0 +1,91 @@
+/*
+ * 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.streaming.api.operators;
+
+import org.apache.flink.runtime.state.KeyGroupedInternalPriorityQueue;
+import 
org.apache.flink.streaming.api.operators.sorted.state.BatchExecutionInternalTimeService;
+import org.apache.flink.streaming.runtime.tasks.ProcessingTimeService;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * An implementation of a {@link InternalTimerService} that manages timers 
with a single active key
+ * at a time. This is used by {@link
+ * 
org.apache.flink.streaming.api.operators.InternalBacklogAwareTimerServiceImpl} 
during backlog
+ * processing.
+ */
+class BacklogTimeService<K, N> extends BatchExecutionInternalTimeService<K, N> 
{
+    private long maxWatermarkDuringBacklog;
+
+    public BacklogTimeService(
+            ProcessingTimeService processingTimeService,
+            Triggerable<K, N> triggerTarget,
+            KeyGroupedInternalPriorityQueue<TimerHeapInternalTimer<K, N>> 
eventTimeTimersQueue) {
+        super(processingTimeService, triggerTarget, eventTimeTimersQueue, 
null);
+    }
+
+    @Override
+    public void registerProcessingTimeTimer(N namespace, long time) {
+        throw new UnsupportedOperationException(
+                "BacklogTimeService does not support registering processing 
timer.");
+    }
+
+    @Override
+    public void deleteProcessingTimeTimer(N namespace, long time) {
+        throw new UnsupportedOperationException(
+                "BacklogTimeService does not support deleting processing 
timer.");
+    }
+
+    /**
+     * Set the current key of the time service. If the new key is different 
from the last key, all
+     * the event time timers of the last key whose timestamp is less than or 
equal to the max
+     * watermark during backlog are triggered.
+     */
+    public void setCurrentKey(K newKey) throws Exception {

Review Comment:
   `@Override`



##########
flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/runtime/utils/TimeTestUtil.scala:
##########
@@ -98,6 +98,8 @@ object TimeTestUtil {
       }
     }
 
+    override def processRecordAttributes(recordAttributes: RecordAttributes): 
Unit =
+      super.processRecordAttributes(recordAttributes)

Review Comment:
   I'm not familiar with Scala. What is this for? Shouldn't the method from the 
super class be called anyway if we don't override it?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/translators/OneInputTransformationTranslator.java:
##########
@@ -62,12 +63,19 @@ public Collection<Integer> translateForBatchInternal(
     @Override
     public Collection<Integer> translateForStreamingInternal(
             final OneInputTransformation<IN, OUT> transformation, final 
Context context) {
-        return translateInternal(
-                transformation,
-                transformation.getOperatorFactory(),
-                transformation.getInputType(),
-                transformation.getStateKeySelector(),
-                transformation.getStateKeyType(),
-                context);
+        final KeySelector<IN, ?> keySelector = 
transformation.getStateKeySelector();
+        final Collection<Integer> ids =
+                translateInternal(
+                        transformation,
+                        transformation.getOperatorFactory(),
+                        transformation.getInputType(),
+                        keySelector,
+                        transformation.getStateKeyType(),
+                        context);
+        final StreamNode node = 
context.getStreamGraph().getStreamNode(transformation.getId());
+        if (keySelector != null && 
BacklogUtils.isCheckpointDisableDuringBacklog(context)) {
+            BacklogUtils.applyBacklogProcessingSettings(transformation, 
context, node);
+        }

Review Comment:
   Same for `ReduceTransformationTranslator`.



-- 
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