Skip to content

fix(loadbalancer): keep neutral 4xx feedback out of the sample timing - #8399

Merged
Aias00 merged 2 commits into
fix/adaptive-ewma-precisionfrom
fix/adaptive-neutral-client-error
Nov 14, 2026
Merged

Aias00 merged 2 commits into
fix/adaptive-ewma-precisionfrom
fix/adaptive-neutral-client-error

Conversation

@dmsolr

@dmsolr dmsolr commented Nov 10, 2026

Copy link
Copy Markdown
Member

What this PR does

Makes CLIENT_ERROR feedback truly neutral for the adaptive latency path. Previously Stats.next replaced lastFeedbackMillis on a 4xx, and the next latency-bearing sample computed its decay from that timestamp — an unrelated 4xx could greatly change recovery from an earlier slow or failed attempt (issue fixture: 229 without the 4xx vs 998 with it).

  • Split the two clocks in Stats: lastFeedbackMillis remains the activity timestamp of the last feedback of any class (retention/pruning only); the new lastSampleMillis records the last latency-bearing observation and is the only clock the decay uses.
  • A 4xx refreshes activity only — EWMA, sample count and effective-sample timing stay intact, so inserting one or many 4xx leaves subsequent updates equivalent for the same latency samples.
  • An identity first seen through a 4xx stays cold (samples == 0) and takes its first real sample as-is; a client error alone never warms a target.

Related Issue

Fixes #8383

Refs #8300, #8365. Independent of the integer-rounding loss fixed in #8398.

Stacked PR

Based on #8398 (fix/adaptive-ewma-precision) because both touch AdaptiveUpstreamStats.Stats. Please merge #8398 first; this PR's base will then be retargeted to master. The diff against its base contains only this fix.

Type of change

  • Bug fix

How was this tested

  • Unit tests added: issue fixture equivalence (with/without 4xx), many interleaved 4xx, 4xx-only cold target, identity first seen through 4xx, retention via 4xx activity, concurrent feedback sample accounting — deterministic timestamps, no sleeps
  • ./mvnw test -pl shenyu-loadbalancer passed (132 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)

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

@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

Splitting the activity clock from the sample clock is exactly the separation #8383 asks for, and the two equivalence tests are genuine regression tests (they fail on the base because the decay interval differs). Comments below.

Service / behaviour

  1. Stats.first(...) uses nowMillis for both clocks, including CLIENT_ERROR. For an identity first seen through a 4xx, lastSampleMillis — documented as "receipt time of the last latency-bearing observation" — holds a 4xx timestamp. It is harmless today only because samples <= 0 skips smooth; if the cold-start branch ever changes, the original defect returns silently. Consider outcome == CLIENT_ERROR ? 0L : nowMillis, or state in the javadoc why the initial value is unobservable.

  2. Out-of-order feedback now means "1 ms of decay", not "no weight". With smooth() clamping to MIN_DECAY_INTERVAL_MILLIS (#8398), a negative nowMillis - lastSampleMillis is treated as real elapsed time. That is reachable: concurrentFeedbackKeepsSampleAccountingConsistent feeds worker-local timestamps (now = worker * perWorker + i) that regress whenever threads interleave, and production can deliver completions out of order. Consider clamping the negative case to zero weight explicitly.

  3. Record readability. Stats now carries four positional fields where three collide in type: new Stats(updated, samples + 1L, nowMillis, nowMillis) next to new Stats(ewmaLatency, samples, nowMillis, lastSampleMillis). Two named factories (latencyBearing(...) / neutral(...)) would make the argument swap that this PR is fixing impossible.

  4. clientErrorDoesNotReshapeTheNextLatencyUpdate and manyClientErrorsLeaveSubsequentUpdatesEquivalent duplicate the same paired-stats harness; a helper would reduce the copy-paste.

Spec (#8383)

  • "Inserting one or many 4xx leaves subsequent updates equivalent" — met and tested.
  • "A client error alone never increases the sample count or makes a cold target warm" — met and tested.
  • "Separate activity/retention bookkeeping from effective-sample timing" — implemented, but only observed indirectly through the EWMA. A direct assertion that lastSampleMillis is unchanged after a 4xx (and after many 4xx) would pin the contract you added to the javadoc.
  • "Verify recovery, pruning and concurrent updates with deterministic timestamps" — partial:
    • clientErrorActivityStillCountsForRetention asserts only assertNotNull; also assert that the filler identities were pruned, so the test proves pruning actually ran rather than that it was a no-op.
    • concurrentFeedbackKeepsSampleAccountingConsistent asserts only the sample count and finiteness. It cannot detect the bug class it targets; add an equality check of the EWMA (or lastSampleMillis) against a single-threaded control run.
  • No scope creep.

…n 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

@Aias00 Aias00 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.

Stream Agent analysis

PR #8399 verified: CLIENT_ERROR feedback no longer shifts the latency-sample clock; the complete pinned diff (3 files) and CI evidence were covered and no blocking defect was found.

Evidence

  • Coverage: the frozen whole diff was read via resource_diff with empty path (26764 chars through has_more=false) plus per-file diffs for AdaptiveLoadBalancer.java, AdaptiveUpstreamStats.java and AdaptiveLoadBalancerTest.java; all four diff resources show complete=true with next_unread_offset == total_characters. Pinned head/base source and tests were also inspected; late re-reads were served from the archived ledger, not missing pages.
  • shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/AdaptiveUpstreamStats.java RIGHT: Stats.next returns new Stats(ewmaLatency, samples, nowMillis, lastSampleMillis) for CLIENT_ERROR (only the activity clock moves) and computes smooth(latency, nowMillis - lastSampleMillis); Stats.first and latency-bearing updates set both clocks, so an unrelated 4xx can no longer reshape the next latency update. lastFeedbackMillis remains the retention/pruning clock used by scanBudgeted/sweepIdle/evictOldestBeyondCapacity.
  • CI attachment: 32 checks, complete=true, failed_checks=[], passed=true (test_group, compat_java21 and build_local_repo reported as skipped). Added maintenance uses conditional removes, a bounded incremental scan and a documented full idle sweep beyond hard capacity; no HIGH/CRITICAL defect identified. The reviewer did not execute tests.

Recommended next steps

Scope: captured diff and GitHub check metadata only; no local tests were executed.

Task: 1fed6d08-1703-4f48-8f2b-4e879a53a4bf · Commit: 84e3fcd0dd6aa9e7a81b963a24c055caf40dd364

Review verdict: PASS

Full diff coverage at pinned head 84e3fcd (complete_diff=true, every diff page read to has_more=false) and CI reported passing with zero failed checks. The verified change splits feedback/activity timing from latency-sample timing, which fixes the described 229-vs-998 regression; the load balancer's select/onFeedback paths and the pruning logic that still keys on lastFeedbackMillis stay consistent, and the bundled maintenance helpers use conditional removes to avoid clobbering concurrent feedback. No concrete HIGH/CRITICAL blocking defect anchored to the diff was found. Caveats: several optional CI groups were skipped, the reviewer ran no tests locally, and a minor non-blocking test-quality issue (unchecked Futures in the concurrency test) exists; none of these is a coverage gap or a blocking defect.

Publication: APPROVE (EXPLICIT_PASS)

@Aias00
Aias00 merged commit 718866b into fix/adaptive-ewma-precision Nov 14, 2026
32 checks passed
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.

3 participants