Skip to content

fix(loadbalancer): keep adaptive EWMA precision at short feedback intervals - #8398

Open
dmsolr wants to merge 6 commits into
masterfrom
fix/adaptive-ewma-precision
Open

dmsolr wants to merge 6 commits into
masterfrom
fix/adaptive-ewma-precision

Conversation

@dmsolr

@dmsolr dmsolr commented Nov 10, 2026

Copy link
Copy Markdown
Member

What this PR does

Fixes the adaptive EWMA quantization loss: every smoothed update was cast to whole millis, so at short feedback intervals each sub-millisecond increment was discarded and a previously fast upstream could stay pinned at its old estimate even under sustained slower responses (the issue fixture stayed at 1 after 10,000 consecutive 100 ms samples).

  • Stats now keeps the EWMA as a double in millis internally; rounding happens only where a long leaves the record (ewmaLatencyMillis() accessor, Math.round) and at the score ceiling. Scoring uses the unrounded value.
  • Same-timestamp behavior is defined explicitly: the decay interval is clamped to a minimum of 1 ms (MIN_DECAY_INTERVAL_MILLIS), so concurrent completions are blended with real weight instead of being discarded with zero weight.
  • Minimum-sample fallback, failure penalty floor, effective weights, exploration and all non-adaptive strategies are unchanged; the estimate stays finite and non-negative (convex blend of non-negative samples).

Related Issue

Fixes #8382

Refs #8300 (opt-in adaptive scoring), #8365 (merged implementation)

Type of change

  • Bug fix

How was this tested

  • Unit tests added: sustained-latency convergence (issue fixture now reaches ~100 ms), same-timestamp observations, decreasing latency at 1 ms intervals, failure penalty floor under short-interval smoothing — all deterministic timestamps, no sleeps
  • ./mvnw test -pl shenyu-loadbalancer passed (126 tests)
  • Checkstyle passed (validate phase of the build)

Checklist

  • No new source files (existing files keep their Apache 2.0 headers)
  • No breaking changes to public API / config / DB schema (Stats is package-private; the ewmaLatencyMillis() accessor keeps its long contract)

…ervals

The adaptive strategy truncated every smoothed update to whole millis, so
sub-millisecond increments at short feedback intervals were discarded and a
previously fast upstream could stay pinned at its old estimate forever.

- keep the EWMA as a double in millis inside Stats; round only where a long
  leaves the record (ewmaLatencyMillis accessor and the score ceiling)
- define same-timestamp behavior: blend with a minimum 1 ms decay interval
  instead of giving the new sample zero weight
- add deterministic regressions for sustained latency convergence, same
  timestamps, decreasing latency and the failure penalty floor

@wy471x wy471x left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two-axis review — standards & spec

Keeping the EWMA as a double and rounding only at the edge is the right shape for #8382, and the new tests are deterministic and sleep-free. Findings below are ordered by severity; the first one is the only one I would ask you to settle before merge.

Service / behaviour

  1. score() now ceils an unrounded double — an unrequested scoring change. AdaptiveUpstreamStats.score() uses (current.ewmaLatency() + 1) * … and then (long) Math.ceil(score). Previously the estimate was an exact long, so the ceiling was exact. Now sub-unit float residue flips the result: an estimate of 1.0000001 scores 3 while 0.9999999 scores 2, i.e. two nodes whose latency is indistinguishable get different routing scores, and any score whose fractional part crosses an integer shifts by 1 (e.g. ewma=1.4, inflight=0, weight=1: 2 before, 3 after). score() is asserted nowhere in the diff. If identical routing to before is intended, score the rounded value (ewmaLatencyMillis()); if the shift is intended, please state it in the class javadoc and cover it with a test.

  2. The minimum decay interval makes the 600 ms window rate-dependent. smooth() applies Math.max(sinceLastMillis, MIN_DECAY_INTERVAL_MILLIS) per sample, so N completions stamped in the same millisecond contribute N ms of decay. 600 same-millisecond completions after a 1 ms baseline move the estimate exp(-1) ≈ 63 % of the way to the burst latency within one wall-clock millisecond, while the same 600 samples spread over 600 ms behave completely differently. The clamp also converts negative gaps (out-of-order feedback, clock regression) into 1 ms of evidence; the old code gave them zero weight, and the javadoc only justifies the zero-gap case. Suggest handling sinceLastMillis <= 0 explicitly and documenting the intended rate-dependence.

  3. MIN_DECAY_INTERVAL_MILLIS is public on a public class but only used internally; a package-private constant keeps the SPI surface unchanged.

Tests

  1. decreasingLatencyPullsTheEstimateDownAtShortIntervals also passes on master — integer truncation converges downward at 1 ms intervals too — so it is a guard, not a regression test for this defect.
  2. sameTimestampObservationsStillMoveTheEstimate is the only test proving the behavioural change and asserts just > 1L; a per-sample weighting of 1e-6 would still pass. Please assert a real bound.
  3. The four new tests repeat the same three-line arrange block; a small helper would keep them readable.

Spec (#8382)

  • Convergence and short-interval/same-timestamp coverage: met.
  • "Keep statistics finite and non-negative" is documented in the javadoc but not asserted anywhere; it holds by construction via latencyOf, so one assertion in the existing tests would close the criterion.
  • No scope creep — the change touches only Stats and its tests.

…#8399)

* fix(loadbalancer): keep neutral 4xx feedback out of the sample timing

CLIENT_ERROR feedback replaced lastFeedbackMillis, and the next latency-bearing
sample computed its decay from that timestamp, so an unrelated 4xx could greatly
change recovery from an earlier slow or failed attempt.

- split activity bookkeeping (lastFeedbackMillis, retention/pruning only) from
  the effective-sample timestamp (lastSampleMillis) that drives the decay
- a 4xx refreshes activity only; EWMA, sample count and sample timing stay intact
- an identity first seen through a 4xx stays cold and takes its first real
  sample as-is
- add deterministic regressions: issue fixture equivalence, many interleaved
  4xx, cold-target neutrality, retention via 4xx activity, concurrent accounting

* fix(loadbalancer): bound adaptive feedback cleanup and cover singleton pools (#8400)

Cleanup only ran from doSelect, so the singleton fast path never reclaimed
removed addresses, and pruneIfNeeded swept the whole map on every multi-node
selection once the size exceeded 256.

- move maintenance to select() so singleton traffic drives cleanup too; the
  inflight reservation pairing is untouched
- gate maintenance by a 10 s interval and a 64-entry scan budget with a resume
  cursor; once armed it drains across windows until a full cycle prunes nothing,
  so expired entries are reclaimed even below the threshold
- hard capacity of 4096 identities: full idle sweep plus oldest-activity eviction
  beyond it; eviction only drops scoring cache, never in-flight reservations
- conditional remove(key, value) keeps concurrently refreshed records safe
- update the prune test to the bounded semantics and add regressions for
  singleton cleanup, the per-run work bound, capacity eviction and concurrent
  feedback during maintenance
Address review on #8398:
- score() ceils ewmaLatencyMillis() so sub-millisecond residue cannot shift
  routing; the double estimate stays internal to the smoothing
- smooth() handles zero and negative gaps explicitly with the minimum decay
  interval instead of Math.max, and the constant documents the intended
  per-sample rate dependence; MIN_DECAY_INTERVAL_MILLIS is package-private
- strengthen the same-timestamp test to the analytic ~96 ms blend bound, turn
  the decreasing-latency test into a real regression (a 10-sample burst must
  follow the 600 ms time constant instead of collapsing by truncation), assert
  finite/non-negative statistics, and extract the shared arrange helper
- add score rounding and backward-clock coverage
compare() scored each candidate through getWeight(), which read the wall
clock separately per candidate. When the millisecond ticked between the two
reads and both upstreams were created in the previous millisecond, one score
used the full weight (uptime 0) while the other used the warm-up weight
(uptime 1), inverting the comparison and flaking
fastServerErrorsArePenalizedByTheFailureFloor.

Add a protected getWeight(upstream, nowMillis) overload and pass the single
selection instant already sampled in doSelect through compare/score, so both
candidates are always weighed on the same scale. Other selectors keep the
existing clock-reading entry point unchanged. Cover the sampled-instant
weight contract and the single-instant comparison with deterministic tests.
@dmsolr

dmsolr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

@wy471x Thanks for the two-axis review — every item is addressed in ffbedd7, plus 0faf723 for a pre-existing flake that the verification surfaced (details at the end).

Service / behaviour

1. score() ceils an unrounded double — took the behaviour-preserving option: score() now ceils ewmaLatencyMillis(), so routing stays identical to whole-millisecond estimates and the double remains internal to the smoothing. The class and accessor javadoc now state that ewmaLatencyMillis() is the single rounded exit. New scoreUsesTheRoundedLatencyEstimate pins exactly the scenario you described (ewma ≈ 1.0066 with inflight 0 / weight 1 must score 2, not 3) plus the inflight/weight scaling path; confirmed it fails on the previous branch state (expected 2, was 3).

2. Rate-dependent minimum decay / negative gaps — smooth() now handles sinceLastMillis <= 0 explicitly: a zero or negative gap (same-timestamp completion, out-of-order feedback, clock regression) blends with the minimum interval instead of relying on Math.max semantics, so a backward clock can neither discard nor amplify the sample. The constant's javadoc documents the intended per-sample rate dependence (N completions sharing one timestamp advance the estimate by N minimum intervals). New backwardClockFeedbackBlendsLikeASameTimestampCompletion pins that a −5 ms gap blends exactly like a same-timestamp completion and still counts as a latency sample.

3. MIN_DECAY_INTERVAL_MILLIS visibility — now package-private (moved after the public constants to satisfy DeclarationOrder); it had no external users.

Tests

4. Decreasing-latency test was a guard — restructured into a real regression: from a 100 ms baseline, a 10-sample burst at 1 ms intervals must follow the 600 ms time constant (~98 ms, asserted within [95, 100]); master's per-update truncation collapses the estimate to 90 and fails the assertion (verified against origin/master's Stats). The sustained phase then asserts exact convergence to 1 ms. A downward-only upper bound can never fail under truncation (it biases the estimate low), so the regression anchor is the burst's lower bound rather than the convergence ceiling.

5. sameTimestamp assertion strength — now asserts the analytic blend band [95, 97] (100 − 99·e^(−2000/600) ≈ 96.5 ms); a token per-sample weight of 1e-6 would leave the estimate near 1 ms and fail. Verified failing on master (got 1).

6. Repeated arrange block — extracted statsSeededWith(identity, elapsed, outcome), shared by all four tests.

Spec (#8382)

The finite/non-negative criterion is now asserted in sustainedSlowerSamplesConvergeDespiteShortFeedbackIntervals.

Additional commit (0faf723)

The verification runs surfaced a pre-existing flake in fastServerErrorsArePenalizedByTheFailureFloor (reproduces on the unmodified branch as well): compare() scored each candidate through getWeight(), which read the wall clock separately per candidate. When the millisecond ticked between the two reads and both upstreams were created in the previous millisecond, one score used the full weight (uptime 0) while the other used the warm-up weight (uptime 1), inverting the comparison. Added a protected getWeight(upstream, nowMillis) overload and passed the single selection instant already sampled in doSelect through compare/score, so both candidates are always weighed on the same scale; the other selectors keep the existing entry point unchanged. Two deterministic tests cover the sampled-instant weight contract and the single-instant comparison.

Verification: ./mvnw -pl shenyu-loadbalancer -am test — 140 tests, 0 failures, Checkstyle clean; 20 consecutive runs of AdaptiveLoadBalancerTest green after the flake fix.

…stream

master's shared upstream() helper now disables warm-up to keep selection
comparisons weight-stable; the sampled-instant weight test needs the ramp,
so build its own warm-up-enabled upstream instead of relying on the helper.
@dmsolr

dmsolr commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

CI note: the first push failed in the merge-with-master build because master's shared upstream() test helper now disables warm-up (weight-stable comparisons), while the new sampled-instant weight test relied on the helper's ramp. Fixed in 469bc31 by building an explicit warm-up-enabled upstream inside that test, and synced master via merge commit 75e64ea. The production single-instant weight sampling complements master's fixture stabilization (which only covers the test path). Verified on the merged tree: ./mvnw -pl shenyu-loadbalancer -am test — 143 tests, 0 failures, Checkstyle clean.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG][Load Balancer] Adaptive EWMA can remain at 1 ms during sustained 100 ms responses

2 participants