Repository: grpc/grpc-go
File: balancer/randomsubsetting/randomsubsetting.go (Go)

Code before:
	}
	if b.cfg == nil || b.cfg.ChildPolicy.Name != lbCfg.ChildPolicy.Name {

		if err := b.Balancer.SwitchTo(balancer.Get(lbCfg.ChildPolicy.Name)); err != nil {
			return fmt.Errorf("randomsubsetting: error switching to child of type %q: %v", lbCfg.ChildPolicy.Name, err)
		}
	}
	b.cfg = lbCfg

	return b.Balancer.UpdateClientConnState(balancer.ClientConnState{
		ResolverState:  b.prepareChildResolverState(s),
		BalancerConfig: b.cfg.ChildPolicy.Config,
	})
}

type endpointWithHash struct {
	hash uint64
	ep   resolver.Endpoint
}

// implements the subsetting algorithm,
// as described in A68: https://github.com/grpc/proposal/blob/master/A68-random-subsetting.md
func (b *subsettingBalancer) prepareChildResolverState(s balancer.ClientConnState) resolver.State {
	subsetSize := b.cfg.SubsetSize
	endpoints := s.ResolverState.Endpoints
	if len(endpoints) <= int(subsetSize) || subsetSize < 2 {
		return s.ResolverState
	}

	endpointSet := make([]endpointWithHash, len(endpoints))
	for i, endpoint := range endpoints {
		b.hashf.Write([]byte(endpoint.Addresses[0].String()))
		endpointSet[i] = endpointWithHash{
			hash: b.hashf.Sum64(),
			ep:   endpoint,
		}
	}

	slices.SortFunc(endpointSet, func(a, b endpointWithHash) int {
		if a.hash == b.hash {
			return 0
		}
		if a.hash < b.hash {
			return -1
		}
		return 1
	})

	if b.logger.V(2) {
		b.logger.Infof("Resulting subset: %v", endpointSet[:subsetSize])
	}

Review comment (refactor):
The subsetting algorithm described in the gRFC does not specify any special considerations for subset sizes less than two. Please see: https://github.com/grpc/proposal/blob/master/A68-random-subsetting.md#subsetting-algorithm

So, please remove this condition `subsetSize < 2`. If the user wants a subset size of `1`, they should get just that.

Code after:
	hashDigest *xxhash.Digest
}

func (b *subsettingBalancer) UpdateClientConnState(s balancer.ClientConnState) error {
	lbCfg, ok := s.BalancerConfig.(*lbConfig)
	if !ok {
		b.logger.Warningf("Received config with unexpected type %T: %v", s.BalancerConfig, s.BalancerConfig)
		return balancer.ErrBadResolverState
	}

	// Build config for the gracefulswitch balancer. It is safe to ignore
	// JSON marshaling errors here, since the config was already validated
	// as part of ParseConfig().
	cfg := []map[string]any{{lbCfg.ChildPolicy.Name: lbCfg.ChildPolicy.Config}}
	cfgJSON, _ := json.Marshal(cfg)
	parsedCfg, err := gracefulswitch.ParseConfig(cfgJSON)
	if err != nil {
		return fmt.Errorf("randomsubsetting: error switching to child of type %q: %v", lbCfg.ChildPolicy.Name, err)
	}
	b.cfg = lbCfg
	endpoints := resolver.State{
		Endpoints:     b.calculateSubset(s.ResolverState.Endpoints),
		ServiceConfig: s.ResolverState.ServiceConfig,
		Attributes:    s.ResolverState.Attributes,
	}

	return b.Balancer.UpdateClientConnState(balancer.ClientConnState{
		ResolverState:  endpoints,
		BalancerConfig: parsedCfg,
	})
}

// calculateSubset implements the subsetting algorithm, as described in A68:
// https://github.com/grpc/proposal/blob/master/A68-random-subsetting.md#subsetting-algorithm
func (b *subsettingBalancer) calculateSubset(endpoints []resolver.Endpoint) []resolver.Endpoint {
	// A helper struct to hold an endpoint and its hash.
	type endpointWithHash struct {
		hash uint64
		ep   resolver.Endpoint
	}

	subsetSize := b.cfg.SubsetSize
	if len(endpoints) <= int(subsetSize) {
		return endpoints
	}

	hashedEndpoints := make([]endpointWithHash, len(endpoints))
	for i, endpoint := range endpoints {
		// For every endpoint in the list, compute a hash with previously
		// generated seed - A68.
		//