Skip to content

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

Merged
Aias00 merged 1 commit into
fix/adaptive-neutral-client-errorfrom
fix/adaptive-feedback-cleanup
Nov 13, 2026
Merged

Aias00 merged 1 commit into
fix/adaptive-neutral-client-errorfrom
fix/adaptive-feedback-cleanup

Conversation

@dmsolr

@dmsolr dmsolr commented Nov 10, 2026

Copy link
Copy Markdown
Member

What this PR does

Repairs the adaptive feedback registry lifecycle (both problems from the issue):

  1. Singleton pools now drive cleanup. Maintenance moved from doSelect to select(), so the inherited singleton fast path no longer bypasses it. Removed/replaced addresses are reclaimed even when traffic keeps using singleton candidate lists. The singleton inflight reservation pairing ([BUG] P2C inflight becomes negative when only one upstream is eligible #7974 semantics) is untouched.
  2. Maintenance is bounded in work and frequency. pruneIfNeeded no longer sweeps the whole map on every selection above 256 entries:
    • time gate: at most one run per MAINTENANCE_INTERVAL_MILLIS (10 s); selections in between pay only a size check;
    • work budget: each run inspects at most MAINTENANCE_SCAN_BUDGET (64) entries via a resume cursor;
    • once armed, maintenance keeps draining across windows until a full scan cycle prunes nothing, so expired entries are reclaimed even after the map shrinks below the threshold;
    • hard capacity MAX_TRACKED_IDENTITIES (4096): beyond it a full idle sweep runs regardless of the interval, and any remaining excess is evicted oldest-activity-first. Statistics are only a scoring cache — eviction merely returns a node to the cold-start comparison; in-flight reservations live on the upstream and are never touched, and exploration (lastPicked) is unaffected.

Concurrency: removals use conditional remove(key, value), so a feedback recorded between inspection and removal keeps its fresh record; removal/re-addition simply restarts the identity cold. No scheduler is introduced — maintenance stays on the existing selection path.

Related Issue

Fixes #8384

Refs #8300, #8365

Stacked PR

Based on #8399 (fix/adaptive-neutral-client-error), which is based on #8398 (fix/adaptive-ewma-precision); all three touch AdaptiveUpstreamStats. Merge order: #8398 → #8399 → this PR, retargeting bases to master as each lands. The diff against its base contains only this fix.

Type of change

  • Bug fix
  • Performance improvement

How was this tested

  • Unit tests added: singleton selection drives maintenance and drains expired identities (issue fixture), hot set above threshold pays zero scan inside the interval and stays within the per-run budget (asserted via lastScanCount()), hard-capacity oldest-activity eviction with all-active identities, concurrent feedback surviving maintenance; existing prune test updated to the bounded drain semantics — deterministic timestamps, no sleeps
  • ./mvnw test -pl shenyu-loadbalancer passed (136 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 (new constants are additive; pruneIfNeeded keeps its signature)

…n pools

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

@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

Moving maintenance into select() so the singleton fast path also reclaims identities, and the conditional remove(key, value) for concurrent feedback, are both correct in spirit. Two points below are worth settling before merge: the capacity branch is still an unbudgeted whole-map sweep, and one new test is scheduling-dependent.

Service / behaviour

  1. The capacity branch bypasses the time gate — the remaining O(N log N) per-selection path. In maintain():

    if (before > MAX_TRACKED_IDENTITIES) {
        sweepIdle(nowMillis);
        evictOldestBeyondCapacity();   // new ArrayList<>(stats.entrySet()) + sort, inside synchronized

    This runs before maintenanceDue(nowMillis), so once the map exceeds 4096 every entry that crosses the cap pays a full removeIf, a full copy and a sort on the selection thread, serialized against every other selection. Under discovery churn near the cap this can repeat and stall gateway-wide selection — the same class of cost #8384 asks to bound ("a hot set above 256 identities does not trigger a whole-map sweep per selection"). Suggest gating the capacity path by the interval as well (or sampling instead of sorting the whole map) and asserting the work bound for this branch, since hardCapacityEvictsOldestActivityWhenNothingIsIdle only checks size and state.

  2. Eviction is hostile to slow in-flight nodes. lastFeedbackMillis advances only on completion, so an upstream currently serving a long request is by definition the "oldest activity" and is evicted first; its completion then re-enters as a cold start, discarding the evidence the routing decision was based on. The class javadoc notes that in-flight reservations live on the upstream, which is true, but the statistics are not protected. Spec #8384 asks to "do not clear active statistics indiscriminately" — skipping identities with inflight > 0 (or evicting idle-first, then least-recently-active) would meet it.

  3. Javadoc/code contradictions. The class doc says maintenance "runs at most once per MAINTENANCE_INTERVAL_MILLIS" and that "selections in between pay only the size check", but (a) the capacity branch above ignores the interval, and (b) once maintenancePending is armed, skipped selections still take the synchronized monitor. Also sweepIdle() assigns lastScanCount = stats.size(), the post-sweep map size, which contradicts lastScanCount()'s "entries inspected by the last maintenance run".

  4. maintain() is synchronized on the per-request path. Every adaptive selection — including single-upstream routes — now acquires the same global monitor; previously the prune was an unsynchronized removeIf. ConcurrentHashMap plus an immutable cursor snapshot would avoid serializing all selections behind maintenance.

  5. return before - stats.size() can be negative when inserts race the sweep, while the javadoc promises "the number of pruned identities". Math.max(0, …) or a reworded contract.

  6. The idle predicate is now duplicated in scanBudgeted() and sweepIdle(), and five coordination fields (maintenancePending, lastMaintenanceMillis, scanCursor, cyclePruned, lastScanCount) always move together — a small private cursor object would shrink maintain() and keep the bound testable.

Tests

  1. concurrentFeedbackSurvivesMaintenance is scheduling-dependent. The writer refreshes up to IDLE_MILLIS + 2000, while the pruner advances its clock 50 × 10 s = ~490 s past IDLE_MILLIS; if the pruner runs last, the target is legitimately expired and assertNotNull(statsOf(target)) fails. Please bound the pruner's clock (or stop it once the writer is done) so the assertion cannot depend on thread ordering.
  2. while (stats.size() > 0) loops (the updated prune test and singletonTrafficStillDrivesCleanup) have no iteration cap; a drain regression hangs CI instead of failing. Add a max-iteration guard.
  3. singletonTrafficStillDrivesCleanup drives one real select() and then drains with synthetic timestamps; the multi-candidate replacement cycle from the issue ("including repeated discovery replacement") is still only exercised through pruneIfNeeded() directly.

Spec (#8384)

  • Cleanup on the singleton path: met, with a test.
  • "A hot set above 256 identities does not trigger a whole-map sweep per selection": met above the threshold, not met at the hard capacity (finding 1).
  • "Define retained-state limits, expiry/capacity policy and behaviour under concurrent feedback and removal/re-addition": capacity and concurrent feedback are documented; prune-then-re-add is documented only implicitly ("restarts the identity cold") and has no test.
  • "Preserve in-flight reservations, exploration and equivalent-address history": reservations and lastPicked survive; the statistics of a live-but-slow node do not (finding 2).
  • "Any scheduler introduced has an explicit owner": satisfied — no scheduler was added.

@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

Bounded adaptive feedback cleanup and singleton-pool coverage reviewed. The VERSIONED_DIFF was read in full (17400 chars, has_more=false) and matches the 3-file WHOLE_PR scope in the frozen evidence.

Evidence

  • VERSIONED_DIFF fully read (17400 chars, has_more=false) across AdaptiveLoadBalancer.java, AdaptiveUpstreamStats.java and AdaptiveLoadBalancerTest.java, matching the 3-file WHOLE_PR scope in the attachment.
  • Frozen evidence: CI complete=true with 32 checks, passed=true (build, CodeQL, rat_check, check-license-header, agent_gateway_migrations success; test_group/compat_java21/build_local_repo skipped).
  • pruneIfNeeded moved to select() (singleton fast path) and maintain() is synchronized, interval-gated (MAINTENANCE_INTERVAL_MILLIS), scan-budgeted (MAINTENANCE_SCAN_BUDGET) with a resumable cursor and a MAX_TRACKED_IDENTITIES hard cap; new tests assert singleton cleanup, per-interval no-sweep, capacity eviction and concurrent-feedback survival.

Recommended next steps

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

Task: e77d23ef-a0bf-40ca-ae98-ac5571c9eb24 · Commit: 61a48d6892f30d58659c41dff072bc53065c7ba1

Review verdict: PASS

Full diff coverage with complete and passing CI and no concrete blocking defect. The singleton fast path now drives maintenance, and the amortized prune is correctly interval-gated, scan-budgeted with a resumable cursor, armed across windows until a drain completes, and hard-capped with oldest-activity eviction; the in-flight reservation pairing in doSelect is untouched and all behaviors are covered by the updated and new tests.

Publication: APPROVE (EXPLICIT_PASS)

@Aias00 Aias00 added this to the 2.7.3 milestone Nov 13, 2026
@Aias00
Aias00 merged commit 84e3fcd into fix/adaptive-neutral-client-error Nov 13, 2026
32 checks passed
Aias00 pushed a commit that referenced this pull request Nov 14, 2026
…#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
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