← Back to Pull requests

fix(loadbalancer): track inflight for shortestResponse (#7973) #7987

Merged
markjoin123 merged 9 files (398 lines) on Nov 13, 2026 06:52 UTC
View on GitHub
markjoin123 markjoin123 commented on Oct 22, 2026 12:31 UTC
Author

Fixes #7973

shortestResponse now accounts for outstanding requests. Selection increments inflight, and Divide decrements it exactly once on success, error, or cancellation, without going negative. A historically fast upstream no longer keeps every request while its queue grows. A half-open probe that skips the balancer increments inflight as well, so the release stays paired.

Tests:

  • ShortestResponseLoadBalancerTest: the issue's repro (fast avg 10 vs slow avg 100, no completions between selections) no longer sends all requests to the fast upstream; each selection increments inflight once.

  • DividePluginTest: after success, error and cancel, inflight returns to its baseline; a zero count stays zero.

  • Checkstyle and Apache RAT pass on the affected modules.
  • Make sure that:

  • You have read the contribution guidelines.

  • You submit test cases (unit or integration tests) that back your changes.

  • Your local test passed ./mvnw clean install -Dmaven.javadoc.skip=true.
  • Diff: 398 lines (+369 / -29) across 9 files Reviewer: Aias00 Review duration: 31340m
    All Vouch review confidence checks passed
    Residual risk 0.13 = Change Risk (0.56) × (1 − Review Confidence (0.76)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.56 · 398 lines diff across 9 files
    0.56
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.57 · 3 substantive comment(s)
    0.57
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    76%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.358
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    9 items
    Aias00 Aias00 requested changes on Oct 23, 2026 01:41 UTC
    Changes Requested Reviewer

    Verdict: the accounting is right on the direct path, but the failover path leaks - please extend the fix

    The core of this change is correct and the two increments do not double count:

  • ShortestResponseLoadBalancer.doSelect increments for the normal selection path;

  • DividePlugin.forwardSelected increments only in the candidates.isProbe() branch, which bypasses LoadbalancerUtils and therefore doSelect. That is the same split P2C already relies on (increment inside P2cLoadBalancer.doSelect, plus a separate increment for the half-open probe), so the shape is consistent.

  • releaseShortestResponseInflight using updateAndGet(current -> current > 0 ? current - 1 : 0) is a reasonable floor guard, and the test covers success, error and cancellation plus the already-zero case.
  • Blocking: retries re-select through the load balancer and leak an increment

    DefaultRetryStrategy.resend picks the standby upstream through LoadbalancerUtils, so with shortestResponse it now runs ShortestResponseLoadBalancer.doSelect and increments that upstream. Divide's doFinally only holds the initially selected upstream, so:

  • request fails -> failover selects standby -> standby.inflight++

  • the response terminates -> doFinally decrements the original upstream
  • standby never gets its decrement back. Each failed-and-retried request leaks +1 on the standby, which permanently inflates succeededAverageElapsed * inflight and eventually drives all traffic away from a healthy upstream. This is exactly the defect #7982 fixes for P2C, and that PR's guard is scoped to P2C only:

    if (LoadBalanceEnum.P2C.getName().equals(loadBalance)) {
        retryResponse = retryResponse.doFinally(signalType -> upstream.getInflight().decrementAndGet());
    }
    

    Please do one of:

    1. add the same release for LoadBalanceEnum.SHORTEST_RESPONSE in DefaultRetryStrategy (mirroring #7982, including its RetryStrategyTest case), and note in both PRs that the guard must cover both load balancers; or
    2. if you would rather land the retry part separately, say so explicitly in the description and keep this PR's scope to the non-retry path - but then the leak exists in master as soon as this merges, so option 1 is preferred.

    Non-blocking

  • ShortestResponseLoadBalancer still inherits AbstractLoadBalancer.select, which short-circuits for a single upstream and never calls doSelect. A single-upstream selector therefore never counts inflight, so shortestResponse silently degrades to "always pick it" (harmless in that case, but inconsistent with #7980, which added an explicit select override on P2cLoadBalancer for exactly this reason). Consider the same override here for symmetry.

  • The new test's last assertion, assertEquals(100, fast.getInflight().get() + slow.getInflight().get() - 2), relies on the two set(1) baselines. It works, but fast.getInflight().get() + slow.getInflight().get() compared against 2 + 100 would read more obviously.
  • markjoin123 markjoin123 commented on Oct 23, 2026 05:19 UTC
    Author

    Thanks for the review @Aias00.

    Blocking: #7982 isn't on master yet (it was merged into fix/p2c-singleton-inflight), so there was no P2C guard to extend. DefaultRetryStrategy now releases the failover standby's inflight once in doFinally for shortestResponse (success, error and cancellation), and the count can't go below zero. The standby was already incremented during selection, so this path doesn't increment again. P2C is left to #7982; when it lands on master, please extend this same guard to cover both rather than adding a second doFinally. RetryStrategyTest covers a multi-candidate retry and a single standby.

    Non-blocking: ShortestResponseLoadBalancer.select now counts inflight for a single-upstream list, same as the P2C override in #7980. The traffic test now compares fast.getInflight().get() + slow.getInflight().get() with 2 + 100.

    Branch rebased onto current master. Tests: ShortestResponseLoadBalancerTest 4 passed, DividePluginTest 15 passed, RetryStrategyTest 27 passed; checkstyle and RAT clean.

    Aias00 Aias00 commented on Oct 26, 2026 09:50 UTC
    Reviewer

    The inflight accounting is correctly paired. I traced all four paths:

  • Normal selection (>1 candidate): ShortestResponseLoadBalancer.doSelect returns through trackInflight(...) on every branch, so selection reserves exactly once.

  • Single candidate: AbstractLoadBalancer.select returns before doSelect, so the select override increments for that case only — guarded by upstreamList.size() == 1, so there is no double count when doSelect did run.

  • Half-open probe: DividePlugin.forwardSelected takes breakeredUpstreamList.get(0) directly without calling the load balancer, so the new SHORTEST_RESPONSE increment there is needed and is not a duplicate (it sits inside the candidates.isProbe() branch, not the normal path).

  • Sticky affinity hit: resolveWithAffinity skips selection, so the added increment is again the only reservation.
  • Release side matches: forwardWithCircuitBreaker decrements once in doFinally, and DefaultRetryStrategy releases the standby attempt it selected, with updateAndGet(current -> current > 0 ? current - 1 : 0) preventing the counter from going negative if a signal fires twice.

    This is consistent with the model already merged for P2C in #7980, and the SHORTEST_RESPONSE.equals(...) normalisation on the release branch is a nice touch.

    LGTM.

    Aias00 Aias00 commented on code on Oct 27, 2026 08:49 UTC
    Code Review
    shenyu-loadbalancer/src/main/java/org/apache/shenyu/loadbalancer/spi/ShortestResponseLoadBalancer.java:1
    @@ -35,6 +36,17 @@
     @Join
     public class ShortestResponseLoadBalancer extends AbstractLoadBalancer {
     
    +    @Override
    +    public Upstream select(final List<Upstream> upstreamList, final LoadBalanceData data) {
    +        Upstream picked = super.select(upstreamList, data);
    +        // A single candidate returns before doSelect, so the inflight increment there is skipped
    +        // while Divide still releases it. Count the selection here. See #7980.
    +        if (Objects.nonNull(picked) && upstreamList.size() == 1) {
    +            picked.getInflight().incrementAndGet();

    [P2] Pair the new selection reservation on the WebSocket path too

    The shared shortestResponse balancer now reserves inflight on every selection, but the corresponding release is added only to Divide and HTTP retry paths. WebSocketPlugin also uses this balancer through LoadbalancerUtils.getForExchange; its lifecycle wrapper currently applies only to leastActivity, so shortestResponse reservations are never released there, including after handshake termination.

    I reproduced this with this PR's ShortestResponseLoadBalancer and the existing WebSocketPlugin test fixture, with the WebSocket service completing each handshake: three additional completed handshakes increased inflight by three instead of returning to the baseline. This leaves stale counts on cached upstreams, including if the selector later switches to leastActivity.

    Please pair the reservation with the WebSocket lifecycle, including failed upgrades and session termination, or keep the reservation scoped to callers that implement the matching release. Add a WebSocket regression test for shortestResponse.

    Aias00 Aias00 commented on Oct 27, 2026 08:49 UTC
    Reviewer

    Code review of commit 5a5372c15ff7aa174996f561a3c08514e8893161.

    [P2] Pair the new selection reservation on the WebSocket path too

    The attached finding was reproduced locally with the PR code and the relevant runtime handler/processor. This is targeted validation, not a full PR test-suite run.

    markjoin123 markjoin123 commented on Oct 27, 2026 13:07 UTC
    Author

    Thanks @Aias00, good catch. Addressed in 94cc5dbcceaa495041b0316674599b13a01efc56.

    The WebSocket path now uses the same session lifecycle wrapper (InflightWebSocketHandler) for shortestResponse as for leastActive. Since ShortestResponseLoadBalancer already reserves inflight at selection, the wrapper does not reserve again for it; it only releases that reservation exactly once:

  • when the handshake completes or fails without a session being started, or

  • when the session ends (normal completion, failure, or cancellation).
  • An open session keeps the reservation until it terminates. leastActive behaviour is unchanged.

    WebSocketPluginTest now checks that three completed handshakes and a failed handshake return inflight to baseline, and that an open session holds the reservation until cancel/complete/error (11 tests pass, checkstyle clean).

    Aias00 Aias00 commented on Oct 30, 2026 04:34 UTC
    Reviewer

    The shortestResponse reservation is paired with release on HTTP, retry and WebSocket lifecycle paths. The earlier WebSocket leak finding is addressed by the inflight lifecycle handler, including termination/cancellation. No remaining actionable finding.

    Validation: 72 focused load-balancer/HTTP/Divide tests passed; an additional WebSocket reactor run passed 15 tests (including 4 repeated load-balancer tests). No GitHub check rollup was available at the initial snapshot; required CI remains a merge gate. Apache RAT passed locally. Scope: source review and targeted verification; full integration/e2e suites were not run locally for this review.

    Aias00 Aias00 approved these changes on Nov 11, 2026 01:23 UTC
    Approved Reviewer

    Stream Agent analysis

    PR #7987 fixes inflight tracking for the shortestResponse load balancer algorithm. The bug was that shortestResponse did not increment inflight on selection, causing a fast upstream to accumulate all requests while its queue grew. The fix adds inflight increments at all selection points (normal selection, single-candidate fast path, half-open probes, sticky-session binding hits, and hash-based picks) and ensures exactly-once release via a guarded decrement that never goes negative. WebSocket upgrades now track the reservation through a state machine so the handshake and the long-lived session share one paired reservation.

    Evidence


  • Full diff (35,635 chars) read across all pages until has_more=false at offset 35635.

  • CI passed: policy (7987), discover, and issue-spec-policy all completed successfully.

  • Key fix verified: ShortestResponseLoadBalancer.select() now increments inflight for single candidate (line 45), DividePlugin adds reserveProbe() for half-open probes and increments for binding hits, releaseShortestResponseInflight() uses updateAndGet to prevent negative counts (line 552), WebSocketPlugin uses AtomicInteger state machine for exactly-once release.
  • Recommended next steps

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

    Task: 044e8695-4ecb-4580-818b-87779b78db94 · Commit: 8f2faf03966af981f89c87deaf10959aef70a6f0

    <!-- stream-agent-review:047deceeb2bf58fce03ec712b0ec8ae1378f5701c05d87f2c87ce1d5b2526bda -->

    Review verdict: PASS


    Complete diff coverage, all CI checks passed, and no concrete blocking defects. The implementation correctly addresses issue #7973 by ensuring shortestResponse tracks outstanding requests at every selection entry point and releases exactly once on all terminal paths (success, error, cancellation).

    Publication: APPROVE (EXPLICIT_PASS)

    Reviewers
    Assignees
    markjoin123 markjoin123
    Labels
    risk: low confidence: 76.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 55.5% (MEDIUM) · Higher = larger blast radius
    55.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 76.2% · Lower = rushed or shallow review
    76.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 13.2% · Safe to merge
    13.2%
    Repository