[ISSUE #7965] Register the scaling observer so metric-driven policies actuate #7966
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.
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.
Thanks for connecting the observer. The production change is small and the single-instance path is correct, but I found two blocking issues.
Standards
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.> / <; adding assertions for exactly 40.0 and 80.0 would pin the intended non-scaling boundary behavior.Spec
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.
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)
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.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.
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:
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.
Re-review of aec13be.
Standards
ScaleObserverContextTest boots an AnnotationConfigApplicationContext, discovers the observer through component scanning, resolves MetricsMonitor, and verifies one SCALE_UP call. Removing @Component makes the test fail.40.0 and 80.0 boundary cases are now covered. No new documented-standard violations or blocking smells were found.Spec
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.
@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.
Re-review after rebase onto 34f2ed0 (includes #7964).
Standards
@Component from ScaleObserver yields zero observer beans and fails the test.40.0 and 80.0, plus above/below/within/disabled cases, is correct.MetricData branch and deduplicate the shared rule fixture between the two tests.Spec
ScaleObserver is registered through Spring, and monitorMetrics() now reaches scaleByAction.ScaleService.active plus master-only lifecycle), so the previous multi-replica merge-order blocker is resolved.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.
Aias00
imDwAaY
Problem
Policy 3 (metric-driven scaling) never actuates.
MetricsMonitor.monitorMetrics()evaluates enabledScaleRuleDOrows and callsnotifyObservers(...), but nothing ever callsMetricsMonitor.addObserver(...)andScaleObserveris never instantiated in production code. The observer list is therefore always empty: Prometheus is read and rules are evaluated, butKubernetesScaler.scaleByActionis never reached.Fixes #7965.
Change
ScaleObserveris now a Spring@Component.MetricsMonitorconstructor-injectsList<Observer>and copies it into its mutable observer list, so Spring registers everyObserverbean at startup. The existingaddObserver/removeObservercontract is unchanged.Tests
New
MetricsMonitorTestcovers:maximumproduces exactly oneSCALE_UPactionminimumproduces exactly oneSCALE_DOWNactionAll 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.