Repository navigation
fix(loadbalancer): bound adaptive feedback cleanup and cover singleton pools - #8400
Conversation
…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
left a comment
There was a problem hiding this comment.
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
-
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 fullremoveIf, 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, sincehardCapacityEvictsOldestActivityWhenNothingIsIdleonly checks size and state. -
Eviction is hostile to slow in-flight nodes.
lastFeedbackMillisadvances 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 withinflight > 0(or evicting idle-first, then least-recently-active) would meet it. -
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) oncemaintenancePendingis armed, skipped selections still take thesynchronizedmonitor. AlsosweepIdle()assignslastScanCount = stats.size(), the post-sweep map size, which contradictslastScanCount()'s "entries inspected by the last maintenance run". -
maintain()issynchronizedon the per-request path. Every adaptive selection — including single-upstream routes — now acquires the same global monitor; previously the prune was an unsynchronizedremoveIf.ConcurrentHashMapplus an immutable cursor snapshot would avoid serializing all selections behind maintenance. -
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. -
The idle predicate is now duplicated in
scanBudgeted()andsweepIdle(), and five coordination fields (maintenancePending,lastMaintenanceMillis,scanCursor,cyclePruned,lastScanCount) always move together — a small private cursor object would shrinkmaintain()and keep the bound testable.
Tests
concurrentFeedbackSurvivesMaintenanceis scheduling-dependent. The writer refreshes up toIDLE_MILLIS + 2000, while the pruner advances its clock 50 × 10 s = ~490 s pastIDLE_MILLIS; if the pruner runs last, the target is legitimately expired andassertNotNull(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.while (stats.size() > 0)loops (the updated prune test andsingletonTrafficStillDrivesCleanup) have no iteration cap; a drain regression hangs CI instead of failing. Add a max-iteration guard.singletonTrafficStillDrivesCleanupdrives one realselect()and then drains with synthetic timestamps; the multi-candidate replacement cycle from the issue ("including repeated discovery replacement") is still only exercised throughpruneIfNeeded()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
lastPickedsurvive; 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
left a comment
There was a problem hiding this comment.
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)
…#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
What this PR does
Repairs the adaptive feedback registry lifecycle (both problems from the issue):
doSelecttoselect(), 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.pruneIfNeededno longer sweeps the whole map on every selection above 256 entries:MAINTENANCE_INTERVAL_MILLIS(10 s); selections in between pay only a size check;MAINTENANCE_SCAN_BUDGET(64) entries via a resume cursor;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 touchAdaptiveUpstreamStats. Merge order: #8398 → #8399 → this PR, retargeting bases tomasteras each lands. The diff against its base contains only this fix.Type of change
How was this tested
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-loadbalancerpassed (136 tests)Checklist
pruneIfNeededkeeps its signature)