WencongLiu commented on code in PR #23000:
URL: https://github.com/apache/flink/pull/23000#discussion_r1321166055


##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/SimpleOperatorFactory.java:
##########
@@ -132,4 +134,12 @@ public void setInputType(TypeInformation<?> type, 
ExecutionConfig executionConfi
     public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader 
classLoader) {
         return operator.getClass();
     }
+
+    @Override
+    public OperatorAttributes getOperatorAttributes() {
+        if (operatorAttributes == null) {
+            operatorAttributes = operator.getOperatorAttributes();
+        }
+        return operatorAttributes;

Review Comment:
   If the `OperatorAttributes ` is a concept inside `StreamOperator`, why we 
put the `operatorAttributes` in the `SimpleOperatorFactory` ? Currently it's 
always unused in `SimpleOperatorFactory`.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/OperatorAttributes.java:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.Experimental;
+
+/**
+ * OperatorAttributes element provides Job Manager with information that can 
be used to optimize job
+ * performance.
+ */
+@Experimental
+public class OperatorAttributes {
+
+    private final boolean outputOnEOF;
+    private final boolean internalSorterSupported;
+
+    public OperatorAttributes(boolean isOutputOnEOF, boolean 
internalSorterSupported) {
+        this.outputOnEOF = isOutputOnEOF;
+        this.internalSorterSupported = internalSorterSupported;
+    }
+
+    /**
+     * Returns true iff the operator can only emit records after inputs have 
reached EOF.
+     *
+     * <p>Here are the implications when it is true:
+     *
+     * <ul>
+     *   <li>The results of this operator as well as its upstream operators 
have blocking partition
+     *       type.
+     *   <li>This operator as well as its upstream operators will be executed 
in batch mode.
+     * </ul>
+     */
+    public boolean isOutputOnEOF() {
+        return outputOnEOF;
+    }
+
+    /**
+     * Returns true iff the operator uses an internal sorter to sort inputs by 
key when any of the

Review Comment:
   `iff` -> `if`



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/OperatorAttributesBuilder.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.Experimental;
+import org.apache.flink.streaming.api.graph.StreamingJobGraphGenerator;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+/** The builder class for {@link OperatorAttributes}. */
+@Experimental
+public class OperatorAttributesBuilder {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(StreamingJobGraphGenerator.class);

Review Comment:
   `private static final Logger LOG = 
LoggerFactory.getLogger(OperatorAttributesBuilder.class);`



##########
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/datastream/CoGroupedStreamsTest.java:
##########
@@ -81,4 +82,20 @@ public void testSetAllowedLateness() {
         Assert.assertEquals(
                 lateness.toMilliseconds(), 
withLateness.getAllowedLateness().toMilliseconds());
     }
+
+    @Test
+    public void testEndOfStreamWindowsCoGroup() {

Review Comment:
   if there should be another test `testEndOfStreamWindowsAggregate`?



##########
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java:
##########
@@ -2035,7 +2039,11 @@ public void startCheckpointScheduler() {
             stopCheckpointScheduler();
 
             periodicScheduling = true;
-            scheduleTriggerWithDelay(clock.relativeTimeMillis(), 
getRandomInitDelay());
+            if (withRandomDelay) {
+                scheduleTriggerWithDelay(clock.relativeTimeMillis(), 
getRandomInitDelay());
+            } else {

Review Comment:
   Could you please explain why this change is needed? 🤔 Thanks.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/sort/EOFAggregationOperator.java:
##########
@@ -0,0 +1,185 @@
+/*
+ * 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.functions.AggregateFunction;
+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.core.memory.ManagedMemoryUseCase;
+import org.apache.flink.runtime.io.disk.iomanager.IOManager;
+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.runtime.util.NonReusingKeyGroupedIterator;
+import org.apache.flink.streaming.api.graph.StreamConfig;
+import org.apache.flink.streaming.api.operators.AbstractUdfStreamOperator;
+import org.apache.flink.streaming.api.operators.BoundedOneInput;
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator;
+import org.apache.flink.streaming.api.operators.OperatorAttributes;
+import org.apache.flink.streaming.api.operators.OperatorAttributesBuilder;
+import org.apache.flink.streaming.api.operators.Output;
+import org.apache.flink.streaming.api.operators.TimestampedCollector;
+import org.apache.flink.streaming.api.watermark.Watermark;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.streaming.runtime.tasks.StreamTask;
+import org.apache.flink.util.MutableObjectIterator;
+
+/**
+ * This operator would replace the regular Aggregate process when the 
WindowAssigner is
+ * EndOfStreamWindows.
+ */
+@Internal
+public class EOFAggregationOperator<IN, KEY, ACC, OUT>
+        extends AbstractUdfStreamOperator<OUT, AggregateFunction<IN, ACC, OUT>>
+        implements OneInputStreamOperator<IN, OUT>, BoundedOneInput {
+
+    private PushSorter<Tuple2<byte[], StreamRecord<IN>>> sorter;
+    TypeSerializer<Tuple2<byte[], StreamRecord<IN>>> keyAndValueSerializer;
+    TypeComparator<Tuple2<byte[], StreamRecord<IN>>> comparator;
+    private KeySelector<IN, KEY> keySelector;
+    private TypeSerializer<KEY> keySerializer;
+    private DataOutputSerializer dataOutputSerializer;
+    private long lastWatermarkTimestamp = Long.MIN_VALUE;
+
+    public EOFAggregationOperator(AggregateFunction<IN, ACC, OUT> 
userFunction) {
+        super(userFunction);
+    }
+
+    @Override
+    public void setup(
+            StreamTask<?, ?> containingTask,
+            StreamConfig config,
+            Output<StreamRecord<OUT>> output) {
+        super.setup(containingTask, config, output);
+        ClassLoader userCodeClassLoader = 
containingTask.getUserCodeClassLoader();
+        MemoryManager memoryManager = 
containingTask.getEnvironment().getMemoryManager();
+        IOManager ioManager = containingTask.getEnvironment().getIOManager();
+
+        keySelector = (KeySelector<IN, KEY>) config.getStatePartitioner(0, 
userCodeClassLoader);
+        keySerializer = config.getStateKeySerializer(userCodeClassLoader);
+        int keyLength = keySerializer.getLength();
+
+        TypeSerializer<IN> typeSerializerA = config.getTypeSerializerIn(0, 
userCodeClassLoader);
+        keyAndValueSerializer = new KeyAndValueSerializer<>(typeSerializerA, 
keyLength);
+
+        if (keyLength > 0) {
+            dataOutputSerializer = new DataOutputSerializer(keyLength);
+            comparator = new FixedLengthByteKeyComparator<>(keyLength);
+        } else {
+            dataOutputSerializer = new DataOutputSerializer(64);
+            comparator = new VariableLengthByteKeyComparator<>();
+        }
+
+        ExecutionConfig executionConfig = 
containingTask.getEnvironment().getExecutionConfig();
+
+        double managedMemoryFraction =
+                config.getManagedMemoryFractionOperatorUseCaseOfSlot(
+                        ManagedMemoryUseCase.OPERATOR,
+                        containingTask.getEnvironment().getTaskConfiguration(),
+                        userCodeClassLoader);
+
+        Configuration jobConfiguration = 
containingTask.getEnvironment().getJobConfiguration();
+
+        try {
+            sorter =
+                    ExternalSorter.newBuilder(
+                                    memoryManager,
+                                    containingTask,
+                                    keyAndValueSerializer,
+                                    comparator,
+                                    executionConfig)
+                            .memoryFraction(managedMemoryFraction)
+                            .enableSpilling(
+                                    ioManager,
+                                    
jobConfiguration.get(AlgorithmOptions.SORT_SPILLING_THRESHOLD))
+                            .maxNumFileHandles(
+                                    
jobConfiguration.get(AlgorithmOptions.SPILLING_MAX_FAN))
+                            
.objectReuse(executionConfig.isObjectReuseEnabled())
+                            .largeRecords(
+                                    jobConfiguration.get(
+                                            
AlgorithmOptions.USE_LARGE_RECORDS_HANDLER))
+                            .build();
+        } catch (MemoryAllocationException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public void endInput() throws Exception {
+        sorter.finishReading();
+        MutableObjectIterator<Tuple2<byte[], StreamRecord<IN>>> iterator = 
sorter.getIterator();
+        TimestampedCollector<OUT> outputCollector = new 
TimestampedCollector<>(output);
+        NonReusingKeyGroupedIterator<Tuple2<byte[], StreamRecord<IN>>> 
keyGroupedIterator =
+                new NonReusingKeyGroupedIterator<>(iterator, comparator);
+
+        while (keyGroupedIterator.nextKey()) {
+            ACC acc = userFunction.createAccumulator();
+            NonReusingKeyGroupedIterator<Tuple2<byte[], 
StreamRecord<IN>>>.ValuesIterator records =
+                    keyGroupedIterator.getValues();
+            for (Tuple2<byte[], StreamRecord<IN>> record : records) {
+                acc = userFunction.add(record.f1.getValue(), acc);
+            }
+            outputCollector.collect(userFunction.getResult(acc));
+        }
+
+        Watermark watermark = new Watermark(lastWatermarkTimestamp);
+        if (getTimeServiceManager().isPresent()) {
+            getTimeServiceManager().get().advanceWatermark(watermark);

Review Comment:
   If the user choose to use `EndOfStreamWindows`, there shouldn't be any 
registered timers. As a result, the TimeService may be useless. WDYT?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/operators/windowing/WindowOperatorBuilder.java:
##########
@@ -346,4 +347,10 @@ public String generateOperatorDescription(Function 
function1, @Nullable Function
     public long getAllowedLateness() {
         return allowedLateness;
     }
+
+    public boolean canApplyEndOfStreamOperator() {
+        return windowAssigner instanceof EndOfStreamWindows
+                && trigger instanceof EndOfStreamWindows.EndOfStreamTrigger
+                && evictor == null;

Review Comment:
   I think we'd better check that we shouldn't use user-defined trigger if the 
`windowAssigner `  is `EndOfStreamWindows` in `public void trigger(Trigger<? 
super T, ? super W> trigger) {`
   
   Currently, `EndOfStreamWindows` and `EndOfStreamTrigger` are a fixed 
combination, right?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/OperatorAttributes.java:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.Experimental;
+
+/**
+ * OperatorAttributes element provides Job Manager with information that can 
be used to optimize job
+ * performance.

Review Comment:
   It is preferable to specify the specific aspect or dimension of the job that 
can be optimized.



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/OperatorAttributes.java:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.Experimental;
+
+/**
+ * OperatorAttributes element provides Job Manager with information that can 
be used to optimize job
+ * performance.
+ */
+@Experimental
+public class OperatorAttributes {
+
+    private final boolean outputOnEOF;
+    private final boolean internalSorterSupported;
+
+    public OperatorAttributes(boolean isOutputOnEOF, boolean 
internalSorterSupported) {
+        this.outputOnEOF = isOutputOnEOF;
+        this.internalSorterSupported = internalSorterSupported;
+    }
+
+    /**
+     * Returns true iff the operator can only emit records after inputs have 
reached EOF.

Review Comment:
   `iff` -> `if`



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/graph/StreamingJobGraphGenerator.java:
##########
@@ -1472,15 +1500,35 @@ private ResultPartitionType 
getResultPartitionType(StreamEdge edge) {
             case HYBRID_SELECTIVE:
                 return ResultPartitionType.HYBRID_SELECTIVE;
             case UNDEFINED:
-                return 
determineUndefinedResultPartitionType(edge.getPartitioner());
+                return determineUndefinedResultPartitionType(edge);
             default:
                 throw new UnsupportedOperationException(
                         "Data exchange mode " + edge.getExchangeMode() + " is 
not supported yet.");
         }
     }
 
-    private ResultPartitionType determineUndefinedResultPartitionType(
-            StreamPartitioner<?> partitioner) {
+    private ResultPartitionType 
determineUndefinedResultPartitionType(StreamEdge edge) {
+        if (outputBlockingNodesID.contains(edge.getSourceId())) {
+            // use corresponding partition type if the upstream node outputs 
EOF
+            
edge.setBufferTimeout(ExecutionOptions.DISABLED_NETWORK_BUFFER_TIMEOUT);
+            if (!outputBlockingNodesID.contains(edge.getTargetId())) {
+                return ResultPartitionType.BLOCKING;
+            }

Review Comment:
   `            if (!outputBlockingNodesID.contains(edge.getTargetId())) {
                   return ResultPartitionType.BLOCKING;
               }`
     Why we need to check the downstream operator when the 
outputBlockingNodesID contains `edge.getSourceId()` ?



##########
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/translators/OneInputTransformationTranslator.java:
##########
@@ -50,24 +50,47 @@ public Collection<Integer> translateForBatchInternal(
                         keySelector,
                         transformation.getStateKeyType(),
                         context);
-        boolean isKeyed = keySelector != null;
-        if (isKeyed) {
-            BatchExecutionUtils.applyBatchExecutionSettings(
-                    transformation.getId(), context, 
StreamConfig.InputRequirement.SORTED);
-        }
+
+        maybeApplyBatchExecutionSettings(transformation, context);
 
         return ids;
     }
 
     @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);
+        Collection<Integer> ids =
+                translateInternal(
+                        transformation,
+                        transformation.getOperatorFactory(),
+                        transformation.getInputType(),
+                        transformation.getStateKeySelector(),
+                        transformation.getStateKeyType(),
+                        context);
+
+        if (transformation.isOutputOnEOF()) {
+            // Try to apply batch execution settings for streaming mode 
transformation.
+            maybeApplyBatchExecutionSettings(transformation, context);
+        }
+
+        return ids;
+    }
+
+    private void maybeApplyBatchExecutionSettings(
+            final OneInputTransformation<IN, OUT> transformation, final 
Context context) {
+        KeySelector<IN, ?> keySelector = transformation.getStateKeySelector();
+        boolean isKeyed = keySelector != null;
+        if (isKeyed) {
+            StreamConfig.InputRequirement inputRequirement;
+            if (!transformation.isInternalSorterSupported()) {
+                inputRequirement = StreamConfig.InputRequirement.SORTED;
+            } else {
+                // The inputs of transformation don't require 
InputRequirement.SORTED
+                // if the transformation support internal sorter.
+                inputRequirement = StreamConfig.InputRequirement.PASS_THROUGH;
+            }

Review Comment:
   Actually, these logic above can also covered by 
`BatchExecutionUtils#getInputRequirements` like 
`TwoInputTransformationTranslator` and `MultiInputTransformationTranslator`.



##########
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinator.java:
##########
@@ -2035,7 +2039,11 @@ public void startCheckpointScheduler() {
             stopCheckpointScheduler();
 
             periodicScheduling = true;
-            scheduleTriggerWithDelay(clock.relativeTimeMillis(), 
getRandomInitDelay());
+            if (withRandomDelay) {
+                scheduleTriggerWithDelay(clock.relativeTimeMillis(), 
getRandomInitDelay());
+            } else {

Review Comment:
   Could you please explain why this change is needed? 🤔 Thanks.



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