• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

grpc / grpc-java / #20365

27 Jul 2026 06:04AM UTC coverage: 89.199% (+0.07%) from 89.125%
#20365

push

github

web-flow
core: Implement LB Delay Observability (Proposal A121) (#12807)

This PR implements **Attempt-Level RPC Delay Observability** across the core channel transport, built-in load balancers, xDS policies, and the OpenTelemetry telemetry plugin, aligned with [gRPC Proposal A121](https://github.com/grpc/proposal/pull/556).

38276 of 42911 relevant lines covered (89.2%)

0.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.63
/../xds/src/main/java/io/grpc/xds/WeightedRoundRobinLoadBalancer.java
1
/*
2
 * Copyright 2023 The gRPC Authors
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16

17
package io.grpc.xds;
18

19
import static com.google.common.base.Preconditions.checkArgument;
20
import static com.google.common.base.Preconditions.checkNotNull;
21

22
import com.google.common.annotations.VisibleForTesting;
23
import com.google.common.base.MoreObjects;
24
import com.google.common.base.Preconditions;
25
import com.google.common.collect.ImmutableList;
26
import com.google.common.collect.Lists;
27
import io.grpc.ConnectivityState;
28
import io.grpc.ConnectivityStateInfo;
29
import io.grpc.Deadline.Ticker;
30
import io.grpc.DoubleHistogramMetricInstrument;
31
import io.grpc.EquivalentAddressGroup;
32
import io.grpc.LoadBalancer;
33
import io.grpc.LoadBalancerProvider;
34
import io.grpc.LongCounterMetricInstrument;
35
import io.grpc.MetricInstrumentRegistry;
36
import io.grpc.NameResolver;
37
import io.grpc.Status;
38
import io.grpc.SynchronizationContext;
39
import io.grpc.SynchronizationContext.ScheduledHandle;
40
import io.grpc.services.MetricReport;
41
import io.grpc.util.ForwardingSubchannel;
42
import io.grpc.util.MultiChildLoadBalancer;
43
import io.grpc.xds.internal.MetricReportUtils;
44
import io.grpc.xds.internal.MetricReportUtils.ParsedMetricName;
45
import io.grpc.xds.orca.OrcaOobUtil;
46
import io.grpc.xds.orca.OrcaOobUtil.OrcaOobReportListener;
47
import io.grpc.xds.orca.OrcaPerRequestUtil;
48
import io.grpc.xds.orca.OrcaPerRequestUtil.OrcaPerRequestReportListener;
49
import java.util.ArrayList;
50
import java.util.Collection;
51
import java.util.HashSet;
52
import java.util.List;
53
import java.util.Objects;
54
import java.util.OptionalDouble;
55
import java.util.Random;
56
import java.util.Set;
57
import java.util.concurrent.ScheduledExecutorService;
58
import java.util.concurrent.TimeUnit;
59
import java.util.concurrent.atomic.AtomicInteger;
60
import java.util.logging.Level;
61
import java.util.logging.Logger;
62

63
/**
64
 * A {@link LoadBalancer} that provides weighted-round-robin load-balancing over the
65
 * {@link EquivalentAddressGroup}s from the {@link NameResolver}. The subchannel weights are
66
 * determined by backend metrics using ORCA.
67
 * To use WRR, users may configure through channel serviceConfig. Example config:
68
 * <pre> {@code
69
 *       String wrrConfig = "{\"loadBalancingConfig\":" +
70
 *           "[{\"weighted_round_robin\":{\"enableOobLoadReport\":true, " +
71
 *           "\"blackoutPeriod\":\"10s\"," +
72
 *           "\"oobReportingPeriod\":\"10s\"," +
73
 *           "\"weightExpirationPeriod\":\"180s\"," +
74
 *           "\"errorUtilizationPenalty\":\"1.0\"," +
75
 *           "\"weightUpdatePeriod\":\"1s\"}}]}";
76
 *        serviceConfig = (Map<String, ?>) JsonParser.parse(wrrConfig);
77
 *        channel = ManagedChannelBuilder.forTarget("test:///lb.test.grpc.io")
78
 *            .defaultServiceConfig(serviceConfig)
79
 *            .build();
80
 *  }
81
 *  </pre>
82
 *  Users may also configure through xDS control plane via custom lb policy. But that is much more
83
 *  complex to set up. Example config:
84
 *  <pre>
85
 *  localityLbPolicies:
86
 *   - customPolicy:
87
 *       name: weighted_round_robin
88
 *       data: '{ "enableOobLoadReport": true }'
89
 *  </pre>
90
 *  See related documentation: https://cloud.google.com/service-mesh/legacy/load-balancing-apis/proxyless-configure-advanced-traffic-management#custom-lb-config
91
 */
92
final class WeightedRoundRobinLoadBalancer extends MultiChildLoadBalancer {
93

94
  private static final LongCounterMetricInstrument RR_FALLBACK_COUNTER;
95
  private static final LongCounterMetricInstrument ENDPOINT_WEIGHT_NOT_YET_USEABLE_COUNTER;
96
  private static final LongCounterMetricInstrument ENDPOINT_WEIGHT_STALE_COUNTER;
97
  private static final DoubleHistogramMetricInstrument ENDPOINT_WEIGHTS_HISTOGRAM;
98
  private static final Logger log = Logger.getLogger(
1✔
99
      WeightedRoundRobinLoadBalancer.class.getName());
1✔
100
  private WeightedRoundRobinLoadBalancerConfig config;
101
  private final SynchronizationContext syncContext;
102
  private final ScheduledExecutorService timeService;
103
  private ScheduledHandle weightUpdateTimer;
104
  private final Runnable updateWeightTask;
105
  private final AtomicInteger sequence;
106
  private final long infTime;
107
  private final Ticker ticker;
108
  private String locality = "";
1✔
109
  private String backendService = "";
1✔
110
  private SubchannelPicker currentPicker = new FixedResultPicker(
1✔
111
      PickResult.withNoResult("connecting", "weighted_round_robin: initializing"));
1✔
112

113
  // The metric instruments are only registered once and shared by all instances of this LB.
114
  static {
115
    MetricInstrumentRegistry metricInstrumentRegistry
116
        = MetricInstrumentRegistry.getDefaultRegistry();
1✔
117
    RR_FALLBACK_COUNTER = metricInstrumentRegistry.registerLongCounter(
1✔
118
        "grpc.lb.wrr.rr_fallback",
119
        "EXPERIMENTAL. Number of scheduler updates in which there were not enough endpoints "
120
            + "with valid weight, which caused the WRR policy to fall back to RR behavior",
121
        "{update}",
122
        Lists.newArrayList("grpc.target"),
1✔
123
        Lists.newArrayList("grpc.lb.locality", "grpc.lb.backend_service"),
1✔
124
        false);
125
    ENDPOINT_WEIGHT_NOT_YET_USEABLE_COUNTER = metricInstrumentRegistry.registerLongCounter(
1✔
126
        "grpc.lb.wrr.endpoint_weight_not_yet_usable",
127
        "EXPERIMENTAL. Number of endpoints from each scheduler update that don't yet have usable "
128
            + "weight information",
129
        "{endpoint}",
130
        Lists.newArrayList("grpc.target"),
1✔
131
        Lists.newArrayList("grpc.lb.locality", "grpc.lb.backend_service"),
1✔
132
        false);
133
    ENDPOINT_WEIGHT_STALE_COUNTER = metricInstrumentRegistry.registerLongCounter(
1✔
134
        "grpc.lb.wrr.endpoint_weight_stale",
135
        "EXPERIMENTAL. Number of endpoints from each scheduler update whose latest weight is "
136
            + "older than the expiration period",
137
        "{endpoint}",
138
        Lists.newArrayList("grpc.target"),
1✔
139
        Lists.newArrayList("grpc.lb.locality", "grpc.lb.backend_service"),
1✔
140
        false);
141
    ENDPOINT_WEIGHTS_HISTOGRAM = metricInstrumentRegistry.registerDoubleHistogram(
1✔
142
        "grpc.lb.wrr.endpoint_weights",
143
        "EXPERIMENTAL. The histogram buckets will be endpoint weight ranges.",
144
        "{weight}",
145
        Lists.newArrayList(),
1✔
146
        Lists.newArrayList("grpc.target"),
1✔
147
        Lists.newArrayList("grpc.lb.locality", "grpc.lb.backend_service"),
1✔
148
        false);
149
  }
1✔
150

151
  public WeightedRoundRobinLoadBalancer(Helper helper, Ticker ticker) {
152
    this(helper, ticker, new Random());
1✔
153
  }
1✔
154

155
  @VisibleForTesting
156
  WeightedRoundRobinLoadBalancer(Helper helper, Ticker ticker, Random random) {
157
    super(OrcaOobUtil.newOrcaReportingHelper(helper));
1✔
158
    this.ticker = checkNotNull(ticker, "ticker");
1✔
159
    this.infTime = ticker.nanoTime() + Long.MAX_VALUE;
1✔
160
    this.syncContext = checkNotNull(helper.getSynchronizationContext(), "syncContext");
1✔
161
    this.timeService = checkNotNull(helper.getScheduledExecutorService(), "timeService");
1✔
162
    this.updateWeightTask = new UpdateWeightTask();
1✔
163
    this.sequence = new AtomicInteger(random.nextInt());
1✔
164
    log.log(Level.FINE, "weighted_round_robin LB created");
1✔
165
  }
1✔
166

167
  @Override
168
  protected ChildLbState createChildLbState(Object key) {
169
    return new WeightedChildLbState(key, pickFirstLbProvider);
1✔
170
  }
171

172
  @Override
173
  public Status acceptResolvedAddresses(ResolvedAddresses resolvedAddresses) {
174
    if (resolvedAddresses.getLoadBalancingPolicyConfig() == null) {
1✔
175
      Status unavailableStatus = Status.UNAVAILABLE.withDescription(
1✔
176
              "NameResolver returned no WeightedRoundRobinLoadBalancerConfig. addrs="
177
                      + resolvedAddresses.getAddresses()
1✔
178
                      + ", attrs=" + resolvedAddresses.getAttributes());
1✔
179
      handleNameResolutionError(unavailableStatus);
1✔
180
      return unavailableStatus;
1✔
181
    }
182
    String locality = resolvedAddresses.getAttributes().get(WeightedTargetLoadBalancer.CHILD_NAME);
1✔
183
    if (locality != null) {
1✔
184
      this.locality = locality;
1✔
185
    } else {
186
      this.locality = "";
1✔
187
    }
188
    String backendService
1✔
189
        = resolvedAddresses.getAttributes().get(NameResolver.ATTR_BACKEND_SERVICE);
1✔
190
    if (backendService != null) {
1✔
191
      this.backendService = backendService;
1✔
192
    } else {
193
      this.backendService = "";
1✔
194
    }
195
    config =
1✔
196
        (WeightedRoundRobinLoadBalancerConfig) resolvedAddresses.getLoadBalancingPolicyConfig();
1✔
197

198
    if (weightUpdateTimer != null && weightUpdateTimer.isPending()) {
1✔
199
      weightUpdateTimer.cancel();
1✔
200
    }
201
    updateWeightTask.run();
1✔
202

203
    Status status = super.acceptResolvedAddresses(resolvedAddresses);
1✔
204

205
    createAndApplyOrcaListeners();
1✔
206

207
    return status;
1✔
208
  }
209

210
  /**
211
   * Updates picker with the list of active subchannels (state == READY).
212
   */
213
  @Override
214
  protected void updateOverallBalancingState() {
215
    List<ChildLbState> activeList = getReadyChildren();
1✔
216
    if (activeList.isEmpty()) {
1✔
217
      // No READY subchannels
218

219
      // MultiChildLB will request connection immediately on subchannel IDLE.
220
      boolean isConnecting = false;
1✔
221
      for (ChildLbState childLbState : getChildLbStates()) {
1✔
222
        ConnectivityState state = childLbState.getCurrentState();
1✔
223
        if (state == ConnectivityState.CONNECTING || state == ConnectivityState.IDLE) {
1✔
224
          isConnecting = true;
1✔
225
          break;
1✔
226
        }
227
      }
1✔
228

229
      if (isConnecting) {
1✔
230
        updateBalancingState(
1✔
231
            ConnectivityState.CONNECTING,
232
            new FixedResultPicker(
233
                PickResult.withNoResult("connecting", "weighted_round_robin: connecting")));
1✔
234
      } else {
235
        updateBalancingState(
1✔
236
            ConnectivityState.TRANSIENT_FAILURE, createReadyPicker(getChildLbStates()));
1✔
237
      }
238
    } else {
1✔
239
      updateBalancingState(ConnectivityState.READY, createReadyPicker(activeList));
1✔
240
    }
241
  }
1✔
242

243
  private SubchannelPicker createReadyPicker(Collection<ChildLbState> activeList) {
244
    WeightedRoundRobinPicker picker = new WeightedRoundRobinPicker(ImmutableList.copyOf(activeList),
1✔
245
        config.enableOobLoadReport, config.errorUtilizationPenalty, sequence,
246
        config.parsedMetricNamesForComputingUtilization);
247
    updateWeight(picker);
1✔
248
    return picker;
1✔
249
  }
250

251
  private void updateWeight(WeightedRoundRobinPicker picker) {
252
    Helper helper = getHelper();
1✔
253
    float[] newWeights = new float[picker.children.size()];
1✔
254
    AtomicInteger staleEndpoints = new AtomicInteger();
1✔
255
    AtomicInteger notYetUsableEndpoints = new AtomicInteger();
1✔
256
    for (int i = 0; i < picker.children.size(); i++) {
1✔
257
      double newWeight = ((WeightedChildLbState) picker.children.get(i)).getWeight(staleEndpoints,
1✔
258
          notYetUsableEndpoints);
259
      helper.getMetricRecorder()
1✔
260
          .recordDoubleHistogram(ENDPOINT_WEIGHTS_HISTOGRAM, newWeight,
1✔
261
              ImmutableList.of(helper.getChannelTarget()),
1✔
262
              ImmutableList.of(locality, backendService));
1✔
263
      newWeights[i] = newWeight > 0 ? (float) newWeight : 0.0f;
1✔
264
    }
265

266
    if (staleEndpoints.get() > 0) {
1✔
267
      helper.getMetricRecorder()
1✔
268
          .addLongCounter(ENDPOINT_WEIGHT_STALE_COUNTER, staleEndpoints.get(),
1✔
269
              ImmutableList.of(helper.getChannelTarget()),
1✔
270
              ImmutableList.of(locality, backendService));
1✔
271
    }
272
    if (notYetUsableEndpoints.get() > 0) {
1✔
273
      helper.getMetricRecorder()
1✔
274
          .addLongCounter(ENDPOINT_WEIGHT_NOT_YET_USEABLE_COUNTER, notYetUsableEndpoints.get(),
1✔
275
              ImmutableList.of(helper.getChannelTarget()),
1✔
276
              ImmutableList.of(locality, backendService));
1✔
277
    }
278
    boolean weightsEffective = picker.updateWeight(newWeights);
1✔
279
    if (!weightsEffective) {
1✔
280
      helper.getMetricRecorder()
1✔
281
          .addLongCounter(RR_FALLBACK_COUNTER, 1, ImmutableList.of(helper.getChannelTarget()),
1✔
282
              ImmutableList.of(locality, backendService));
1✔
283
    }
284
  }
1✔
285

286
  private void updateBalancingState(ConnectivityState state, SubchannelPicker picker) {
287
    if (state != currentConnectivityState || !picker.equals(currentPicker)) {
1✔
288
      getHelper().updateBalancingState(state, picker);
1✔
289
      currentConnectivityState = state;
1✔
290
      currentPicker = picker;
1✔
291
    }
292
  }
1✔
293

294
  @VisibleForTesting
295
  final class WeightedChildLbState extends ChildLbState {
296

297
    private final Set<WrrSubchannel> subchannels = new HashSet<>();
1✔
298
    private volatile long lastUpdated;
299
    private volatile long nonEmptySince;
300
    private volatile double weight = 0;
1✔
301

302
    private OrcaReportListener orcaReportListener;
303

304
    public WeightedChildLbState(Object key, LoadBalancerProvider policyProvider) {
1✔
305
      super(key, policyProvider);
1✔
306
    }
1✔
307

308
    @Override
309
    protected ChildLbStateHelper createChildHelper() {
310
      return new WrrChildLbStateHelper();
1✔
311
    }
312

313
    private double getWeight(AtomicInteger staleEndpoints, AtomicInteger notYetUsableEndpoints) {
314
      if (config == null) {
1✔
315
        return 0;
×
316
      }
317
      long now = ticker.nanoTime();
1✔
318
      if (now - lastUpdated >= config.weightExpirationPeriodNanos) {
1✔
319
        nonEmptySince = infTime;
1✔
320
        staleEndpoints.incrementAndGet();
1✔
321
        return 0;
1✔
322
      } else if (now - nonEmptySince < config.blackoutPeriodNanos
1✔
323
          && config.blackoutPeriodNanos > 0) {
1✔
324
        notYetUsableEndpoints.incrementAndGet();
1✔
325
        return 0;
1✔
326
      } else {
327
        return weight;
1✔
328
      }
329
    }
330

331
    public void addSubchannel(WrrSubchannel wrrSubchannel) {
332
      subchannels.add(wrrSubchannel);
1✔
333
    }
1✔
334

335
    public OrcaReportListener getOrCreateOrcaListener(float errorUtilizationPenalty,
336
        ImmutableList<ParsedMetricName> parsedMetricNamesForComputingUtilization) {
337
      if (orcaReportListener != null
1✔
338
          && orcaReportListener.errorUtilizationPenalty == errorUtilizationPenalty
1✔
339
          && orcaReportListener.parsedMetricNamesForComputingUtilization
1✔
340
              .equals(parsedMetricNamesForComputingUtilization)) {
1✔
341
        return orcaReportListener;
1✔
342
      }
343
      orcaReportListener =
1✔
344
          new OrcaReportListener(errorUtilizationPenalty, parsedMetricNamesForComputingUtilization);
345
      return orcaReportListener;
1✔
346
    }
347

348
    public void removeSubchannel(WrrSubchannel wrrSubchannel) {
349
      subchannels.remove(wrrSubchannel);
1✔
350
    }
1✔
351

352
    final class WrrChildLbStateHelper extends ChildLbStateHelper {
1✔
353
      @Override
354
      public Subchannel createSubchannel(CreateSubchannelArgs args) {
355
        return new WrrSubchannel(super.createSubchannel(args), WeightedChildLbState.this);
1✔
356
      }
357

358
      @Override
359
      public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
360
        super.updateBalancingState(newState, newPicker);
1✔
361
        if (!resolvingAddresses && newState == ConnectivityState.IDLE) {
1✔
362
          getLb().requestConnection();
×
363
        }
364
      }
1✔
365
    }
366

367
    final class OrcaReportListener implements OrcaPerRequestReportListener, OrcaOobReportListener {
368
      private final float errorUtilizationPenalty;
369
      private final ImmutableList<ParsedMetricName> parsedMetricNamesForComputingUtilization;
370

371
      OrcaReportListener(float errorUtilizationPenalty,
372
          ImmutableList<ParsedMetricName> parsedMetricNamesForComputingUtilization) {
1✔
373
        this.errorUtilizationPenalty = errorUtilizationPenalty;
1✔
374
        this.parsedMetricNamesForComputingUtilization = parsedMetricNamesForComputingUtilization;
1✔
375
      }
1✔
376

377
      @Override
378
      public void onLoadReport(MetricReport report) {
379
        double utilization = getUtilization(report);
1✔
380

381
        double newWeight = 0;
1✔
382
        if (utilization > 0 && report.getQps() > 0) {
1✔
383
          double penalty = 0;
1✔
384
          if (report.getEps() > 0 && errorUtilizationPenalty > 0) {
1✔
385
            penalty = report.getEps() / report.getQps() * errorUtilizationPenalty;
1✔
386
          }
387
          newWeight = report.getQps() / (utilization + penalty);
1✔
388
        }
389
        if (newWeight == 0) {
1✔
390
          return;
1✔
391
        }
392
        if (nonEmptySince == infTime) {
1✔
393
          nonEmptySince = ticker.nanoTime();
1✔
394
        }
395
        lastUpdated = ticker.nanoTime();
1✔
396
        weight = newWeight;
1✔
397
      }
1✔
398

399
      /**
400
       * Returns the utilization value computed from the specified metric names. If the custom
401
       * metrics are present and valid, the maximum of the custom metrics is returned. Otherwise,
402
       * if application utilization is > 0, it is returned. If neither are present, the CPU
403
       * utilization is returned.
404
       */
405
      private double getUtilization(MetricReport report) {
406
        OptionalDouble customUtil = getCustomMetricUtilization(report);
1✔
407
        if (customUtil.isPresent()) {
1✔
408
          return customUtil.getAsDouble();
1✔
409
        }
410
        double appUtil = report.getApplicationUtilization();
1✔
411
        if (appUtil > 0) {
1✔
412
          return appUtil;
1✔
413
        }
414
        return report.getCpuUtilization();
1✔
415
      }
416

417
      /**
418
       * Returns the maximum utilization value among the parsed metric names.
419
       * Returns OptionalDouble.empty() if NONE of the specified metrics are present in the report,
420
       * or if all present metrics are NaN or non positive.
421
       */
422
      private OptionalDouble getCustomMetricUtilization(MetricReport report) {
423
        OptionalDouble max = OptionalDouble.empty();
1✔
424
        for (int i = 0; i < parsedMetricNamesForComputingUtilization.size(); i++) {
1✔
425
          OptionalDouble opt = MetricReportUtils.getMetricValue(report,
1✔
426
              parsedMetricNamesForComputingUtilization.get(i));
1✔
427
          if (opt.isPresent()) {
1✔
428
            double d = opt.getAsDouble();
1✔
429
            if (!Double.isNaN(d) && d > 0 && (!max.isPresent() || d > max.getAsDouble())) {
1✔
430
              max = opt;
1✔
431
            }
432
          }
433
        }
434
        return max;
1✔
435
      }
436
    }
437
  }
438

439
  private final class UpdateWeightTask implements Runnable {
1✔
440
    @Override
441
    public void run() {
442
      if (currentPicker != null && currentPicker instanceof WeightedRoundRobinPicker) {
1✔
443
        updateWeight((WeightedRoundRobinPicker) currentPicker);
1✔
444
      }
445
      weightUpdateTimer = syncContext.schedule(this, config.weightUpdatePeriodNanos,
1✔
446
          TimeUnit.NANOSECONDS, timeService);
1✔
447
    }
1✔
448
  }
449

450
  private void createAndApplyOrcaListeners() {
451
    for (ChildLbState child : getChildLbStates()) {
1✔
452
      WeightedChildLbState wChild = (WeightedChildLbState) child;
1✔
453
      for (WrrSubchannel weightedSubchannel : wChild.subchannels) {
1✔
454
        if (config.enableOobLoadReport) {
1✔
455
          OrcaOobUtil.setListener(weightedSubchannel,
1✔
456
              wChild.getOrCreateOrcaListener(config.errorUtilizationPenalty,
1✔
457
                      config.parsedMetricNamesForComputingUtilization),
458
              OrcaOobUtil.OrcaReportingConfig.newBuilder()
1✔
459
                  .setReportInterval(config.oobReportingPeriodNanos, TimeUnit.NANOSECONDS).build());
1✔
460
        } else {
461
          OrcaOobUtil.setListener(weightedSubchannel, null, null);
1✔
462
        }
463
      }
1✔
464
    }
1✔
465
  }
1✔
466

467
  @Override
468
  public void shutdown() {
469
    if (weightUpdateTimer != null) {
1✔
470
      weightUpdateTimer.cancel();
1✔
471
    }
472
    super.shutdown();
1✔
473
  }
1✔
474

475
  @VisibleForTesting
476
  final class WrrSubchannel extends ForwardingSubchannel {
477
    private final Subchannel delegate;
478
    private final WeightedChildLbState owner;
479

480
    WrrSubchannel(Subchannel delegate, WeightedChildLbState owner) {
1✔
481
      this.delegate = checkNotNull(delegate, "delegate");
1✔
482
      this.owner = checkNotNull(owner, "owner");
1✔
483
    }
1✔
484

485
    @Override
486
    public void start(SubchannelStateListener listener) {
487
      owner.addSubchannel(this);
1✔
488
      delegate().start(new SubchannelStateListener() {
1✔
489
        @Override
490
        public void onSubchannelState(ConnectivityStateInfo newState) {
491
          if (newState.getState().equals(ConnectivityState.READY)) {
1✔
492
            owner.nonEmptySince = infTime;
1✔
493
          }
494
          listener.onSubchannelState(newState);
1✔
495
        }
1✔
496
      });
497
    }
1✔
498

499
    @Override
500
    protected Subchannel delegate() {
501
      return delegate;
1✔
502
    }
503

504
    @Override
505
    public void shutdown() {
506
      super.shutdown();
1✔
507
      owner.removeSubchannel(this);
1✔
508
    }
1✔
509
  }
510

511
  @VisibleForTesting
512
  static final class WeightedRoundRobinPicker extends SubchannelPicker {
513
    // Parallel lists (column-based storage instead of normal row-based storage of List<Struct>).
514
    // The ith element of children corresponds to the ith element of pickers, listeners, and even
515
    // updateWeight(float[]).
516
    private final List<ChildLbState> children; // May only be accessed from sync context
517
    private final List<SubchannelPicker> pickers;
518
    private final List<OrcaPerRequestReportListener> reportListeners;
519
    private final boolean enableOobLoadReport;
520
    private final float errorUtilizationPenalty;
521
    private final AtomicInteger sequence;
522
    private final int hashCode;
523
    private volatile StaticStrideScheduler scheduler;
524

525
    WeightedRoundRobinPicker(List<ChildLbState> children, boolean enableOobLoadReport,
526
        float errorUtilizationPenalty, AtomicInteger sequence,
527
        ImmutableList<ParsedMetricName> parsedMetricNamesForComputingUtilization) {
1✔
528
      checkNotNull(children, "children");
1✔
529
      Preconditions.checkArgument(!children.isEmpty(), "empty child list");
1✔
530
      this.children = children;
1✔
531
      List<SubchannelPicker> pickers = new ArrayList<>(children.size());
1✔
532
      List<OrcaPerRequestReportListener> reportListeners = new ArrayList<>(children.size());
1✔
533
      for (ChildLbState child : children) {
1✔
534
        WeightedChildLbState wChild = (WeightedChildLbState) child;
1✔
535
        pickers.add(wChild.getCurrentPicker());
1✔
536
        reportListeners.add(wChild.getOrCreateOrcaListener(errorUtilizationPenalty,
1✔
537
            parsedMetricNamesForComputingUtilization));
538
      }
1✔
539
      this.pickers = pickers;
1✔
540
      this.reportListeners = reportListeners;
1✔
541
      this.enableOobLoadReport = enableOobLoadReport;
1✔
542
      this.errorUtilizationPenalty = errorUtilizationPenalty;
1✔
543
      this.sequence = checkNotNull(sequence, "sequence");
1✔
544

545
      // For equality we treat pickers as a set; use hash code as defined by Set
546
      int sum = 0;
1✔
547
      for (SubchannelPicker picker : pickers) {
1✔
548
        sum += picker.hashCode();
1✔
549
      }
1✔
550
      this.hashCode = sum
1✔
551
          ^ Boolean.hashCode(enableOobLoadReport)
1✔
552
          ^ Float.hashCode(errorUtilizationPenalty);
1✔
553
    }
1✔
554

555
    @Override
556
    public PickResult pickSubchannel(PickSubchannelArgs args) {
557
      int pick = scheduler.pick();
1✔
558
      PickResult pickResult = pickers.get(pick).pickSubchannel(args);
1✔
559
      Subchannel subchannel = pickResult.getSubchannel();
1✔
560
      if (subchannel == null) {
1✔
561
        return pickResult;
1✔
562
      }
563
      
564
      subchannel = ((WrrSubchannel) subchannel).delegate();
1✔
565
      if (!enableOobLoadReport) {
1✔
566
        return pickResult.copyWithSubchannel(subchannel)
1✔
567
            .copyWithStreamTracerFactory(
1✔
568
                OrcaPerRequestUtil.getInstance().newOrcaClientStreamTracerFactory(
1✔
569
                    reportListeners.get(pick)));
1✔
570
      } else {
571
        return pickResult.copyWithSubchannel(subchannel);
1✔
572
      }
573
    }
574

575
    /** Returns {@code true} if weights are different than round_robin. */
576
    private boolean updateWeight(float[] newWeights) {
577
      this.scheduler = new StaticStrideScheduler(newWeights, sequence);
1✔
578
      return !this.scheduler.usesRoundRobin();
1✔
579
    }
580

581
    @Override
582
    public String toString() {
583
      return MoreObjects.toStringHelper(WeightedRoundRobinPicker.class)
1✔
584
          .add("enableOobLoadReport", enableOobLoadReport)
1✔
585
          .add("errorUtilizationPenalty", errorUtilizationPenalty)
1✔
586
          .add("pickers", pickers)
1✔
587
          .toString();
1✔
588
    }
589

590
    @VisibleForTesting
591
    List<ChildLbState> getChildren() {
592
      return children;
1✔
593
    }
594

595
    @Override
596
    public int hashCode() {
597
      return hashCode;
×
598
    }
599

600
    @Override
601
    public boolean equals(Object o) {
602
      if (!(o instanceof WeightedRoundRobinPicker)) {
1✔
603
        return false;
×
604
      }
605
      WeightedRoundRobinPicker other = (WeightedRoundRobinPicker) o;
1✔
606
      if (other == this) {
1✔
607
        return true;
×
608
      }
609
      // the lists cannot contain duplicate subchannels
610
      return hashCode == other.hashCode
1✔
611
          && sequence == other.sequence
612
          && enableOobLoadReport == other.enableOobLoadReport
613
          && Float.compare(errorUtilizationPenalty, other.errorUtilizationPenalty) == 0
1✔
614
          && pickers.size() == other.pickers.size()
1✔
615
          && new HashSet<>(pickers).containsAll(other.pickers);
1✔
616
    }
617
  }
618

619
  /*
620
   * The Static Stride Scheduler is an implementation of an earliest deadline first (EDF) scheduler
621
   * in which each object's deadline is the multiplicative inverse of the object's weight.
622
   * <p>
623
   * The way in which this is implemented is through a static stride scheduler. 
624
   * The Static Stride Scheduler works by iterating through the list of subchannel weights
625
   * and using modular arithmetic to proportionally distribute picks, favoring entries 
626
   * with higher weights. It is based on the observation that the intended sequence generated 
627
   * from an EDF scheduler is a periodic one that can be achieved through modular arithmetic. 
628
   * The Static Stride Scheduler is more performant than other implementations of the EDF
629
   * Scheduler, as it removes the need for a priority queue (and thus mutex locks).
630
   * <p>
631
   * go/static-stride-scheduler
632
   * <p>
633
   *
634
   * <ul>
635
   *  <li>nextSequence() - O(1)
636
   *  <li>pick() - O(n)
637
   */
638
  @VisibleForTesting
639
  static final class StaticStrideScheduler {
640
    private final short[] scaledWeights;
641
    private final AtomicInteger sequence;
642
    private final boolean usesRoundRobin;
643
    private static final int K_MAX_WEIGHT = 0xFFFF;
644

645
    // Assuming the mean of all known weights is M, StaticStrideScheduler will clamp
646
    // weights bigger than M*kMaxRatio and weights smaller than M*kMinRatio.
647
    //
648
    // This is done as a performance optimization by limiting the number of rounds for picks
649
    // for edge cases where channels have large differences in subchannel weights.
650
    // In this case, without these clips, it would potentially require the scheduler to
651
    // frequently traverse through the entire subchannel list within the pick method.
652
    //
653
    // The current values of 10 and 0.1 were chosen without any experimenting. It should
654
    // decrease the amount of sequences that the scheduler must traverse through in order
655
    // to pick a high weight subchannel in such corner cases.
656
    // But, it also makes WeightedRoundRobin to send slightly more requests to
657
    // potentially very bad tasks (that would have near-zero weights) than zero.
658
    // This is not necessarily a downside, though. Perhaps this is not a problem at
659
    // all, and we can increase this value if needed to save CPU cycles.
660
    private static final double K_MAX_RATIO = 10;
661
    private static final double K_MIN_RATIO = 0.1;
662

663
    StaticStrideScheduler(float[] weights, AtomicInteger sequence) {
1✔
664
      checkArgument(weights.length >= 1, "Couldn't build scheduler: requires at least one weight");
1✔
665
      int numChannels = weights.length;
1✔
666
      int numWeightedChannels = 0;
1✔
667
      double sumWeight = 0;
1✔
668
      double unscaledMeanWeight;
669
      float unscaledMaxWeight = 0;
1✔
670
      for (float weight : weights) {
1✔
671
        if (weight > 0) {
1✔
672
          sumWeight += weight;
1✔
673
          unscaledMaxWeight = Math.max(weight, unscaledMaxWeight);
1✔
674
          numWeightedChannels++;
1✔
675
        }
676
      }
677

678
      // Adjust max value s.t. ratio does not exceed K_MAX_RATIO. This should
679
      // ensure that we on average do at most K_MAX_RATIO rounds for picks.
680
      if (numWeightedChannels > 0) {
1✔
681
        unscaledMeanWeight = sumWeight / numWeightedChannels;
1✔
682
        unscaledMaxWeight = Math.min(unscaledMaxWeight, (float) (K_MAX_RATIO * unscaledMeanWeight));
1✔
683
      } else {
684
        // Fall back to round robin if all values are non-positives. Note that
685
        // numWeightedChannels == 1 also behaves like RR because the weights are all the same, but
686
        // the weights aren't 1, so it doesn't go through this path.
687
        unscaledMeanWeight = 1;
1✔
688
        unscaledMaxWeight = 1;
1✔
689
      }
690
      // We need at least two weights for WRR to be distinguishable from round_robin.
691
      usesRoundRobin = numWeightedChannels < 2;
1✔
692

693
      // Scales weights s.t. max(weights) == K_MAX_WEIGHT, meanWeight is scaled accordingly.
694
      // Note that, since we cap the weights to stay within K_MAX_RATIO, meanWeight might not
695
      // match the actual mean of the values that end up in the scheduler.
696
      double scalingFactor = K_MAX_WEIGHT / unscaledMaxWeight;
1✔
697
      // We compute weightLowerBound and clamp it to 1 from below so that in the
698
      // worst case, we represent tiny weights as 1.
699
      int weightLowerBound = (int) Math.ceil(scalingFactor * unscaledMeanWeight * K_MIN_RATIO);
1✔
700
      short[] scaledWeights = new short[numChannels];
1✔
701
      for (int i = 0; i < numChannels; i++) {
1✔
702
        if (weights[i] <= 0) {
1✔
703
          scaledWeights[i] = (short) Math.round(scalingFactor * unscaledMeanWeight);
1✔
704
        } else {
705
          int weight = (int) Math.round(scalingFactor * Math.min(weights[i], unscaledMaxWeight));
1✔
706
          scaledWeights[i] = (short) Math.max(weight, weightLowerBound);
1✔
707
        }
708
      }
709

710
      this.scaledWeights = scaledWeights;
1✔
711
      this.sequence = sequence;
1✔
712
    }
1✔
713

714
    // Without properly weighted channels, we do plain vanilla round_robin.
715
    boolean usesRoundRobin() {
716
      return usesRoundRobin;
1✔
717
    }
718

719
    /**
720
     * Returns the next sequence number and atomically increases sequence with wraparound.
721
     */
722
    private long nextSequence() {
723
      return Integer.toUnsignedLong(sequence.getAndIncrement());
1✔
724
    }
725

726
    /*
727
     * Selects index of next backend server.
728
     * <p>
729
     * A 2D array is compactly represented as a function of W(backend), where the row
730
     * represents the generation and the column represents the backend index:
731
     * X(backend,generation) | generation ∈ [0,kMaxWeight).
732
     * Each element in the conceptual array is a boolean indicating whether the backend at
733
     * this index should be picked now. If false, the counter is incremented again,
734
     * and the new element is checked. An atomically incremented counter keeps track of our
735
     * backend and generation through modular arithmetic within the pick() method.
736
     * <p>
737
     * Modular arithmetic allows us to evenly distribute picks and skips between
738
     * generations based on W(backend).
739
     * X(backend,generation) = (W(backend) * generation) % kMaxWeight >= kMaxWeight - W(backend)
740
     * If we have the same three backends with weights:
741
     * W(backend) = {2,3,6} scaled to max(W(backend)) = 6, then X(backend,generation) is:
742
     * <p>
743
     * B0    B1    B2
744
     * T     T     T
745
     * F     F     T
746
     * F     T     T
747
     * T     F     T
748
     * F     T     T
749
     * F     F     T
750
     * The sequence of picked backend indices is given by
751
     * walking across and down: {0,1,2,2,1,2,0,2,1,2,2}.
752
     * <p>
753
     * To reduce the variance and spread the wasted work among different picks,
754
     * an offset that varies per backend index is also included to the calculation.
755
     */
756
    int pick() {
757
      while (true) {
758
        long sequence = this.nextSequence();
1✔
759
        int backendIndex = (int) (sequence % scaledWeights.length);
1✔
760
        long generation = sequence / scaledWeights.length;
1✔
761
        int weight = Short.toUnsignedInt(scaledWeights[backendIndex]);
1✔
762
        long offset = (long) K_MAX_WEIGHT / 2 * backendIndex;
1✔
763
        if ((weight * generation + offset) % K_MAX_WEIGHT < K_MAX_WEIGHT - weight) {
1✔
764
          continue;
1✔
765
        }
766
        return backendIndex;
1✔
767
      }
768
    }
769
  }
770

771
  static final class WeightedRoundRobinLoadBalancerConfig {
772
    final long blackoutPeriodNanos;
773
    final long weightExpirationPeriodNanos;
774
    final boolean enableOobLoadReport;
775
    final long oobReportingPeriodNanos;
776
    final long weightUpdatePeriodNanos;
777
    final float errorUtilizationPenalty;
778
    final ImmutableList<ParsedMetricName> parsedMetricNamesForComputingUtilization;
779

780
    public static Builder newBuilder() {
781
      return new Builder();
1✔
782
    }
783

784
    private WeightedRoundRobinLoadBalancerConfig(long blackoutPeriodNanos,
785
        long weightExpirationPeriodNanos, boolean enableOobLoadReport, long oobReportingPeriodNanos,
786
        long weightUpdatePeriodNanos, float errorUtilizationPenalty,
787
        ImmutableList<String> metricNamesForComputingUtilization) {
1✔
788
      this.blackoutPeriodNanos = blackoutPeriodNanos;
1✔
789
      this.weightExpirationPeriodNanos = weightExpirationPeriodNanos;
1✔
790
      this.enableOobLoadReport = enableOobLoadReport;
1✔
791
      this.oobReportingPeriodNanos = oobReportingPeriodNanos;
1✔
792
      this.weightUpdatePeriodNanos = weightUpdatePeriodNanos;
1✔
793
      this.errorUtilizationPenalty = errorUtilizationPenalty;
1✔
794

795
      ImmutableList.Builder<ParsedMetricName> builder = ImmutableList.builder();
1✔
796
      if (metricNamesForComputingUtilization != null) {
1✔
797
        for (int i = 0; i < metricNamesForComputingUtilization.size(); i++) {
1✔
798
          String metricName = metricNamesForComputingUtilization.get(i);
1✔
799
          ParsedMetricName parsed = MetricReportUtils.ParsedMetricName.parse(metricName);
1✔
800
          if (parsed.getMetricType() != MetricReportUtils.MetricType.INVALID) {
1✔
801
            builder.add(parsed);
1✔
802
          } else {
803
            log.log(Level.FINE, "Invalid custom metric name configured and ignored: " + metricName);
1✔
804
          }
805
        }
806
      }
807
      this.parsedMetricNamesForComputingUtilization = builder.build();
1✔
808
    }
1✔
809

810
    @Override
811
    public boolean equals(Object o) {
812
      if (!(o instanceof WeightedRoundRobinLoadBalancerConfig)) {
1✔
813
        return false;
1✔
814
      }
815
      WeightedRoundRobinLoadBalancerConfig that = (WeightedRoundRobinLoadBalancerConfig) o;
1✔
816
      return this.blackoutPeriodNanos == that.blackoutPeriodNanos
1✔
817
          && this.weightExpirationPeriodNanos == that.weightExpirationPeriodNanos
818
          && this.enableOobLoadReport == that.enableOobLoadReport
819
          && this.oobReportingPeriodNanos == that.oobReportingPeriodNanos
820
          && this.weightUpdatePeriodNanos == that.weightUpdatePeriodNanos
821
          // Float.compare considers NaNs equal
822
          && Float.compare(this.errorUtilizationPenalty, that.errorUtilizationPenalty) == 0
1✔
823
          && Objects.equals(this.parsedMetricNamesForComputingUtilization,
1✔
824
              that.parsedMetricNamesForComputingUtilization);
825
    }
826

827
    @Override
828
    public int hashCode() {
829
      return Objects.hash(blackoutPeriodNanos, weightExpirationPeriodNanos, enableOobLoadReport,
1✔
830
          oobReportingPeriodNanos, weightUpdatePeriodNanos, errorUtilizationPenalty,
1✔
831
          parsedMetricNamesForComputingUtilization);
832
    }
833

834
    @Override
835
    public String toString() {
836
      return MoreObjects.toStringHelper(this)
1✔
837
          .add("blackoutPeriodNanos", blackoutPeriodNanos)
1✔
838
          .add("weightExpirationPeriodNanos", weightExpirationPeriodNanos)
1✔
839
          .add("enableOobLoadReport", enableOobLoadReport)
1✔
840
          .add("oobReportingPeriodNanos", oobReportingPeriodNanos)
1✔
841
          .add("weightUpdatePeriodNanos", weightUpdatePeriodNanos)
1✔
842
          .add("errorUtilizationPenalty", errorUtilizationPenalty)
1✔
843
          .add("parsedMetricNamesForComputingUtilization", parsedMetricNamesForComputingUtilization)
1✔
844
          .toString();
1✔
845
    }
846

847
    static final class Builder {
848
      long blackoutPeriodNanos = 10_000_000_000L; // 10s
1✔
849
      long weightExpirationPeriodNanos = 180_000_000_000L; // 3min
1✔
850
      boolean enableOobLoadReport = false;
1✔
851
      long oobReportingPeriodNanos = 10_000_000_000L; // 10s
1✔
852
      long weightUpdatePeriodNanos = 1_000_000_000L; // 1s
1✔
853
      float errorUtilizationPenalty = 1.0F;
1✔
854
      ImmutableList<String> metricNamesForComputingUtilization = ImmutableList.of();
1✔
855

856
      private Builder() {
1✔
857

858
      }
1✔
859

860
      @SuppressWarnings("UnusedReturnValue")
861
      Builder setBlackoutPeriodNanos(long blackoutPeriodNanos) {
862
        this.blackoutPeriodNanos = blackoutPeriodNanos;
1✔
863
        return this;
1✔
864
      }
865

866
      @SuppressWarnings("UnusedReturnValue")
867
      Builder setWeightExpirationPeriodNanos(long weightExpirationPeriodNanos) {
868
        this.weightExpirationPeriodNanos = weightExpirationPeriodNanos;
1✔
869
        return this;
1✔
870
      }
871

872
      Builder setEnableOobLoadReport(boolean enableOobLoadReport) {
873
        this.enableOobLoadReport = enableOobLoadReport;
1✔
874
        return this;
1✔
875
      }
876

877
      Builder setOobReportingPeriodNanos(long oobReportingPeriodNanos) {
878
        this.oobReportingPeriodNanos = oobReportingPeriodNanos;
1✔
879
        return this;
1✔
880
      }
881

882
      Builder setWeightUpdatePeriodNanos(long weightUpdatePeriodNanos) {
883
        this.weightUpdatePeriodNanos = weightUpdatePeriodNanos;
1✔
884
        return this;
1✔
885
      }
886

887
      Builder setErrorUtilizationPenalty(float errorUtilizationPenalty) {
888
        this.errorUtilizationPenalty = errorUtilizationPenalty;
1✔
889
        return this;
1✔
890
      }
891

892
      Builder setMetricNamesForComputingUtilization(
893
          List<String> metricNamesForComputingUtilization) {
894
        this.metricNamesForComputingUtilization =
1✔
895
            ImmutableList.copyOf(metricNamesForComputingUtilization);
1✔
896
        return this;
1✔
897
      }
898

899
      WeightedRoundRobinLoadBalancerConfig build() {
900
        return new WeightedRoundRobinLoadBalancerConfig(blackoutPeriodNanos,
1✔
901
            weightExpirationPeriodNanos, enableOobLoadReport, oobReportingPeriodNanos,
902
            weightUpdatePeriodNanos, errorUtilizationPenalty, metricNamesForComputingUtilization);
903
      }
904
    }
905
  }
906
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc