← Back to Pull requests

[ISSUE #7965] Register the scaling observer so metric-driven policies actuate #7966

Merged
imDwAaY merged 4 files (240 lines) on Oct 24, 2026 11:47 UTC
View on GitHub
imDwAaY imDwAaY commented on Oct 21, 2026 16:37 UTC
Author

Problem

Policy 3 (metric-driven scaling) never actuates. MetricsMonitor.monitorMetrics() evaluates enabled ScaleRuleDO rows and calls notifyObservers(...), but nothing ever calls MetricsMonitor.addObserver(...) and ScaleObserver is never instantiated in production code. The observer list is therefore always empty: Prometheus is read and rules are evaluated, but KubernetesScaler.scaleByAction is never reached.

Fixes #7965.

Change

  • ScaleObserver is now a Spring @Component.

  • MetricsMonitor constructor-injects List<Observer> and copies it into its mutable observer list, so Spring registers every Observer bean at startup. The existing addObserver / removeObserver contract is unchanged.
  • Tests

    New MetricsMonitorTest covers:

  • metric above maximum produces exactly one SCALE_UP action

  • metric below minimum produces exactly one SCALE_DOWN action

  • metric within bounds produces no action

  • a disabled rule fetches no metric and produces no action

  • an observer supplied through the constructor receives the update
  • All 27 targeted tests pass and checkstyle reports 0 violations (Java 17).

    Relationship to #7913 / #7964

    This change only connects the actuator. Single-owner behavior in clustered Admin mode is handled by #7964 (#7913). Until that PR merges, metric-driven actuation would occur on every Admin replica, which is the pre-existing behavior of the scaling loop rather than something introduced here. Merging #7964 first (or together) gives the intended one-owner behavior.

    Diff: 240 lines (+238 / -2) across 4 files Reviewer: Aias00 Review duration: 4030m
    All Vouch review confidence checks passed
    Residual risk 0.10 = Change Risk (0.40) × (1 − Review Confidence (0.76)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.40 · 240 lines diff across 4 files
    0.40
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.53 · 4 substantive comment(s)
    0.53
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    76%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.328
    Real PR Conversation Timeline
    10 items
    wy471x wy471x commented on code on Oct 22, 2026 01:09 UTC
    Code Review
    shenyu-admin/src/main/java/org/apache/shenyu/admin/scale/monitor/observer/ScaleObserver.java:1
    @@ -24,9 +24,11 @@
     import org.apache.shenyu.admin.scale.scaler.dynamic.ScaleAction;
     import org.slf4j.Logger;
     import org.slf4j.LoggerFactory;
    +import org.springframework.stereotype.Component;
     
     import java.util.Objects;
     
    +@Component

    Blocking: Registering this bean activates metric-driven scaling on every Admin replica. ScaleService.startDynamicTask() still schedules monitorMetrics() per replica, so one evaluation will call scaleByAction once per Admin until #7964 is merged. Please make #7964 a hard merge dependency or gate this registration/scheduling on the scaling owner.

    wy471x wy471x commented on code on Oct 22, 2026 01:09 UTC
    Code Review
    shenyu-admin/src/test/java/org/apache/shenyu/admin/scale/monitor/subject/MetricsMonitorTest.java:1
    @@ -0,0 +1,132 @@
    +/*
    + * 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.shenyu.admin.scale.monitor.subject;
    +
    +import org.apache.shenyu.admin.model.entity.ScaleRuleDO;
    +import org.apache.shenyu.admin.scale.collector.PrometheusMetricsProvider;
    +import org.apache.shenyu.admin.scale.collector.provider.MetricData;
    +import org.apache.shenyu.admin.scale.monitor.observer.Observer;
    +import org.apache.shenyu.admin.scale.monitor.observer.ScaleObserver;
    +import org.apache.shenyu.admin.scale.monitor.subject.cache.ScaleRuleCache;
    +import org.apache.shenyu.admin.scale.scaler.KubernetesScaler;
    +import org.apache.shenyu.admin.scale.scaler.dynamic.ScaleAction;
    +import org.apache.shenyu.admin.scale.scaler.dynamic.ScaleRuleEvaluator;
    +import org.junit.jupiter.api.BeforeEach;
    +import org.junit.jupiter.api.Test;
    +
    +import java.util.List;
    +
    +import static org.mockito.Mockito.mock;
    +import static org.mockito.Mockito.verify;
    +import static org.mockito.Mockito.verifyNoInteractions;
    +import static org.mockito.Mockito.verifyNoMoreInteractions;
    +import static org.mockito.Mockito.when;
    +
    +/**
    + * Tests for metric monitoring and scaling observer registration.
    + */
    +public final class MetricsMonitorTest {
    +
    +    private static final String METRIC_NAME = "cpu_usage";
    +
    +    private PrometheusMetricsProvider metricsProvider;
    +
    +    private ScaleRuleCache scaleRuleCache;
    +
    +    private KubernetesScaler kubernetesScaler;
    +
    +    private MetricsMonitor metricsMonitor;
    +
    +    @BeforeEach
    +    public void setUp() {
    +        metricsProvider = mock(PrometheusMetricsProvider.class);
    +        scaleRuleCache = mock(ScaleRuleCache.class);
    +        kubernetesScaler = mock(KubernetesScaler.class);
    +        final ScaleObserver scaleObserver = new ScaleObserver(kubernetesScaler, new ScaleRuleEvaluator());

    Blocking: The test constructs and injects the observer itself, bypassing the production wiring that failed. Removing @Component from ScaleObserver would leave this suite green. Please add a context-level test that resolves MetricsMonitor and asserts the discovered ScaleObserver is invoked exactly once.

    wy471x wy471x requested changes on Oct 22, 2026 01:09 UTC
    Changes Requested Reviewer

    Thanks for connecting the observer. The production change is small and the single-instance path is correct, but I found two blocking issues.

    Standards

  • The regression test bypasses the failure it is meant to catch. MetricsMonitorTest#setUp manually constructs ScaleObserver and passes it into MetricsMonitor. If the new @Component is removed, these tests still pass, so the original wiring regression is not covered. Please add a small Spring-context test (ApplicationContextRunner or AnnotationConfigApplicationContext) that obtains MetricsMonitor and verifies the discovered ScaleObserver invokes scaleByAction exactly once.

  • Non-blocking: the evaluator uses strict > / <; adding assertions for exactly 40.0 and 80.0 would pin the intended non-scaling boundary behavior.
  • Spec

  • This is unsafe to merge before #7964. ScaleService.startDynamicTask() still schedules monitorMetrics() on every Admin replica. With this observer now registered, one evaluation can invoke scaleByAction once per replica, violating the issue's "exactly one" expectation and introducing concurrent read-modify-write scaling. The description already identifies this dependency; please make #7964 (or an equivalent owner guard) a hard merge requirement rather than a note.
  • Verification: ./mvnw -pl shenyu-admin -am -Dtest=MetricsMonitorTest -DfailIfNoTests=false -Djacoco.skip=true test passed with 5 tests. Required GitHub checks pass.

    Aias00 Aias00 commented on Oct 22, 2026 01:54 UTC
    Reviewer

    Review: #7966 [ISSUE #7965] Register the scaling observer so metric-driven policies actuate

    Verdict: approved — this fix bridges the disconnected observer chain in ShenYu Admin's metric-driven dynamic scaling subsystem.

    What I verified

    1. Root cause resolved: Prior to this change, MetricsMonitor held an empty internal observers list that was never populated because no callers invoked addObserver(...), and ScaleObserver was an unmanaged class lacking @Component. As a result, metric evaluations by MetricsMonitor.monitorMetrics() never dispatched to any observer, rendering dynamic autoscaling inoperative.
    2. Spring wiring:
    - Marking ScaleObserver with @Component allows Spring to manage it alongside its required dependencies (KubernetesScaler and ScaleRuleEvaluator, both of which are already registered components).
    - In MetricsMonitor, accepting List<Observer> observers in the constructor leverages Spring's built-in collection injection (which gracefully resolves to an empty list if no Observer beans exist, and collects all available implementations when present). Defensive copying via new ArrayList<>(observers) prevents external mutation of the injected list.
    3. Test coverage:
    - MetricsMonitorTest cleanly exercises the five critical scenarios:
    - Metric exceeding maximum (81.0 > 80.0) actuates SCALE_UP.
    - Metric falling below minimum (39.0 < 40.0) actuates SCALE_DOWN.
    - Metric within bounds (60.0) triggers no scaler interaction.
    - Disabled rules (status == 0) are filtered out prior to querying metrics.
    - Constructor-injected observers receive the dispatched metric and rule payload.
    4. CI:
    - pr_build, rat_check, check-license-header, CodeQL, and unit test suites passed. The sole red run on shenyu-integrated-test-http is the known master regression (CryptorResponsePluginTest.testWhenDoesntExistFiled), unrelated to this PR.

    Follow-up suggestions (non-blocking)

  • Concurrency: MetricsMonitor retains mutable addObserver and removeObserver methods while wrapping the list in a standard ArrayList. If external callers ever add or remove observers dynamically while monitorMetrics() executes concurrently, a ConcurrentModificationException could occur. Using new CopyOnWriteArrayList<>(observers) would guarantee thread-safe iteration without locking.
  • imDwAaY imDwAaY commented on Oct 22, 2026 04:56 UTC
    Author

    Thanks for the review.

    1. Added ScaleObserverContextTest. It boots an AnnotationConfigApplicationContext, scans only org.apache.shenyu.admin.scale.monitor.observer, registers MetricsMonitor, and asserts that exactly one Observer bean — the discovered ScaleObserver — receives the metric update and calls scaleByAction exactly once. I verified the test fails when @Component is removed from ScaleObserver, so the production wiring regression is now covered.

    2. Agreed on the merge order. #7964 is approved and should merge first; I will rebase this branch onto master immediately afterwards, which brings in the owner guard (ScaleService.active) and makes this PR safe on its own.

    3. Also added the strict boundary assertions from the non-blocking comment: metrics of exactly 40.0 and 80.0 produce no action.

    Current state: 30 targeted tests pass, checkstyle reports 0 violations.

    Aias00 Aias00 approved these changes on Oct 22, 2026 05:47 UTC
    Approved Reviewer

    Re-approving after the follow-up commit.

    ScaleObserverContextTest closes the gap I could not close from the unit test alone: MetricsMonitorTest constructed the monitor with List.of(scaleObserver) by hand, so it proved the wiring works but not that Spring performs it — the whole defect in #7965 was that ScaleObserver had no @Component. This test boots an AnnotationConfigApplicationContext, registers the three collaborators, scans org.apache.shenyu.admin.scale.monitor.observer, and asserts:

  • exactly one Observer bean exists and it is a ScaleObserver — so a missing or duplicated @Component fails here;

  • context.getBean(MetricsMonitor.class).monitorMetrics() then drives scaleByAction(SCALE_UP) for a rule at 81% against a maximum of 80 — so the injected List<Observer> is genuinely the discovered bean, not an empty list silently accepted by the constructor.
  • Registering ScaleRuleEvaluator explicitly while scanning for the observer is the right split: it keeps the scan narrow enough that the test is about discovery of the observer specifically.

    Still open from my first review (non-blocking): MetricsMonitor copies the injected observers into an ArrayList while keeping the public addObserver/removeObserver methods, so a dynamic add during monitorMetrics() iteration could still throw ConcurrentModificationException; CopyOnWriteArrayList would remove that class. Nothing in the current wiring mutates the list, so this is a robustness note rather than a defect.

    wy471x wy471x requested changes on Oct 22, 2026 13:09 UTC
    Changes Requested Reviewer

    Re-review of aec13be.

    Standards

  • The prior regression-test gap is resolved. ScaleObserverContextTest boots an AnnotationConfigApplicationContext, discovers the observer through component scanning, resolves MetricsMonitor, and verifies one SCALE_UP call. Removing @Component makes the test fail.

  • The exact 40.0 and 80.0 boundary cases are now covered. No new documented-standard violations or blocking smells were found.
  • Spec

  • The functional spec is satisfied for a single Admin instance.

  • The merge-order blocker remains. This head is still based on be34dd1 and does not contain the #7964 owner/lease guard. ScaleService.startDynamicTask() schedules monitorMetrics() on every replica, so merging this head first would call scaleByAction once per Admin. Please rebase after #7964 merges; then this can be approved.
  • Verification: ./mvnw -pl shenyu-admin -am -Dtest=MetricsMonitorTest,ScaleObserverContextTest -DfailIfNoTests=false -Djacoco.skip=true test passes with 8 tests. Checkstyle reports 0 violations.

    imDwAaY imDwAaY commented on Oct 23, 2026 04:23 UTC
    Author

    @wy471x #7964 has merged (cfb0a1a). I've rebased this branch onto master (34f2ed036) and force-pushed — the head is now ab583fa48.

    The head now carries the #7964 owner guard:

  • ScaleService has the active gate; start() / stop() are driven by ShenyuClusterService on winning the master lease and by ShenyuStandaloneService in standalone mode.

  • startDynamicTask() is only reached from executeScaling(), which returns early while active is false.
  • So registering ScaleObserver no longer actuates on non-owner replicas: on followers monitorMetrics() is never scheduled.

    The rebased diff is unchanged from the previous head — still 4 files, +238/−2. ./mvnw -pl shenyu-admin -am -DskipTests compile passes against the new base, and CI is re-running the full matrix. The it / build (shenyu-integrated-test-http) failure is the known master regression tracked in #7968.

    Could you re-review when you get a chance? That should clear the merge-order blocker.

    wy471x wy471x approved these changes on Oct 24, 2026 11:46 UTC
    Approved Reviewer

    Re-review after rebase onto 34f2ed0 (includes #7964).

    Standards

  • The Spring-context regression test now exercises the real component-scan wiring and is mutation-sensitive: removing @Component from ScaleObserver yields zero observer beans and fails the test.

  • Boundary coverage at 40.0 and 80.0, plus above/below/within/disabled cases, is correct.

  • No blocking style or test violations. Optional non-blocking follow-ups: cover the existing null-MetricData branch and deduplicate the shared rule fixture between the two tests.
  • Spec

  • ScaleObserver is registered through Spring, and monitorMetrics() now reaches scaleByAction.

  • The merged #7964 owner/lease guard is present in the base (ScaleService.active plus master-only lifecycle), so the previous multi-replica merge-order blocker is resolved.

  • No scope creep or missing spec requirements.
  • Verification: ./mvnw -pl shenyu-admin -am -Dtest=MetricsMonitorTest,ScaleObserverContextTest -DfailIfNoTests=false -Djacoco.skip=true test passes with 8 tests. Checkstyle reports 0 violations, and required GitHub checks pass.

    Approving.

    Reviewers
    Assignees
    imDwAaY imDwAaY
    Labels
    risk: low confidence: 76.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 40.2% (MEDIUM) · Higher = larger blast radius
    40.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 76.2% · Lower = rushed or shallow review
    76.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.6% · Safe to merge
    9.6%
    Repository