diff --git a/shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/AdaptiveLoadBalancer.java b/shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/AdaptiveLoadBalancer.java
index 69940576f276..081bfed0d411 100644
--- a/shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/AdaptiveLoadBalancer.java
+++ b/shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/AdaptiveLoadBalancer.java
@@ -83,6 +83,10 @@ AdaptiveUpstreamStats stats() {
@Override
public Upstream select(final List upstreamList, final LoadBalanceData data) {
+ // maintenance must cover the singleton fast path too: completed singleton
+ // attempts still record statistics, and removed addresses would otherwise
+ // linger forever while traffic keeps using singleton candidate lists
+ stats.pruneIfNeeded(System.currentTimeMillis());
Upstream picked = super.select(upstreamList, data);
// AbstractLoadBalancer short-circuits a singleton candidate list before doSelect
// runs, so the in-flight reservation made here pairs the completion decrement in
@@ -97,7 +101,6 @@ public Upstream select(final List upstreamList, final LoadBalanceData
@Override
protected Upstream doSelect(final List upstreamList, final LoadBalanceData data) {
long now = System.currentTimeMillis();
- stats.pruneIfNeeded(now);
Upstream[] upstreams = pickTwoUpstreams(upstreamList);
Upstream picked;
Upstream unpicked;
diff --git a/shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/AdaptiveUpstreamStats.java b/shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/AdaptiveUpstreamStats.java
index 688de80df2ec..9e58bc6a28c5 100644
--- a/shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/AdaptiveUpstreamStats.java
+++ b/shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/AdaptiveUpstreamStats.java
@@ -19,6 +19,10 @@
import org.apache.shenyu.loadbalancer.entity.UpstreamIdentity;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalLong;
@@ -40,13 +44,24 @@
* latency sample of at least {@link #FAILURE_PENALTY_MILLIS} — this is what keeps a
* fast failing node unattractive: finishing quickly can never make its score smaller
* than the failure floor, and a clean node recovers because subsequent successful
- * samples dominate the smoothing.
+ * samples dominate the smoothing. Neutrality also covers timing: a 4xx refreshes the
+ * activity timestamp used for retention, but never the effective-sample timestamp
+ * that drives the decay of the next latency-bearing observation.
*
- * The map is bounded: once it holds more than {@link #PRUNE_THRESHOLD} entries a
- * selection prunes the identities whose last feedback is older than
- * {@link #IDLE_MILLIS}, so churned upstreams cannot accumulate indefinitely. All
- * timing is passed in by the caller, which keeps the scoring deterministic under
- * test.
+ * The map is bounded by amortized maintenance: once it holds more than
+ * {@link #PRUNE_THRESHOLD} entries, selections drive a prune that drops identities
+ * without feedback for {@link #IDLE_MILLIS}. Maintenance runs at most once per
+ * {@link #MAINTENANCE_INTERVAL_MILLIS} and inspects at most
+ * {@link #MAINTENANCE_SCAN_BUDGET} entries per run, so a hot set above the threshold
+ * never pays a whole-map sweep per selection. Once triggered, maintenance keeps
+ * running across windows until a full scan cycle completes without pruning anything,
+ * so expired entries are drained even after the map shrinks below the threshold.
+ * Above the hard capacity
+ * {@link #MAX_TRACKED_IDENTITIES} a full idle sweep runs instead, and any remaining
+ * excess is evicted oldest-activity-first: statistics are only a scoring cache, so
+ * eviction merely returns a node to the cold-start comparison, while in-flight
+ * reservations live on the upstream itself and are never touched. All timing is
+ * passed in by the caller, which keeps the scoring deterministic under test.
*/
public class AdaptiveUpstreamStats {
@@ -85,8 +100,37 @@ public class AdaptiveUpstreamStats {
*/
public static final int PRUNE_THRESHOLD = 256;
+ /**
+ * Minimum gap between two maintenance runs; selections in between pay only the
+ * size check, so a hot set above the threshold is not swept on every selection.
+ */
+ public static final long MAINTENANCE_INTERVAL_MILLIS = 10_000L;
+
+ /**
+ * Maximum number of entries inspected by one incremental maintenance run; the
+ * scan cursor resumes where the previous run stopped.
+ */
+ public static final int MAINTENANCE_SCAN_BUDGET = 64;
+
+ /**
+ * Hard capacity of the registry. Beyond it a full idle sweep runs regardless of
+ * the maintenance interval, and any remaining excess is evicted
+ * oldest-activity-first so retained state stays bounded under discovery churn.
+ */
+ public static final int MAX_TRACKED_IDENTITIES = 4096;
+
private final Map stats = new ConcurrentHashMap<>();
+ private volatile boolean maintenancePending;
+
+ private long lastMaintenanceMillis = Long.MIN_VALUE;
+
+ private Iterator> scanCursor;
+
+ private int cyclePruned;
+
+ private int lastScanCount;
+
/**
* Record one classified attempt. The elapsed time is the caller's own
* per-attempt measurement, so overlapping attempts never share a timestamp.
@@ -142,22 +186,98 @@ public boolean bothAdaptive(final UpstreamIdentity first, final UpstreamIdentity
}
/**
- * Amortized prune, called from the selection path: only runs a scan once the map
- * outgrew its threshold, and then drops identities without feedback for
- * {@link #IDLE_MILLIS}.
+ * Amortized prune, called from the selection path (both the singleton fast path
+ * and the multi-candidate comparison): only runs once the map outgrew its
+ * threshold, then drops identities without feedback for {@link #IDLE_MILLIS}
+ * under the documented work and frequency bounds.
*
* @param nowMillis the selection time
* @return the number of pruned identities
*/
public int pruneIfNeeded(final long nowMillis) {
- if (stats.size() <= PRUNE_THRESHOLD) {
+ if (stats.size() <= PRUNE_THRESHOLD && !maintenancePending) {
return 0;
}
+ return maintain(nowMillis);
+ }
+
+ private synchronized int maintain(final long nowMillis) {
int before = stats.size();
- stats.entrySet().removeIf(entry -> nowMillis - entry.getValue().lastFeedbackMillis() > IDLE_MILLIS);
+ if (before > PRUNE_THRESHOLD) {
+ maintenancePending = true;
+ }
+ if (!maintenancePending) {
+ return 0;
+ }
+ lastScanCount = 0;
+ if (before > MAX_TRACKED_IDENTITIES) {
+ sweepIdle(nowMillis);
+ evictOldestBeyondCapacity();
+ maintenancePending = stats.size() > PRUNE_THRESHOLD;
+ lastMaintenanceMillis = nowMillis;
+ } else if (maintenanceDue(nowMillis)) {
+ boolean cycleCompleted = scanBudgeted(nowMillis);
+ if (cycleCompleted) {
+ // one full inspection cycle is done; stay armed while the map still
+ // outgrows the threshold or this cycle pruned something (entries may
+ // have expired after their inspection), otherwise the drain is done
+ maintenancePending = stats.size() > PRUNE_THRESHOLD || cyclePruned > 0;
+ }
+ // only an actual run advances the gate; a skipped call must not push the
+ // next eligible maintenance further into the future
+ lastMaintenanceMillis = nowMillis;
+ }
return before - stats.size();
}
+ private boolean maintenanceDue(final long nowMillis) {
+ // the sentinel forces the first run; a backward clock also re-arms the gate
+ // instead of overflowing the subtraction into a negative gap
+ return lastMaintenanceMillis == Long.MIN_VALUE || nowMillis < lastMaintenanceMillis
+ || nowMillis - lastMaintenanceMillis >= MAINTENANCE_INTERVAL_MILLIS;
+ }
+
+ private boolean scanBudgeted(final long nowMillis) {
+ if (Objects.isNull(scanCursor) || !scanCursor.hasNext()) {
+ scanCursor = stats.entrySet().iterator();
+ cyclePruned = 0;
+ }
+ int inspected = 0;
+ while (inspected < MAINTENANCE_SCAN_BUDGET && scanCursor.hasNext()) {
+ Map.Entry entry = scanCursor.next();
+ inspected++;
+ Stats observed = entry.getValue();
+ if (nowMillis - observed.lastFeedbackMillis() > IDLE_MILLIS) {
+ // conditional remove: a feedback recorded since the inspection keeps
+ // its fresh record instead of being dropped by this maintenance
+ if (stats.remove(entry.getKey(), observed)) {
+ cyclePruned++;
+ }
+ }
+ }
+ lastScanCount = inspected;
+ return !scanCursor.hasNext();
+ }
+
+ private void sweepIdle(final long nowMillis) {
+ stats.entrySet().removeIf(entry -> nowMillis - entry.getValue().lastFeedbackMillis() > IDLE_MILLIS);
+ lastScanCount = stats.size();
+ scanCursor = null;
+ }
+
+ private void evictOldestBeyondCapacity() {
+ int excess = stats.size() - MAX_TRACKED_IDENTITIES;
+ if (excess <= 0) {
+ return;
+ }
+ List> entries = new ArrayList<>(stats.entrySet());
+ entries.sort(Comparator.comparingLong(entry -> entry.getValue().lastFeedbackMillis()));
+ for (int i = 0; i < excess && i < entries.size(); i++) {
+ Map.Entry entry = entries.get(i);
+ stats.remove(entry.getKey(), entry.getValue());
+ }
+ }
+
/**
* Number of tracked identities; visible for tests.
*
@@ -177,6 +297,16 @@ Stats statsOf(final UpstreamIdentity identity) {
return stats.get(identity);
}
+ /**
+ * Entries inspected by the last maintenance run; visible for tests asserting the
+ * per-run work bound.
+ *
+ * @return the inspected entry count of the last run
+ */
+ int lastScanCount() {
+ return lastScanCount;
+ }
+
/**
* One immutable statistics snapshot.
*
@@ -184,12 +314,16 @@ Stats statsOf(final UpstreamIdentity identity) {
* double in millis so sub-millisecond increments survive
* short feedback intervals; always finite and non-negative
* @param samples number of latency-bearing observations
- * @param lastFeedbackMillis receipt time of the last feedback of any class
+ * @param lastFeedbackMillis receipt time of the last feedback of any class;
+ * activity bookkeeping for retention and pruning only
+ * @param lastSampleMillis receipt time of the last latency-bearing observation;
+ * the decay of the next sample is measured from here, so
+ * a neutral 4xx cannot reshape the next latency update
*/
- record Stats(double ewmaLatency, long samples, long lastFeedbackMillis) {
+ record Stats(double ewmaLatency, long samples, long lastFeedbackMillis, long lastSampleMillis) {
static Stats first(final long elapsedMillis, final AdaptiveOutcome outcome, final long nowMillis) {
- return new Stats(latencyOf(elapsedMillis, outcome), samplesOf(outcome), nowMillis);
+ return new Stats(latencyOf(elapsedMillis, outcome), samplesOf(outcome), nowMillis, nowMillis);
}
/**
@@ -204,12 +338,13 @@ long ewmaLatencyMillis() {
Stats next(final long elapsedMillis, final AdaptiveOutcome outcome, final long nowMillis) {
if (outcome == AdaptiveOutcome.CLIENT_ERROR) {
- // neutral: the observation says nothing about the upstream
- return new Stats(ewmaLatency, samples, nowMillis);
+ // neutral: the observation says nothing about the upstream; only the
+ // activity timestamp moves, the effective-sample timing stays intact
+ return new Stats(ewmaLatency, samples, nowMillis, lastSampleMillis);
}
long latency = latencyOf(elapsedMillis, outcome);
- double updated = samples <= 0L ? latency : smooth(latency, nowMillis - lastFeedbackMillis);
- return new Stats(updated, samples + 1L, nowMillis);
+ double updated = samples <= 0L ? latency : smooth(latency, nowMillis - lastSampleMillis);
+ return new Stats(updated, samples + 1L, nowMillis, nowMillis);
}
private double smooth(final long latency, final long sinceLastMillis) {
diff --git a/shenyu-loadbalancer/src/test/java/org/apache/shenyu/loadbalancer/spi/AdaptiveLoadBalancerTest.java b/shenyu-loadbalancer/src/test/java/org/apache/shenyu/loadbalancer/spi/AdaptiveLoadBalancerTest.java
index 8c92a9b29e97..262b8bf4832c 100644
--- a/shenyu-loadbalancer/src/test/java/org/apache/shenyu/loadbalancer/spi/AdaptiveLoadBalancerTest.java
+++ b/shenyu-loadbalancer/src/test/java/org/apache/shenyu/loadbalancer/spi/AdaptiveLoadBalancerTest.java
@@ -25,8 +25,12 @@
import org.junit.jupiter.api.Test;
import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -117,6 +121,116 @@ void clientErrorObservationsAreNeutral() {
assertTrue(after.lastFeedbackMillis() >= before.lastFeedbackMillis());
}
+ @Test
+ void clientErrorDoesNotReshapeTheNextLatencyUpdate() {
+ Upstream node = upstream("node:8080", 50);
+ AdaptiveUpstreamStats normal = new AdaptiveUpstreamStats();
+ AdaptiveUpstreamStats with4xx = new AdaptiveUpstreamStats();
+ normal.record(node.identity(), 1000L, AdaptiveOutcome.SERVER_ERROR, 0L);
+ with4xx.record(node.identity(), 1000L, AdaptiveOutcome.SERVER_ERROR, 0L);
+ with4xx.record(node.identity(), 1L, AdaptiveOutcome.CLIENT_ERROR, 999L);
+ normal.record(node.identity(), 50L, AdaptiveOutcome.SUCCESS, 1000L);
+ with4xx.record(node.identity(), 50L, AdaptiveOutcome.SUCCESS, 1000L);
+
+ assertEquals(normal.statsOf(node.identity()).ewmaLatencyMillis(),
+ with4xx.statsOf(node.identity()).ewmaLatencyMillis(),
+ "an unrelated 4xx must not change the decay of the next latency-bearing sample");
+ assertEquals(normal.statsOf(node.identity()).samples(), with4xx.statsOf(node.identity()).samples());
+ }
+
+ @Test
+ void manyClientErrorsLeaveSubsequentUpdatesEquivalent() {
+ Upstream node = upstream("node:8080", 50);
+ AdaptiveUpstreamStats normal = new AdaptiveUpstreamStats();
+ AdaptiveUpstreamStats with4xx = new AdaptiveUpstreamStats();
+ for (int time = 0; time <= 5_000; time += 100) {
+ normal.record(node.identity(), 50L, AdaptiveOutcome.SUCCESS, time);
+ with4xx.record(node.identity(), 50L, AdaptiveOutcome.SUCCESS, time);
+ for (int i = 1; i <= 5; i++) {
+ with4xx.record(node.identity(), 1L, AdaptiveOutcome.CLIENT_ERROR, time + i);
+ }
+ }
+
+ assertEquals(normal.statsOf(node.identity()).ewmaLatencyMillis(),
+ with4xx.statsOf(node.identity()).ewmaLatencyMillis(),
+ "any number of interleaved 4xx observations must leave the latency path equivalent");
+ assertEquals(normal.statsOf(node.identity()).samples(), with4xx.statsOf(node.identity()).samples());
+ }
+
+ @Test
+ void clientErrorAloneNeverWarmsAColdTarget() {
+ Upstream node = upstream("cold:8080", 50);
+ Upstream warm = upstream("warm:8080", 50);
+ feed(balancer, warm, AdaptiveOutcome.SUCCESS, 10L, 20);
+ for (int i = 0; i < 20; i++) {
+ balancer.onFeedback(node, 1L, AdaptiveOutcome.CLIENT_ERROR);
+ }
+
+ AdaptiveUpstreamStats.Stats stats = balancer.stats().statsOf(node.identity());
+ assertEquals(0L, stats.samples(), "a 4xx must never count as a latency sample");
+ assertTrue(balancer.stats().score(node.identity(), 1L, 50).isEmpty(),
+ "a target seen only through 4xx must stay cold");
+ assertFalse(balancer.stats().bothAdaptive(node.identity(), warm.identity()));
+ }
+
+ @Test
+ void identityFirstSeenThroughClientErrorStartsFromTheFirstRealSample() {
+ AdaptiveUpstreamStats stats = new AdaptiveUpstreamStats();
+ UpstreamIdentity identity = upstream("node:8080", 50).identity();
+ stats.record(identity, 1L, AdaptiveOutcome.CLIENT_ERROR, 0L);
+ stats.record(identity, 50L, AdaptiveOutcome.SUCCESS, 1000L);
+
+ AdaptiveUpstreamStats.Stats record = stats.statsOf(identity);
+ assertEquals(1L, record.samples());
+ assertEquals(50L, record.ewmaLatencyMillis(),
+ "the first real sample must be taken as-is, not decayed from the 4xx timestamp");
+ }
+
+ @Test
+ void clientErrorActivityStillCountsForRetention() {
+ AdaptiveUpstreamStats stats = new AdaptiveUpstreamStats();
+ UpstreamIdentity retained = upstream("retained:8080", 50).identity();
+ stats.record(retained, 10L, AdaptiveOutcome.SUCCESS, 0L);
+ stats.record(retained, 1L, AdaptiveOutcome.CLIENT_ERROR, AdaptiveUpstreamStats.IDLE_MILLIS);
+ for (int i = 0; i < AdaptiveUpstreamStats.PRUNE_THRESHOLD + 10; i++) {
+ stats.record(upstream("filler-" + i + ":8080", 50).identity(), 10L, AdaptiveOutcome.SUCCESS, 0L);
+ }
+
+ stats.pruneIfNeeded(AdaptiveUpstreamStats.IDLE_MILLIS + 1L);
+ assertNotNull(stats.statsOf(retained),
+ "a recent 4xx keeps the identity alive for retention even without a new latency sample");
+ }
+
+ @Test
+ void concurrentFeedbackKeepsSampleAccountingConsistent() throws Exception {
+ AdaptiveUpstreamStats stats = new AdaptiveUpstreamStats();
+ UpstreamIdentity identity = upstream("node:8080", 50).identity();
+ int workers = 4;
+ int perWorker = 250;
+ ExecutorService pool = Executors.newFixedThreadPool(workers);
+ try {
+ for (int w = 0; w < workers; w++) {
+ final int worker = w;
+ pool.submit(() -> {
+ for (int i = 0; i < perWorker; i++) {
+ long now = (long) worker * perWorker + i;
+ stats.record(identity, 50L, AdaptiveOutcome.SUCCESS, now);
+ stats.record(identity, 1L, AdaptiveOutcome.CLIENT_ERROR, now);
+ }
+ });
+ }
+ pool.shutdown();
+ assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS));
+ } finally {
+ pool.shutdownNow();
+ }
+
+ AdaptiveUpstreamStats.Stats record = stats.statsOf(identity);
+ assertEquals((long) workers * perWorker, record.samples(),
+ "only latency-bearing observations may count, regardless of interleaving");
+ assertTrue(Double.isFinite(record.ewmaLatency()) && record.ewmaLatency() >= 0.0);
+ }
+
@Test
void transportFailureEntersWithTheFailureFloorWithoutARealMeasurement() {
Upstream node = upstream("node:8080", 50);
@@ -267,11 +381,124 @@ void pruneDropsIdleIdentitiesOnceTheMapOutgrowsItsThreshold() {
"below the idle bound nothing may be pruned");
assertEquals(AdaptiveUpstreamStats.PRUNE_THRESHOLD + 10, stats.size());
- int pruned = stats.pruneIfNeeded(AdaptiveUpstreamStats.IDLE_MILLIS + 1L);
+ // maintenance is budgeted: each eligible run inspects at most the scan budget,
+ // so draining the expired set takes several windows instead of one full sweep
+ long now = AdaptiveUpstreamStats.IDLE_MILLIS + 1L;
+ int pruned = 0;
+ while (stats.size() > 0) {
+ pruned += stats.pruneIfNeeded(now);
+ assertTrue(stats.lastScanCount() <= AdaptiveUpstreamStats.MAINTENANCE_SCAN_BUDGET,
+ "one maintenance run must never inspect more than the scan budget");
+ now += AdaptiveUpstreamStats.MAINTENANCE_INTERVAL_MILLIS;
+ }
assertEquals(AdaptiveUpstreamStats.PRUNE_THRESHOLD + 10, pruned);
assertEquals(0, stats.size());
}
+ @Test
+ void singletonTrafficStillDrivesCleanup() {
+ for (int i = 0; i < 1000; i++) {
+ Upstream old = upstream("old-" + i + ":8080", 50);
+ balancer.stats().record(old.identity(), 1L, AdaptiveOutcome.SUCCESS, 0L);
+ }
+ Upstream live = upstream("live:8080", 50);
+ final long before = live.getInflight().get();
+
+ // the singleton fast path bypasses doSelect, so the selection itself must run
+ // maintenance; the epoch-zero feedback is already expired against the real clock
+ Upstream picked = balancer.select(List.of(live), new LoadBalanceData());
+ assertEquals(live, picked);
+ assertTrue(balancer.stats().lastScanCount() > 0,
+ "a singleton selection must drive maintenance, not skip it");
+ assertTrue(balancer.stats().size() < 1000, "the singleton selection must prune expired identities");
+ assertEquals(before + 1L, live.getInflight().get(),
+ "cleanup must not disturb the singleton inflight reservation pairing");
+
+ // deterministic drain across maintenance windows, as repeated discovery
+ // replacement would see under sustained singleton traffic
+ long now = AdaptiveUpstreamStats.IDLE_MILLIS + 1L;
+ while (balancer.stats().size() > 0) {
+ balancer.stats().pruneIfNeeded(now);
+ now += AdaptiveUpstreamStats.MAINTENANCE_INTERVAL_MILLIS;
+ }
+ assertEquals(0, balancer.stats().size(), "removed identities must eventually be reclaimed");
+ }
+
+ @Test
+ void hotSetAboveThresholdDoesNotSweepPerSelection() {
+ AdaptiveUpstreamStats stats = new AdaptiveUpstreamStats();
+ long now = 1_000_000L;
+ for (int i = 0; i < AdaptiveUpstreamStats.PRUNE_THRESHOLD + 200; i++) {
+ stats.record(upstream("hot-" + i + ":8080", 50).identity(), 10L, AdaptiveOutcome.SUCCESS, now);
+ }
+
+ assertEquals(0, stats.pruneIfNeeded(now), "the first run finds nothing expired");
+ for (int i = 1; i < 100; i++) {
+ assertEquals(0, stats.pruneIfNeeded(now + i),
+ "selections inside the maintenance interval must pay no scan at all");
+ assertEquals(0, stats.lastScanCount());
+ }
+ assertEquals(AdaptiveUpstreamStats.PRUNE_THRESHOLD + 200, stats.size(),
+ "active history must be preserved while nothing is expired");
+
+ assertEquals(0, stats.pruneIfNeeded(now + AdaptiveUpstreamStats.MAINTENANCE_INTERVAL_MILLIS));
+ assertTrue(stats.lastScanCount() <= AdaptiveUpstreamStats.MAINTENANCE_SCAN_BUDGET,
+ "even an eligible run stays within the per-call work budget");
+ }
+
+ @Test
+ void hardCapacityEvictsOldestActivityWhenNothingIsIdle() {
+ AdaptiveUpstreamStats stats = new AdaptiveUpstreamStats();
+ int total = AdaptiveUpstreamStats.MAX_TRACKED_IDENTITIES + 100;
+ for (int i = 0; i < total; i++) {
+ stats.record(upstream("churn-" + i + ":8080", 50).identity(), 10L, AdaptiveOutcome.SUCCESS, i);
+ }
+
+ // nothing is idle at this timestamp, so only the capacity eviction may act
+ stats.pruneIfNeeded(total + 1000L);
+
+ assertEquals(AdaptiveUpstreamStats.MAX_TRACKED_IDENTITIES, stats.size(),
+ "retained state must stay bounded even when every identity is active");
+ assertNotNull(stats.statsOf(upstream("churn-" + (total - 1) + ":8080", 50).identity()),
+ "the most recently active identity must survive the capacity eviction");
+ assertNull(stats.statsOf(upstream("churn-0:8080", 50).identity()),
+ "the oldest activity must be evicted first");
+ }
+
+ @Test
+ void concurrentFeedbackSurvivesMaintenance() throws Exception {
+ AdaptiveUpstreamStats stats = new AdaptiveUpstreamStats();
+ UpstreamIdentity target = upstream("target:8080", 50).identity();
+ stats.record(target, 10L, AdaptiveOutcome.SUCCESS, 0L);
+ for (int i = 0; i < AdaptiveUpstreamStats.PRUNE_THRESHOLD + 10; i++) {
+ stats.record(upstream("filler-" + i + ":8080", 50).identity(), 10L, AdaptiveOutcome.SUCCESS, 0L);
+ }
+
+ ExecutorService pool = Executors.newFixedThreadPool(2);
+ try {
+ pool.submit(() -> {
+ for (int i = 0; i < 2_000; i++) {
+ stats.record(target, 10L, AdaptiveOutcome.SUCCESS, AdaptiveUpstreamStats.IDLE_MILLIS + 1L + i);
+ }
+ });
+ pool.submit(() -> {
+ long now = AdaptiveUpstreamStats.IDLE_MILLIS + 1L;
+ for (int i = 0; i < 50; i++) {
+ stats.pruneIfNeeded(now);
+ now += AdaptiveUpstreamStats.MAINTENANCE_INTERVAL_MILLIS;
+ }
+ });
+ pool.shutdown();
+ assertTrue(pool.awaitTermination(30, TimeUnit.SECONDS));
+ } finally {
+ pool.shutdownNow();
+ }
+
+ assertNotNull(stats.statsOf(target),
+ "a concurrently refreshed record must not be dropped by maintenance");
+ assertTrue(stats.statsOf(target).lastFeedbackMillis() >= AdaptiveUpstreamStats.IDLE_MILLIS + 1L);
+ }
+
@Test
void rejectedCandidatesWithoutIdentityFailSoftly() {
balancer.onFeedback(null, 10L, AdaptiveOutcome.SUCCESS);