Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,28 @@ public Upstream select(final List<Upstream> upstreamList, final LoadBalanceData
}

protected int getWeight(final Upstream upstream) {
return getWeight(upstream, System.currentTimeMillis());
}

/**
* Warm-up adjusted weight sampled at a caller-provided instant, so one selection
* can compare every candidate on the same weight scale even when the millisecond
* clock ticks mid-comparison.
*
* @param upstream the candidate
* @param nowMillis the selection time
* @return the effective weight
*/
protected int getWeight(final Upstream upstream, final long nowMillis) {
if (!upstream.isStatus()) {
return 0;
}
return getWeight(upstream.getTimestamp(), upstream.getWarmup(), upstream.getWeight());
return getWeight(upstream.getTimestamp(), upstream.getWarmup(), upstream.getWeight(), nowMillis);
}

private int getWeight(final long timestamp, final int warmup, final int weight) {
private int getWeight(final long timestamp, final int warmup, final int weight, final long nowMillis) {
if (weight > 0 && timestamp > 0) {
long uptime = System.currentTimeMillis() - timestamp;
long uptime = nowMillis - timestamp;
if (uptime > 0 && uptime < warmup) {
return calculateWarmupWeight((int) uptime, warmup, weight);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ AdaptiveUpstreamStats stats() {

@Override
public Upstream select(final List<Upstream> 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
Expand All @@ -97,11 +101,10 @@ public Upstream select(final List<Upstream> upstreamList, final LoadBalanceData
@Override
protected Upstream doSelect(final List<Upstream> upstreamList, final LoadBalanceData data) {
long now = System.currentTimeMillis();
stats.pruneIfNeeded(now);
Upstream[] upstreams = pickTwoUpstreams(upstreamList);
Upstream picked;
Upstream unpicked;
if (compare(upstreams[0], upstreams[1]) > 0) {
if (compare(upstreams[0], upstreams[1], now) > 0) {
picked = upstreams[1];
unpicked = upstreams[0];
} else {
Expand All @@ -124,21 +127,24 @@ protected Upstream doSelect(final List<Upstream> upstreamList, final LoadBalance

/**
* Compare two candidates: adaptive scores when both are warm, the p2c load formula
* for a cold pair (the scales must never be mixed inside one comparison).
* for a cold pair (the scales must never be mixed inside one comparison). Both
* weights are sampled at the single selection instant, so a millisecond tick
* mid-comparison cannot score the pair on two different warm-up scales.
*
* @param first the first candidate
* @param second the second candidate
* @param nowMillis the selection time
* @return negative/zero/positive following the first candidate's advantage
*/
private long compare(final Upstream first, final Upstream second) {
private long compare(final Upstream first, final Upstream second, final long nowMillis) {
if (stats.bothAdaptive(first.identity(), second.identity())) {
return Long.compare(score(first), score(second));
return Long.compare(score(first, nowMillis), score(second, nowMillis));
}
return Long.compare(coldStartComparison.load(first), coldStartComparison.load(second));
}

private long score(final Upstream upstream) {
OptionalLong adaptive = stats.score(upstream.identity(), upstream.getInflight().get(), getWeight(upstream));
private long score(final Upstream upstream, final long nowMillis) {
OptionalLong adaptive = stats.score(upstream.identity(), upstream.getInflight().get(), getWeight(upstream, nowMillis));
// bothAdaptive already guaranteed warm statistics; the fallback keeps the
// comparison total if a concurrent prune removed the entry between the checks
return adaptive.orElseGet(() -> coldStartComparison.load(upstream));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -29,19 +33,36 @@
*
* <p>Each upstream identity holds one immutable statistics record that is replaced
* atomically on every feedback. The record carries a smoothed latency in the same
* EWMA family as the p2c trigger. Feedback classification follows
* EWMA family as the p2c trigger. The smoothing keeps double precision internally
* (in milliseconds): truncating every update to whole milliseconds would discard
* sub-millisecond increments at short feedback intervals and could pin the estimate
* at its old value forever. Rounding happens only where a long leaves the record:
* {@link Stats#ewmaLatencyMillis()} is the single rounded exit, and {@link #score}
* scores that rounded value so routing stays identical to whole-millisecond
* estimates. Feedback classification follows
* {@link AdaptiveOutcome}: a 4xx is neutral (the observation says nothing about the
* upstream), while a 5xx or a transport failure enters the smoothing as a synthetic
* 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.</p>
* 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.</p>
*
* <p>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.</p>
* <p>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.</p>
*/
public class AdaptiveUpstreamStats {

Expand Down Expand Up @@ -73,8 +94,48 @@ 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;

/**
* Minimum decay interval in millis applied to observations whose gap is zero or
* negative (same-timestamp completions, out-of-order feedback or a clock
* regression): a zero gap would give the new sample zero weight and discard it
* permanently, so such completions are blended with at least this much evidence.
* Decay is applied per sample, so N completions sharing one timestamp advance the
* estimate by N minimum intervals; the smoothing is intentionally rate-dependent
* in that regime.
*/
static final long MIN_DECAY_INTERVAL_MILLIS = 1L;

private final Map<UpstreamIdentity, Stats> stats = new ConcurrentHashMap<>();

private volatile boolean maintenancePending;

private long lastMaintenanceMillis = Long.MIN_VALUE;

private Iterator<Map.Entry<UpstreamIdentity, Stats>> 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.
Expand Down Expand Up @@ -130,22 +191,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<UpstreamIdentity, Stats> 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<Map.Entry<UpstreamIdentity, Stats>> 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<UpstreamIdentity, Stats> entry = entries.get(i);
stats.remove(entry.getKey(), entry.getValue());
}
}

/**
* Number of tracked identities; visible for tests.
*
Expand All @@ -165,32 +302,64 @@ 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.
*
* @param ewmaLatencyMillis smoothed latency of latency-bearing attempts
* @param ewmaLatency smoothed latency of latency-bearing attempts, kept as a
* 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(long ewmaLatencyMillis, 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);
}

/**
* The smoothed latency rounded to whole millis; the internal double keeps
* the unrounded estimate for the next update, while scoring uses this
* rounded value so sub-millisecond residue cannot shift routing.
*
* @return the smoothed latency in millis, rounded to the nearest long
*/
long ewmaLatencyMillis() {
return Math.round(ewmaLatency);
}

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(ewmaLatencyMillis, 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);
long 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 long smooth(final long latency, final long sinceLastMillis) {
double w = Math.exp((double) -Math.max(sinceLastMillis, 0L) / (double) EWMA_WINDOW_MILLIS);
return (long) ((double) ewmaLatencyMillis * w + (double) latency * (1.0 - w));
private double smooth(final long latency, final long sinceLastMillis) {
// a zero or negative gap (same-timestamp completion, out-of-order feedback
// or clock regression) carries no elapsed-time evidence: blend with the
// minimum interval instead of discarding the sample or amplifying it
long interval = sinceLastMillis <= 0L ? MIN_DECAY_INTERVAL_MILLIS : sinceLastMillis;
double w = Math.exp((double) -interval / (double) EWMA_WINDOW_MILLIS);
return ewmaLatency * w + (double) latency * (1.0 - w);
}

private static long latencyOf(final long elapsedMillis, final AdaptiveOutcome outcome) {
Expand Down
Loading
Loading