gyfora commented on code in PR #502:
URL: 
https://github.com/apache/flink-kubernetes-operator/pull/502#discussion_r1066574644


##########
flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/JobVertexScaler.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.kubernetes.operator.autoscaler;
+
+import org.apache.flink.annotation.VisibleForTesting;
+import org.apache.flink.configuration.Configuration;
+import 
org.apache.flink.kubernetes.operator.autoscaler.config.AutoScalerOptions;
+import 
org.apache.flink.kubernetes.operator.autoscaler.metrics.EvaluatedScalingMetric;
+import org.apache.flink.kubernetes.operator.autoscaler.metrics.ScalingMetric;
+import org.apache.flink.kubernetes.operator.autoscaler.utils.AutoScalerUtils;
+import org.apache.flink.runtime.jobgraph.JobVertexID;
+import org.apache.flink.util.Preconditions;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneId;
+import java.util.Map;
+import java.util.SortedMap;
+
+import static 
org.apache.flink.kubernetes.operator.autoscaler.config.AutoScalerOptions.MAX_SCALE_DOWN_FACTOR;
+import static 
org.apache.flink.kubernetes.operator.autoscaler.config.AutoScalerOptions.SCALE_UP_GRACE_PERIOD;
+import static 
org.apache.flink.kubernetes.operator.autoscaler.config.AutoScalerOptions.TARGET_UTILIZATION;
+import static 
org.apache.flink.kubernetes.operator.autoscaler.config.AutoScalerOptions.VERTEX_MAX_PARALLELISM;
+import static 
org.apache.flink.kubernetes.operator.autoscaler.config.AutoScalerOptions.VERTEX_MIN_PARALLELISM;
+import static 
org.apache.flink.kubernetes.operator.autoscaler.metrics.ScalingMetric.EXPECTED_PROCESSING_RATE;
+import static 
org.apache.flink.kubernetes.operator.autoscaler.metrics.ScalingMetric.MAX_PARALLELISM;
+import static 
org.apache.flink.kubernetes.operator.autoscaler.metrics.ScalingMetric.PARALLELISM;
+import static 
org.apache.flink.kubernetes.operator.autoscaler.metrics.ScalingMetric.TRUE_PROCESSING_RATE;
+
+/** Component responsible for computing vertex parallelism based on the 
scaling metrics. */
+public class JobVertexScaler {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(JobVertexScaler.class);
+
+    private Clock clock = Clock.system(ZoneId.systemDefault());
+
+    public int computeScaleTargetParallelism(
+            Configuration conf,
+            JobVertexID vertex,
+            Map<ScalingMetric, EvaluatedScalingMetric> evaluatedMetrics,
+            SortedMap<Instant, ScalingSummary> history) {
+
+        var currentParallelism = (int) 
evaluatedMetrics.get(PARALLELISM).getCurrent();
+        double averageTrueProcessingRate = 
evaluatedMetrics.get(TRUE_PROCESSING_RATE).getAverage();
+        if (Double.isNaN(averageTrueProcessingRate)) {
+            LOG.info(
+                    "True processing rate is not available for {}, cannot 
compute new parallelism",
+                    vertex);
+            return currentParallelism;
+        }
+
+        double targetCapacity =
+                AutoScalerUtils.getTargetProcessingCapacity(
+                        evaluatedMetrics, conf, conf.get(TARGET_UTILIZATION), 
true);
+        if (Double.isNaN(targetCapacity)) {
+            LOG.info(
+                    "Target data rate is not available for {}, cannot compute 
new parallelism",
+                    vertex);
+            return currentParallelism;
+        }
+
+        LOG.info("Target processing capacity for {} is {}", vertex, 
targetCapacity);
+        double scaleFactor = targetCapacity / averageTrueProcessingRate;
+        double minScaleFactor = 1 - conf.get(MAX_SCALE_DOWN_FACTOR);
+        if (scaleFactor < minScaleFactor) {
+            LOG.info(
+                    "Computed scale factor of {} for {} is capped by maximum 
scale down factor to {}",
+                    scaleFactor,
+                    vertex,
+                    minScaleFactor);
+            scaleFactor = minScaleFactor;
+        }
+
+        int newParallelism =
+                scale(
+                        currentParallelism,
+                        (int) 
evaluatedMetrics.get(MAX_PARALLELISM).getCurrent(),
+                        scaleFactor,
+                        conf.getInteger(VERTEX_MIN_PARALLELISM),
+                        conf.getInteger(VERTEX_MAX_PARALLELISM));
+
+        if (newParallelism == currentParallelism
+                || blockScalingBasedOnPastActions(
+                        vertex,
+                        conf,
+                        evaluatedMetrics,
+                        history,
+                        currentParallelism,
+                        newParallelism)) {
+            return currentParallelism;
+        }
+
+        // We record our expectations for this scaling operation
+        evaluatedMetrics.put(
+                ScalingMetric.EXPECTED_PROCESSING_RATE, 
EvaluatedScalingMetric.of(targetCapacity));
+        return newParallelism;
+    }
+
+    private boolean blockScalingBasedOnPastActions(
+            JobVertexID vertex,
+            Configuration conf,
+            Map<ScalingMetric, EvaluatedScalingMetric> evaluatedMetrics,
+            SortedMap<Instant, ScalingSummary> history,
+            int currentParallelism,
+            int newParallelism) {
+
+        // If we don't have past scaling actions for this vertex, there is 
nothing to do
+        if (history.isEmpty()) {
+            return false;
+        }
+
+        boolean scaleUp = currentParallelism < newParallelism;
+
+        return detectImmediateScaleDownAfterScaleUp(vertex, conf, history, 
scaleUp)
+                || detectIneffectiveScaleup(vertex, conf, evaluatedMetrics, 
history, scaleUp);
+    }
+
+    private boolean detectImmediateScaleDownAfterScaleUp(
+            JobVertexID vertex,
+            Configuration conf,
+            SortedMap<Instant, ScalingSummary> history,
+            boolean scaleUp) {
+
+        // Does not apply to scale up operations
+        if (scaleUp) {
+            return false;
+        }
+
+        var lastScalingTs = history.lastKey();
+        var lastSummary = history.get(lastScalingTs);
+
+        boolean lastScaleUp = lastSummary.getNewParallelism() > 
lastSummary.getCurrentParallelism();
+        if (!lastScaleUp) {
+            return false;
+        }
+
+        var gracePeriod = conf.get(SCALE_UP_GRACE_PERIOD);
+        if (lastScalingTs.plus(gracePeriod).isAfter(clock.instant())) {
+            LOG.info(
+                    "Skipping immediate scale down after scale up within grace 
period for {}",
+                    vertex);
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    private boolean detectIneffectiveScaleup(
+            JobVertexID vertex,
+            Configuration conf,
+            Map<ScalingMetric, EvaluatedScalingMetric> evaluatedMetrics,
+            SortedMap<Instant, ScalingSummary> history,
+            boolean scaleUp) {
+
+        // Does not apply to scale down operations
+        if (!scaleUp) {
+            return false;
+        }
+
+        var lastScalingTs = history.lastKey();
+        var lastSummary = history.get(lastScalingTs);
+
+        boolean lastScaleUp = lastSummary.getNewParallelism() > 
lastSummary.getCurrentParallelism();
+        if (!lastScaleUp) {
+            return false;
+        }
+
+        double lastProcRate = 
lastSummary.getMetrics().get(TRUE_PROCESSING_RATE).getAverage();
+        double lastExpectedProcRate =
+                
lastSummary.getMetrics().get(EXPECTED_PROCESSING_RATE).getCurrent();
+        var currentProcRate = 
evaluatedMetrics.get(TRUE_PROCESSING_RATE).getAverage();
+
+        double expectedIncrease = lastExpectedProcRate / lastProcRate - 1;
+        double actualIncrease = currentProcRate / lastProcRate - 1;
+
+        boolean withinEffectiveThreshold =
+                (expectedIncrease - actualIncrease) / expectedIncrease
+                        < (1 - 
conf.get(AutoScalerOptions.SCALING_EFFECTIVENESS_THRESHOLD));

Review Comment:
   The intention here is not to compare against the percentage change (what 
your code does) because this will make this unusuable for large jobs when the 
expected change may actually be small. Going from parallelism 1000 -> 1010 may 
be a 1% expected change and that is completely efficient. 
   
   What we actually want is if we expected a 1.01 (1%) increase and we only got 
(1.0001) we need to mark this uneffective. So we actually compare the change 
itself so we have to subtract 1.
   
   This is not immediately obvious and I spent some time thinking about it. I 
think this is the only correct way that is parallelism agnostic.



-- 
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: issues-unsubscr...@flink.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to