You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by mx...@apache.org on 2023/01/03 17:37:37 UTC

[flink-kubernetes-operator] branch main updated: [FLINK-30464] Exclude metrics during stabilization and ensure a full metric window (#493)

This is an automated email from the ASF dual-hosted git repository.

mxm pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/flink-kubernetes-operator.git


The following commit(s) were added to refs/heads/main by this push:
     new c71b471f [FLINK-30464] Exclude metrics during stabilization and ensure a full metric window (#493)
c71b471f is described below

commit c71b471fc8b0840cd8cf96cc48c41e70d795dab0
Author: Maximilian Michels <mx...@apache.org>
AuthorDate: Tue Jan 3 18:37:31 2023 +0100

    [FLINK-30464] Exclude metrics during stabilization and ensure a full metric window (#493)
    
    So far, the code collects metrics as soon as the job goes into RUNNING mode,
    regardless of whether we are still in the stabilization period. This means the
    first metric collection window after rescaling will include metrics from the
    stabilization period. This is not desirable. The stabilization period is
    supposed to allow the job to stabilize. Metrics during stabilization shouldn't
    be used to make new scaling decisions.
    
    Further, the collected metrics for the scaling decider initially do not span a full
    metric window. Only after the first metric window is complete, we are guaranteed
    to have a full windows available. This leads to short-sighted scaling decisions
    which is fixed in this change.
---
 .../operator/autoscaler/AutoScalerInfo.java        |  12 +--
 .../operator/autoscaler/JobAutoScaler.java         |   3 +-
 .../operator/autoscaler/ScalingExecutor.java       |   3 +-
 .../autoscaler/ScalingMetricCollector.java         |  44 +++++---
 .../autoscaler/ScalingMetricEvaluator.java         |  15 ++-
 .../autoscaler/BacklogBasedScalingTest.java        |  18 +++-
 .../MetricsCollectionAndEvaluationTest.java        | 119 ++++++++++++++++++---
 7 files changed, 161 insertions(+), 53 deletions(-)

diff --git a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/AutoScalerInfo.java b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/AutoScalerInfo.java
index 1236cc65..6f35281f 100644
--- a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/AutoScalerInfo.java
+++ b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/AutoScalerInfo.java
@@ -56,7 +56,7 @@ public class AutoScalerInfo {
 
     private static final String COLLECTED_METRICS_KEY = "collectedMetrics";
     private static final String SCALING_HISTORY_KEY = "scalingHistory";
-    private static final String JOB_START_TS_KEY = "jobStartTs";
+    private static final String JOB_UPDATE_TS_KEY = "jobUpdateTs";
 
     private static final ObjectMapper YAML_MAPPER =
             new ObjectMapper(new YAMLFactory())
@@ -88,19 +88,19 @@ public class AutoScalerInfo {
 
     @SneakyThrows
     public void updateMetricHistory(
-            Instant jobStartTs,
+            Instant jobUpdateTs,
             SortedMap<Instant, Map<JobVertexID, Map<ScalingMetric, Double>>> history) {
         configMap.getData().put(COLLECTED_METRICS_KEY, YAML_MAPPER.writeValueAsString(history));
-        configMap.getData().put(JOB_START_TS_KEY, jobStartTs.toString());
+        configMap.getData().put(JOB_UPDATE_TS_KEY, jobUpdateTs.toString());
     }
 
     public void clearMetricHistory() {
         configMap.getData().remove(COLLECTED_METRICS_KEY);
-        configMap.getData().remove(JOB_START_TS_KEY);
+        configMap.getData().remove(JOB_UPDATE_TS_KEY);
     }
 
-    public Optional<Instant> getJobStartTs() {
-        return Optional.ofNullable(configMap.getData().get(JOB_START_TS_KEY)).map(Instant::parse);
+    public Optional<Instant> getJobUpdateTs() {
+        return Optional.ofNullable(configMap.getData().get(JOB_UPDATE_TS_KEY)).map(Instant::parse);
     }
 
     @SneakyThrows
diff --git a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/JobAutoScaler.java b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/JobAutoScaler.java
index d9fb0041..9ada816c 100644
--- a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/JobAutoScaler.java
+++ b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/JobAutoScaler.java
@@ -104,8 +104,7 @@ public class JobAutoScaler implements Cleanup {
 
             LOG.info("Collecting metrics for scaling");
             var collectedMetrics =
-                    metricsCollector.getMetricsHistory(
-                            resource, autoScalerInfo, flinkService, conf);
+                    metricsCollector.updateMetrics(resource, autoScalerInfo, flinkService, conf);
 
             if (collectedMetrics == null || collectedMetrics.getMetricHistory().isEmpty()) {
                 LOG.info("No metrics were collected. Skipping scaling step");
diff --git a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingExecutor.java b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingExecutor.java
index 6a2353ab..df2d96a9 100644
--- a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingExecutor.java
+++ b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingExecutor.java
@@ -81,8 +81,7 @@ public class ScalingExecutor implements Cleanup {
             AbstractFlinkResource<?, ?> resource,
             AutoScalerInfo scalingInformation,
             Configuration conf,
-            Map<JobVertexID, Map<ScalingMetric, EvaluatedScalingMetric>> evaluatedMetrics)
-            throws Exception {
+            Map<JobVertexID, Map<ScalingMetric, EvaluatedScalingMetric>> evaluatedMetrics) {
 
         if (!conf.get(SCALING_ENABLED)) {
             return false;
diff --git a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingMetricCollector.java b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingMetricCollector.java
index 993e6760..c7674a5b 100644
--- a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingMetricCollector.java
+++ b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingMetricCollector.java
@@ -51,6 +51,7 @@ import java.time.Duration;
 import java.time.Instant;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
@@ -77,7 +78,7 @@ public abstract class ScalingMetricCollector implements Cleanup {
 
     private Clock clock = Clock.systemDefaultZone();
 
-    public CollectedMetrics getMetricsHistory(
+    public CollectedMetrics updateMetrics(
             AbstractFlinkResource<?, ?> cr,
             AutoScalerInfo scalingInformation,
             FlinkService flinkService,
@@ -85,16 +86,33 @@ public abstract class ScalingMetricCollector implements Cleanup {
             throws Exception {
 
         var resourceID = ResourceID.fromResource(cr);
-        var currentJobStartTs =
-                Instant.ofEpochMilli(Long.parseLong(cr.getStatus().getJobStatus().getStartTime()));
+        var jobStatus = cr.getStatus().getJobStatus();
+        var currentJobUpdateTs = Instant.ofEpochMilli(Long.parseLong(jobStatus.getUpdateTime()));
+        var now = clock.instant();
 
-        if (!currentJobStartTs.equals(
-                scalingInformation.getJobStartTs().orElse(currentJobStartTs))) {
+        if (!currentJobUpdateTs.equals(
+                scalingInformation.getJobUpdateTs().orElse(currentJobUpdateTs))) {
             scalingInformation.clearMetricHistory();
             cleanup(cr);
         }
 
-        // Initialize metric history
+        var topology = getJobTopology(flinkService, cr, conf);
+
+        var stabilizationDuration = conf.get(AutoScalerOptions.STABILIZATION_INTERVAL);
+        var stableTime = currentJobUpdateTs.plus(stabilizationDuration);
+        if (now.isBefore(stableTime)) {
+            // As long as we are stabilizing, collect no metrics at all
+            return new CollectedMetrics(topology, Collections.emptySortedMap());
+        }
+
+        // Adjust the window size until it reaches the max size
+        var metricsWindowSize =
+                Duration.ofMillis(
+                        Math.min(
+                                now.toEpochMilli() - stableTime.toEpochMilli(),
+                                conf.get(AutoScalerOptions.METRICS_WINDOW).toMillis()));
+
+        // Extract metrics history for metric window size
         var scalingMetricHistory =
                 histories.compute(
                         resourceID,
@@ -102,13 +120,9 @@ public abstract class ScalingMetricCollector implements Cleanup {
                             if (h == null) {
                                 h = scalingInformation.getMetricHistory();
                             }
-                            return h.tailMap(
-                                    clock.instant()
-                                            .minus(conf.get(AutoScalerOptions.METRICS_WINDOW)));
+                            return h.tailMap(now.minus(metricsWindowSize));
                         });
 
-        var topology = getJobTopology(flinkService, cr, conf);
-
         // The filtered list of metrics we want to query for each vertex
         var filteredVertexMetricNames = queryFilteredMetricNames(flinkService, cr, conf, topology);
 
@@ -122,7 +136,13 @@ public abstract class ScalingMetricCollector implements Cleanup {
 
         // Add scaling metrics to history if they were computed successfully
         scalingMetricHistory.put(clock.instant(), scalingMetrics);
-        scalingInformation.updateMetricHistory(currentJobStartTs, scalingMetricHistory);
+        scalingInformation.updateMetricHistory(currentJobUpdateTs, scalingMetricHistory);
+
+        if (now.isBefore(stableTime.plus(conf.get(AutoScalerOptions.METRICS_WINDOW)))) {
+            // As long as we haven't had time to collect a full window,
+            // collect metrics but do not return any metrics
+            return new CollectedMetrics(topology, Collections.emptySortedMap());
+        }
 
         return new CollectedMetrics(topology, scalingMetricHistory);
     }
diff --git a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingMetricEvaluator.java b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingMetricEvaluator.java
index fdf5e33f..709b975c 100644
--- a/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingMetricEvaluator.java
+++ b/flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/autoscaler/ScalingMetricEvaluator.java
@@ -101,7 +101,7 @@ public class ScalingMetricEvaluator {
                 TRUE_PROCESSING_RATE,
                 new EvaluatedScalingMetric(
                         latestVertexMetrics.get(TRUE_PROCESSING_RATE),
-                        getAverage(TRUE_PROCESSING_RATE, vertex, metricsHistory, conf)));
+                        getAverage(TRUE_PROCESSING_RATE, vertex, metricsHistory)));
 
         evaluatedMetrics.put(
                 PARALLELISM, EvaluatedScalingMetric.of(topology.getParallelisms().get(vertex)));
@@ -117,12 +117,12 @@ public class ScalingMetricEvaluator {
                     TRUE_OUTPUT_RATE,
                     new EvaluatedScalingMetric(
                             latestVertexMetrics.get(TRUE_OUTPUT_RATE),
-                            getAverage(TRUE_OUTPUT_RATE, vertex, metricsHistory, conf)));
+                            getAverage(TRUE_OUTPUT_RATE, vertex, metricsHistory)));
             evaluatedMetrics.put(
                     OUTPUT_RATIO,
                     new EvaluatedScalingMetric(
                             latestVertexMetrics.get(OUTPUT_RATIO),
-                            getAverage(OUTPUT_RATIO, vertex, metricsHistory, conf)));
+                            getAverage(OUTPUT_RATIO, vertex, metricsHistory)));
         }
 
         return evaluatedMetrics;
@@ -172,7 +172,7 @@ public class ScalingMetricEvaluator {
                     TARGET_DATA_RATE,
                     new EvaluatedScalingMetric(
                             latestVertexMetrics.get(sourceRateMetric),
-                            getAverage(sourceRateMetric, vertex, metricsHistory, conf)));
+                            getAverage(sourceRateMetric, vertex, metricsHistory)));
 
             double lag = latestVertexMetrics.getOrDefault(LAG, 0.);
             double catchUpInputRate = catchUpTargetSec == 0 ? 0 : lag / catchUpTargetSec;
@@ -208,12 +208,9 @@ public class ScalingMetricEvaluator {
     private double getAverage(
             ScalingMetric metric,
             JobVertexID jobVertexId,
-            SortedMap<Instant, Map<JobVertexID, Map<ScalingMetric, Double>>> metricsHistory,
-            Configuration conf) {
+            SortedMap<Instant, Map<JobVertexID, Map<ScalingMetric, Double>>> metricsHistory) {
         return StatUtils.mean(
-                metricsHistory
-                        .tailMap(clock.instant().minus(conf.get(AutoScalerOptions.METRICS_WINDOW)))
-                        .values().stream()
+                metricsHistory.values().stream()
                         .map(m -> m.get(jobVertexId))
                         .filter(m -> m.containsKey(metric))
                         .mapToDouble(m -> m.get(metric))
diff --git a/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/autoscaler/BacklogBasedScalingTest.java b/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/autoscaler/BacklogBasedScalingTest.java
index 0d043a80..578b01a0 100644
--- a/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/autoscaler/BacklogBasedScalingTest.java
+++ b/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/autoscaler/BacklogBasedScalingTest.java
@@ -116,11 +116,9 @@ public class BacklogBasedScalingTest {
     @Test
     public void test() throws Exception {
         var ctx = createAutoscalerTestContext();
-        var now = Instant.now();
+        var now = Instant.ofEpochMilli(0);
         setClocksTo(now);
-        String startTime = String.valueOf(now.toEpochMilli());
-        app.getStatus().getJobStatus().setStartTime(startTime);
-        app.getStatus().getJobStatus().setUpdateTime(startTime);
+        redeployJob(now);
         metricsCollector.setCurrentMetrics(
                 Map.of(
                         source1,
@@ -180,7 +178,7 @@ public class BacklogBasedScalingTest {
 
         now = now.plus(Duration.ofSeconds(1));
         setClocksTo(now);
-        app.getStatus().getJobStatus().setStartTime(String.valueOf(now.toEpochMilli()));
+        redeployJob(now);
         autoscaler.scale(
                 app, service, confManager.getObserveConfig(app), createAutoscalerTestContext());
         assertFalse(AutoScalerInfo.forResource(app, kubernetesClient).getMetricHistory().isEmpty());
@@ -334,6 +332,16 @@ public class BacklogBasedScalingTest {
         assertEquals(2, scaledParallelism.get(sink));
     }
 
+    private void redeployJob(Instant now) {
+        // Offset the update time by one metrics window to simulate collecting one entire window
+        app.getStatus()
+                .getJobStatus()
+                .setUpdateTime(
+                        String.valueOf(
+                                now.minus(AutoScalerOptions.METRICS_WINDOW.defaultValue())
+                                        .toEpochMilli()));
+    }
+
     private void setClocksTo(Instant time) {
         var clock = Clock.fixed(time, ZoneId.systemDefault());
         metricsCollector.setClock(clock);
diff --git a/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/autoscaler/MetricsCollectionAndEvaluationTest.java b/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/autoscaler/MetricsCollectionAndEvaluationTest.java
index 29b92abb..61ed26ce 100644
--- a/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/autoscaler/MetricsCollectionAndEvaluationTest.java
+++ b/flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/autoscaler/MetricsCollectionAndEvaluationTest.java
@@ -54,11 +54,14 @@ import java.util.Set;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 
 /** Test for scaling metrics collection logic. */
 @EnableKubernetesMockClient(crud = true)
 public class MetricsCollectionAndEvaluationTest {
 
+    private final AutoScalerInfo scalingInfo = new AutoScalerInfo(new HashMap<>());
+
     private ScalingMetricEvaluator evaluator;
     private TestingFlinkService service;
     private TestingMetricsCollector metricsCollector;
@@ -71,6 +74,10 @@ public class MetricsCollectionAndEvaluationTest {
 
     private KubernetesClient kubernetesClient;
 
+    private Clock clock;
+
+    private Instant startTime;
+
     @BeforeEach
     public void setup() {
         evaluator = new ScalingMetricEvaluator();
@@ -98,13 +105,17 @@ public class MetricsCollectionAndEvaluationTest {
 
         var confManager = new FlinkConfigManager(new Configuration());
         conf = confManager.getDeployConfig(app.getMetadata(), app.getSpec());
-        conf.set(AutoScalerOptions.STABILIZATION_INTERVAL, Duration.ZERO);
+        conf.set(AutoScalerOptions.STABILIZATION_INTERVAL, Duration.ofSeconds(10));
+        conf.set(AutoScalerOptions.METRICS_WINDOW, Duration.ofSeconds(100));
         conf.set(AutoScalerOptions.RESTART_TIME, Duration.ZERO);
         conf.set(AutoScalerOptions.SCALING_ENABLED, true);
         conf.set(AutoScalerOptions.MAX_SCALE_DOWN_FACTOR, 1.);
         ReconciliationUtils.updateStatusForDeployedSpec(app, conf);
-        app.getStatus().getJobStatus().setStartTime(String.valueOf(System.currentTimeMillis()));
-        app.getStatus().getJobStatus().setUpdateTime(String.valueOf(System.currentTimeMillis()));
+        clock = Clock.fixed(Instant.ofEpochSecond(0), ZoneId.systemDefault());
+        metricsCollector.setClock(clock);
+        startTime = clock.instant();
+        app.getStatus().getJobStatus().setStartTime(String.valueOf(startTime.toEpochMilli()));
+        app.getStatus().getJobStatus().setUpdateTime(String.valueOf(startTime.toEpochMilli()));
         app.getStatus().getJobStatus().setState(JobStatus.RUNNING.name());
     }
 
@@ -113,25 +124,52 @@ public class MetricsCollectionAndEvaluationTest {
         conf.set(AutoScalerOptions.TARGET_UTILIZATION, 1.);
         conf.set(AutoScalerOptions.TARGET_UTILIZATION_BOUNDARY, 0.);
 
-        var scalingInfo = new AutoScalerInfo(new HashMap<>());
+        setDefaultMetrics(metricsCollector);
 
-        setDefaultMetrics();
-        metricsCollector.getMetricsHistory(app, scalingInfo, service, conf);
+        // We haven't left the stabilization period
+        // => no metrics reporting and collection should take place
+        var collectedMetrics = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertTrue(collectedMetrics.getMetricHistory().isEmpty());
 
-        // Test resetting the collector and make sure we can deserialize the scalingInfo correctly
-        metricsCollector = new TestingMetricsCollector(topology);
-        setDefaultMetrics();
+        // We haven't collected a full window yet, no metrics should be reported but metrics should
+        // still get collected.
+        clock = Clock.offset(clock, conf.get(AutoScalerOptions.STABILIZATION_INTERVAL));
+        metricsCollector.setClock(clock);
+        collectedMetrics = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertTrue(collectedMetrics.getMetricHistory().isEmpty());
 
-        var clock = Clock.fixed(Instant.now().plus(Duration.ofSeconds(3)), ZoneId.systemDefault());
+        // We haven't collected a full window yet
+        // => no metrics should be reported but metrics should still get collected.
+        clock = Clock.offset(clock, Duration.ofSeconds(1));
         metricsCollector.setClock(clock);
-        evaluator.setClock(clock);
+        collectedMetrics = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertTrue(collectedMetrics.getMetricHistory().isEmpty());
+
+        // Advance time to stabilization period + full window => metrics should be present
+        clock =
+                Clock.fixed(
+                        startTime
+                                .plus(conf.get(AutoScalerOptions.STABILIZATION_INTERVAL))
+                                .plus(conf.get(AutoScalerOptions.METRICS_WINDOW)),
+                        ZoneId.systemDefault());
+        metricsCollector.setClock(clock);
+        collectedMetrics = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertEquals(3, collectedMetrics.getMetricHistory().size());
 
-        var collectedMetrics = metricsCollector.getMetricsHistory(app, scalingInfo, service, conf);
+        // Test resetting the collector and make sure we can deserialize the scalingInfo correctly
+        metricsCollector = new TestingMetricsCollector(topology);
+        metricsCollector.setClock(clock);
+        setDefaultMetrics(metricsCollector);
+        collectedMetrics = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertEquals(3, collectedMetrics.getMetricHistory().size());
 
+        evaluator.setClock(clock);
         var evaluation = evaluator.evaluate(conf, collectedMetrics);
         scalingExecutor.scaleResource(app, scalingInfo, conf, evaluation);
 
         var scaledParallelism = ScalingExecutorTest.getScaledParallelism(app);
+        assertEquals(4, scaledParallelism.size());
+
         assertEquals(2, scaledParallelism.get(source1));
         assertEquals(2, scaledParallelism.get(source2));
         assertEquals(6, scaledParallelism.get(map));
@@ -161,7 +199,7 @@ public class MetricsCollectionAndEvaluationTest {
         assertNull(metricsCollector.getTopologies().get(resourceID));
     }
 
-    private void setDefaultMetrics() {
+    private void setDefaultMetrics(TestingMetricsCollector metricsCollector) {
         metricsCollector.setCurrentMetrics(
                 Map.of(
                         source1,
@@ -206,14 +244,14 @@ public class MetricsCollectionAndEvaluationTest {
     public void testKafkaPartitionMaxParallelism() throws Exception {
         var scalingInfo = new AutoScalerInfo(new HashMap<>());
 
-        setDefaultMetrics();
-        metricsCollector.getMetricsHistory(app, scalingInfo, service, conf);
+        setDefaultMetrics(metricsCollector);
+        metricsCollector.updateMetrics(app, scalingInfo, service, conf);
 
         var clock = Clock.fixed(Instant.now().plus(Duration.ofSeconds(3)), ZoneId.systemDefault());
         metricsCollector.setClock(clock);
         evaluator.setClock(clock);
 
-        var collectedMetrics = metricsCollector.getMetricsHistory(app, scalingInfo, service, conf);
+        var collectedMetrics = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
 
         assertEquals(720, collectedMetrics.getJobTopology().getMaxParallelisms().get(source1));
         assertEquals(720, collectedMetrics.getJobTopology().getMaxParallelisms().get(source2));
@@ -235,7 +273,7 @@ public class MetricsCollectionAndEvaluationTest {
                                 new AggregatedMetric(
                                         "1.Source__Kafka_Source_(testTopic).KafkaSourceReader.topic.testTopic.partition.3.currentOffset"))));
 
-        collectedMetrics = metricsCollector.getMetricsHistory(app, scalingInfo, service, conf);
+        collectedMetrics = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
         assertEquals(4, collectedMetrics.getJobTopology().getMaxParallelisms().get(source1));
         assertEquals(720, collectedMetrics.getJobTopology().getMaxParallelisms().get(source2));
     }
@@ -251,4 +289,51 @@ public class MetricsCollectionAndEvaluationTest {
         flinkObjectMapper.readValue(flink15Response, JobDetailsInfo.class);
         flinkObjectMapper.readValue(flink16Response, JobDetailsInfo.class);
     }
+
+    @Test
+    public void testMetricCollectorWindow() throws Exception {
+        setDefaultMetrics(metricsCollector);
+        var metricsHistory = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertEquals(0, metricsHistory.getMetricHistory().size());
+
+        // Not stable, nothing should be collected
+        metricsCollector.setClock(Clock.offset(clock, Duration.ofSeconds(1)));
+        metricsHistory = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertEquals(0, metricsHistory.getMetricHistory().size());
+
+        // Update clock to stable time
+        clock = Clock.offset(clock, conf.get(AutoScalerOptions.STABILIZATION_INTERVAL));
+        metricsCollector.setClock(clock);
+
+        // This call will lead to metric collection but we haven't reached the window size yet
+        // which will hold back metrics
+        metricsHistory = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertEquals(0, metricsHistory.getMetricHistory().size());
+
+        // Collect more values in window
+        metricsCollector.setClock(Clock.offset(clock, Duration.ofSeconds(1)));
+        metricsHistory = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertEquals(0, metricsHistory.getMetricHistory().size());
+
+        // Window size reached
+        metricsCollector.setClock(Clock.offset(clock, conf.get(AutoScalerOptions.METRICS_WINDOW)));
+        metricsHistory = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertEquals(3, metricsHistory.getMetricHistory().size());
+
+        // Window size + 1 will invalidate the first metric
+        metricsCollector.setClock(
+                Clock.offset(clock, conf.get(AutoScalerOptions.METRICS_WINDOW).plusSeconds(1)));
+        metricsHistory = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertEquals(3, metricsHistory.getMetricHistory().size());
+
+        // Completely new metric window with just the currently connected metric
+        metricsCollector.setClock(
+                Clock.offset(clock, conf.get(AutoScalerOptions.METRICS_WINDOW).plusDays(1)));
+        metricsHistory = metricsCollector.updateMetrics(app, scalingInfo, service, conf);
+        assertEquals(1, metricsHistory.getMetricHistory().size());
+
+        // Everything should reset on job updates
+        app.getStatus().getJobStatus().setUpdateTime("0");
+        assertEquals(1, metricsHistory.getMetricHistory().size());
+    }
 }