ronantakizawa/codereview-bench huggingface dataset:
Repository: etcd-io/etcd
File: server/etcdmain/config_test.go (Go)

Code before:
				t.Fatal(err)
			}

			tmpfile := mustCreateCfgFile(t, b)
			defer os.Remove(tmpfile.Name())

			// Parse config
			cfg := newConfig()
			err = cfg.parse([]string{fmt.Sprintf("--config-file=%s", tmpfile.Name())})
			if err != nil {
				t.Fatal(err)
			}

			// Check which flags were set and marked as deprecated
			foundFlags := make(map[string]struct{})
			for flagName := range cfg.ec.FlagsExplicitlySet {
				if _, ok := deprecatedFlags[flagName]; ok {
					foundFlags[flagName] = struct{}{}
				}
			}

			// Compare sets of flags
			if !reflect.DeepEqual(foundFlags, tc.expectedFlags) {
				t.Errorf("deprecated flags mismatch:\ngot: %v\nwant: %v",
					mapToSortedSlice(foundFlags),
					mapToSortedSlice(tc.expectedFlags))
			}

			// Special check for experimental-warning-unary-request-duration
			if tc.configFileYAML.ExperimentalWarningUnaryRequestDuration != 0 {
				// Verify that the warning was logged, but don't require it to be in FlagsExplicitlySet
				// The warning is handled in a different way in the code
				t.Log("Note: experimental-warning-unary-request-duration deprecation is handled separately")
			}
		})
	}
}

// Helper function to convert map keys to sorted slice for better error messages
func mapToSortedSlice(m map[string]struct{}) []string {
	result := make([]string, 0, len(m))
	for k := range m {
		result = append(result, k)
	}
	sort.Strings(result)
	return result
}


Review comment (suggestion):
```suggestion
					slices.Sorted(maps.Keys(foundFlags)),
					slices.Sorted(maps.Keys(tc.expectedFlags))
```

Code after:
				t.Fatal(err)
			}

			tmpfile := mustCreateCfgFile(t, b)
			defer os.Remove(tmpfile.Name())

			// Parse config
			cfg := newConfig()
			err = cfg.parse([]string{fmt.Sprintf("--config-file=%s", tmpfile.Name())})
			if err != nil {
				t.Fatal(err)
			}

			// Check which flags were set and marked as deprecated
			foundFlags := make(map[string]struct{})
			for flagName := range cfg.ec.FlagsExplicitlySet {
				if _, ok := deprecatedFlags[flagName]; ok {
					foundFlags[flagName] = struct{}{}
				}
			}

			// Compare sets of flags
			assert.Equalf(t, tc.expectedFlags, foundFlags, "deprecated flags mismatch - expected: %v, got: %v",
				tc.expectedFlags, foundFlags)

			// Note: experimental-warning-unary-request-duration deprecation is handled
			// through a separate mechanism in embed.Config
			if tc.configFileYAML.ExperimentalWarningUnaryRequestDuration != 0 {
				assert.Equalf(t, cfg.ec.WarningUnaryRequestDuration,
					tc.configFileYAML.ExperimentalWarningUnaryRequestDuration,
					"experimental warning duration mismatch - expected: %v, got: %v",
					tc.configFileYAML.ExperimentalWarningUnaryRequestDuration,
					cfg.ec.WarningUnaryRequestDuration)
			}
		})
	}
}
Repository: etcd-io/etcd
File: pkg/flags/selective_string.go (Go)

Code before:
// for which any one of the given strings is a valid value,
// and any other value is an error.
//
// valids[0] will be default value. Caller must be sure
// len(valids) != 0 or it will panic.
func NewSelectiveStringValue(valids ...string) *SelectiveStringValue {
	vm := make(map[string]struct{})
	for _, v := range valids {
		vm[v] = struct{}{}
	}
	return &SelectiveStringValue{valids: vm, v: valids[0]}
}

// SelectiveStringsValue implements the flag.Value interface.
type SelectiveStringsValue struct {
	vs     []string
	valids map[string]struct{}
}

// Set verifies the argument to be a valid member of the allowed values
// before setting the underlying flag value.
func (ss *SelectiveStringsValue) Set(s string) error {
	vs := strings.Split(s, ",")
	for i := range vs {
		_, ok := ss.valids[vs[i]]
		if !ok {
			return fmt.Errorf("invalid value %q", vs[i])
		}
		ss.vs = append(ss.vs, vs[i])
	}
	sort.Strings(ss.vs)
	return nil
}

// String returns the set value (if any) of the SelectiveStringsValue.
func (ss *SelectiveStringsValue) String() string {
	return strings.Join(ss.vs, ",")
}

// Valids returns the list of valid strings.
func (ss *SelectiveStringsValue) Valids() []string {
	s := make([]string, 0, len(ss.valids))
	for k := range ss.valids {
		s = append(s, k)
	}
	sort.Strings(s)
	return s
}

// NewSelectiveStringsValue creates a new string slice flag
// for which any one of the given strings is a valid value,

Review comment (suggestion):
minor comment
```suggestion
		if _, ok := ss.valids[vs[i]]; !ok {
```

Code after:
// for which any one of the given strings is a valid value,
// and any other value is an error.
//
// valids[0] will be default value. Caller must be sure
// len(valids) != 0 or it will panic.
func NewSelectiveStringValue(valids ...string) *SelectiveStringValue {
	vm := make(map[string]struct{})
	for _, v := range valids {
		vm[v] = struct{}{}
	}
	return &SelectiveStringValue{valids: vm, v: valids[0]}
}

// SelectiveStringsValue implements the flag.Value interface.
type SelectiveStringsValue struct {
	vs     []string
	valids map[string]struct{}
}

// Set verifies the argument to be a valid member of the allowed values
// before setting the underlying flag value.
func (ss *SelectiveStringsValue) Set(s string) error {
	vs := strings.Split(s, ",")
	for i := range vs {
		if _, ok := ss.valids[vs[i]]; !ok {
			return fmt.Errorf("invalid value %q", vs[i])
		}
		ss.vs = append(ss.vs, vs[i])
	}
	sort.Strings(ss.vs)
	return nil
}

// String returns the set value (if any) of the SelectiveStringsValue.
func (ss *SelectiveStringsValue) String() string {
	return strings.Join(ss.vs, ",")
}

// Valids returns the list of valid strings.
func (ss *SelectiveStringsValue) Valids() []string {
	s := make([]string, 0, len(ss.valids))
	for k := range ss.valids {
		s = append(s, k)
	}
	sort.Strings(s)
	return s
}

// NewSelectiveStringsValue creates a new string slice flag
// for which any one of the given strings is a valid value,
// and any other value is an error.
Repository: etcd-io/etcd
File: etcdctl/ctlv3/ctl.go (Go)

Code before:
		command.NewAuthCommand(),
		command.NewUserCommand(),
		command.NewRoleCommand(),
		command.NewCheckCommand(),
		command.NewCompletionCommand(),
		command.NewDowngradeCommand(),
	)
}

func usageFunc(c *cobra.Command) error {
	return cobrautl.UsageFunc(c, version.Version, version.APIVersion)
}

func Start() error {
	rootCmd.SetUsageFunc(usageFunc)
	// Make help just show the usage
	rootCmd.SetHelpTemplate(`{{.UsageString}}`)
	return rootCmd.Execute()
}

func MustStart() {
	if err := Start(); err != nil {
		if !rootCmd.SilenceErrors {
			os.Exit(cobrautl.ExitError)
		}
		cobrautl.ExitWithError(cobrautl.ExitError, err)
	}
}

func init() {
	cobra.EnablePrefixMatching = true
}


Review comment (suggestion):
I think this can also be simplified as just removing the else condition, as [`cobrautl.ExitWithError()`](https://github.com/etcd-io/etcd/blob/507c0de87bd5034e3de4ab76ebf96b54dae0cd52/pkg/cobrautl/error.go#L37-L40) already does an `os.Exit()`.

```suggestion
		if rootCmd.SilenceErrors {
			cobrautl.ExitWithError(cobrautl.ExitError, err)
		}
		os.Exit(cobrautl.ExitError)
```

Code after:
		command.NewAuthCommand(),
		command.NewUserCommand(),
		command.NewRoleCommand(),
		command.NewCheckCommand(),
		command.NewCompletionCommand(),
		command.NewDowngradeCommand(),
	)
}

func usageFunc(c *cobra.Command) error {
	return cobrautl.UsageFunc(c, version.Version, version.APIVersion)
}

func Start() error {
	rootCmd.SetUsageFunc(usageFunc)
	// Make help just show the usage
	rootCmd.SetHelpTemplate(`{{.UsageString}}`)
	return rootCmd.Execute()
}

func MustStart() {
	if err := Start(); err != nil {
		if rootCmd.SilenceErrors {
			cobrautl.ExitWithError(cobrautl.ExitError, err)
		}
		os.Exit(cobrautl.ExitError)
	}
}

func init() {
	cobra.EnablePrefixMatching = true
}
Repository: etcd-io/etcd
File: integration/embed_test.go (Go)

Code before:
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !cluster_proxy
// +build !cluster_proxy

// TODO: fix race conditions with setupLogging

package integration

import (
	"context"
	"fmt"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	"go.etcd.io/etcd/clientv3"
	"go.etcd.io/etcd/embed"
	gofail "go.etcd.io/gofail/runtime"
)

func TestEmbedEtcd(t *testing.T) {
	tests := []struct {
		cfg embed.Config

		werr     string
		wpeers   int
		wclients int
	}{
		{werr: "multiple discovery"},
		{werr: "advertise-client-urls is required"},
		{werr: "should be at least"},
		{werr: "is too long"},
		{wpeers: 1, wclients: 1},
		{wpeers: 2, wclients: 1},
		{wpeers: 1, wclients: 2},
		{werr: "expected IP"},
		{werr: "expected IP"},
	}

	urls := newEmbedURLs(false, 10)

Review comment (suggestion):
```suggestion
	"github.com/stretchr/testify/require"

```

Code after:
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !cluster_proxy
// +build !cluster_proxy

// TODO: fix race conditions with setupLogging

package integration

import (
	"context"
	"fmt"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"go.etcd.io/etcd/clientv3"
	"go.etcd.io/etcd/embed"
	gofail "go.etcd.io/gofail/runtime"
)

func TestEmbedEtcd(t *testing.T) {
	tests := []struct {
		cfg embed.Config

		werr     string
		wpeers   int
		wclients int
	}{
		{werr: "multiple discovery"},
		{werr: "advertise-client-urls is required"},
		{werr: "should be at least"},
		{werr: "is too long"},
		{wpeers: 1, wclients: 1},
		{wpeers: 2, wclients: 1},
		{wpeers: 1, wclients: 2},
		{werr: "expected IP"},
		{werr: "expected IP"},
	}
Repository: etcd-io/etcd
File: tests/integration/embed/embed_test.go (Go)

Code before:
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !cluster_proxy
// +build !cluster_proxy

// Keep the test in a separate package from other tests such that
// .setupLogging method does not race with other (previously running) servers (grpclog is global).

package embed_test

import (
	"context"
	"fmt"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
	"go.etcd.io/etcd/client/pkg/v3/testutil"
	"go.etcd.io/etcd/client/pkg/v3/transport"
	clientv3 "go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/server/v3/embed"
	"go.etcd.io/etcd/tests/v3/integration"
	gofail "go.etcd.io/gofail/runtime"
)

var (
	testTLSInfo = transport.TLSInfo{
		KeyFile:        integration.MustAbsPath("../../fixtures/server.key.insecure"),
		CertFile:       integration.MustAbsPath("../../fixtures/server.crt"),
		TrustedCAFile:  integration.MustAbsPath("../../fixtures/ca.crt"),
		ClientCertAuth: true,
	}
)

func TestEmbedEtcd(t *testing.T) {
	testutil.SkipTestIfShortMode(t, "Cannot start embedded cluster in --short tests")

	tests := []struct {
		cfg embed.Config

		werr     string
		wpeers   int

Review comment (suggestion):
```suggestion
	"github.com/stretchr/testify/require"

```

Code after:
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !cluster_proxy
// +build !cluster_proxy

// Keep the test in a separate package from other tests such that
// .setupLogging method does not race with other (previously running) servers (grpclog is global).

package embed_test

import (
	"context"
	"fmt"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"go.etcd.io/etcd/client/pkg/v3/testutil"
	"go.etcd.io/etcd/client/pkg/v3/transport"
	clientv3 "go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/server/v3/embed"
	"go.etcd.io/etcd/tests/v3/integration"
	gofail "go.etcd.io/gofail/runtime"
)

var (
	testTLSInfo = transport.TLSInfo{
		KeyFile:        integration.MustAbsPath("../../fixtures/server.key.insecure"),
		CertFile:       integration.MustAbsPath("../../fixtures/server.crt"),
		TrustedCAFile:  integration.MustAbsPath("../../fixtures/ca.crt"),
		ClientCertAuth: true,
	}
)

func TestEmbedEtcd(t *testing.T) {
	testutil.SkipTestIfShortMode(t, "Cannot start embedded cluster in --short tests")

	tests := []struct {
		cfg embed.Config

		werr     string
Repository: etcd-io/etcd
File: client/pkg/logutil/zap.go (Go)

Code before:

	// Use "/dev/null" to discard all
	OutputPaths:      []string{"stderr"},
	ErrorOutputPaths: []string{"stderr"},
}

// MergeOutputPaths merges logging output paths, resolving conflicts.
func MergeOutputPaths(cfg zap.Config) zap.Config {
	outputs := make(map[string]struct{})
	for _, v := range cfg.OutputPaths {
		outputs[v] = struct{}{}
	}
	outputSlice := make([]string, 0)
	if _, ok := outputs["/dev/null"]; ok {
		// "/dev/null" to discard all
		outputSlice = []string{"/dev/null"}
	} else {
		for k := range outputs {
			outputSlice = append(outputSlice, k)
		}
	}
	cfg.OutputPaths = outputSlice
	sort.Strings(cfg.OutputPaths)

	errOutputs := make(map[string]struct{})
	for _, v := range cfg.ErrorOutputPaths {
		errOutputs[v] = struct{}{}
	}
	errOutputSlice := make([]string, 0)
	if _, ok := errOutputs["/dev/null"]; ok {
		// "/dev/null" to discard all
		errOutputSlice = []string{"/dev/null"}
	} else {
		for k := range errOutputs {
			errOutputSlice = append(errOutputSlice, k)
		}
	}
	cfg.ErrorOutputPaths = errOutputSlice
	sort.Strings(cfg.ErrorOutputPaths)

	return cfg
}


Review comment (performance):
This changes the complexity, however I don't expect it number of outputs to be large. Readability should take precedence here.

Code after:

	// Use "/dev/null" to discard all
	OutputPaths:      []string{"stderr"},
	ErrorOutputPaths: []string{"stderr"},
}

// MergeOutputPaths merges logging output paths, resolving conflicts.
func MergeOutputPaths(cfg zap.Config) zap.Config {
	cfg.OutputPaths = mergePaths(cfg.OutputPaths)
	cfg.ErrorOutputPaths = mergePaths(cfg.ErrorOutputPaths)
	return cfg
}

func mergePaths(old []string) []string {
	if len(old) == 0 {
		// the original implementation ensures the result is non-nil
		return []string{}
	}
	// use "/dev/null" to discard all
	if slices.Contains(old, "/dev/null") {
		return []string{"/dev/null"}
	}
	// clone a new one; don't modify the original, in case it matters.
	dup := slices.Clone(old)
	slices.Sort(dup)
	return slices.Compact(dup)
}
Repository: etcd-io/etcd
File: server/embed/etcd.go (Go)

Code before:

	// close client requests with request timeout
	timeout := 2 * time.Second
	if e.Server != nil {
		timeout = e.Server.Cfg.ReqTimeout()
	}
	for _, sctx := range e.sctxs {
		for ss := range sctx.serversC {
			ctx, cancel := context.WithTimeout(context.Background(), timeout)
			stopServers(ctx, ss)
			cancel()
		}
	}

	for _, sctx := range e.sctxs {
		sctx.cancel()
	}

	// shutdown tracing exporter
	if e.tracingExporterShutdown != nil {
		e.tracingExporterShutdown()
	}

	// close rafthttp transports
	if e.Server != nil {
		e.Server.Stop()
	}

	// close all idle connections in peer handler (wait up to 1-second)
	for i := range e.Peers {
		if e.Peers[i] != nil && e.Peers[i].close != nil {
			ctx, cancel := context.WithTimeout(context.Background(), time.Second)
			e.Peers[i].close(ctx)
			cancel()
		}
	}
	if e.errc != nil {
		e.wg.Wait()
		close(e.errc)
	}
}

func stopServers(ctx context.Context, ss *servers) {
	// first, close the http.Server
	if ss.http != nil {
		ss.http.Shutdown(ctx)
	}
	if ss.grpc == nil {
		return
	}
	// do not grpc.Server.GracefulStop when grpc runs under http server

Review comment (suggestion):
The Clients here is about net listener. If we close it at the beginning, all the connections will be closed, and it seems like we are unable to drain all the inflight requests gracefully. The `stopServers` function is used to gracefully shutdown.

Code after:
		zap.String("data-dir", e.cfg.Dir),
		zap.Strings("advertise-peer-urls", e.cfg.getAdvertisePeerURLs()),
		zap.Strings("advertise-client-urls", e.cfg.getAdvertiseClientURLs()),
	}
	lg := e.GetLogger()
	lg.Info("closing etcd server", fields...)
	defer func() {
		lg.Info("closed etcd server", fields...)
		verify.MustVerifyIfEnabled(verify.Config{
			Logger:     lg,
			DataDir:    e.cfg.Dir,
			ExactIndex: false,
		})
		lg.Sync()
	}()

	e.closeOnce.Do(func() {
		close(e.stopc)
	})

	// close client requests with request timeout
	timeout := 2 * time.Second
	if e.Server != nil {
		timeout = e.Server.Cfg.ReqTimeout()
	}
	for _, sctx := range e.sctxs {
		for ss := range sctx.serversC {
			ctx, cancel := context.WithTimeout(context.Background(), timeout)
			stopServers(ctx, ss)
			cancel()
		}
	}

	for _, sctx := range e.sctxs {
		sctx.cancel()
	}

	for i := range e.Clients {
		if e.Clients[i] != nil {
			e.Clients[i].Close()
		}
	}

	for i := range e.metricsListeners {
		e.metricsListeners[i].Close()
	}

	// shutdown tracing exporter
	if e.tracingExporterShutdown != nil {
		e.tracingExporterShutdown()
	}
Repository: etcd-io/etcd
File: tests/robustness/traffic/kubernetes.go (Go)

Code before:
func (s *storage) Reset(revision int64, kvs []*mvccpb.KeyValue) {
	s.mux.Lock()
	defer s.mux.Unlock()
	if revision <= s.revision {
		return
	}
	s.keyRevision = make(map[string]int64, len(kvs))
	for _, kv := range kvs {
		s.keyRevision[string(kv.Key)] = kv.ModRevision
	}
	s.revision = revision
}

func (s *storage) Count() int {
	s.mux.RLock()
	defer s.mux.RUnlock()
	return len(s.keyRevision)
}

func (s *storage) PickRandom() (key string, rev int64) {
	s.mux.RLock()
	defer s.mux.RUnlock()
	for k, v := range s.keyRevision {
		return k, v
	}
	return "", 0
}


Review comment (suggestion):
Let's keep the `PickRandom` function random and fair. Picking first element from map, might seem random, but in reality it will return the same element everytime if map was not changed. I think it's important to have this function to have some equal distribution. 

Code after:

func (s *storage) Reset(revision int64, kvs []*mvccpb.KeyValue) {
	s.mux.Lock()
	defer s.mux.Unlock()
	if revision <= s.revision {
		return
	}
	s.keyRevision = make(map[string]int64, len(kvs))
	for _, kv := range kvs {
		s.keyRevision[string(kv.Key)] = kv.ModRevision
	}
	s.revision = revision
}

func (s *storage) Count() int {
	s.mux.RLock()
	defer s.mux.RUnlock()
	return len(s.keyRevision)
}

func (s *storage) PickRandom() (key string, rev int64) {
	s.mux.RLock()
	defer s.mux.RUnlock()
	n := rand.Intn(len(s.keyRevision))
	i := 0
	for k, v := range s.keyRevision {
		if i == n {
			return k, v
		}
		i++
	}
	return "", 0
}
Repository: etcd-io/etcd
File: tests/robustness/traffic/etcd.go (Go)

Code before:
			choices := t.requests
			if shouldReturn = nonUniqueWriteLimiter.Take(); !shouldReturn {
				choices = filterOutNonUniqueEtcdWrites(choices)
			}
			requestType = random.PickRandom(choices)
		} else {
			requestType = Get
		}
		rev, err := client.Request(ctx, requestType, lastRev)
		if shouldReturn {
			nonUniqueWriteLimiter.Return()
		}
		lastOperationSucceeded = err == nil
		if err != nil {
			continue
		}
		if rev != 0 {
			lastRev = rev
		}
		limiter.Wait(ctx)
	}
}

func (t etcdTraffic) RunCompactLoop(ctx context.Context, c *client.RecordingClient, period time.Duration, finish <-chan struct{}) {
	var lastRev int64 = 2
	timer := time.NewTimer(period)
	for {
		select {
		case <-ctx.Done():
			return
		case <-finish:
			return
		case <-timer.C:
		}
		timer.Reset(period)
		statusCtx, cancel := context.WithTimeout(ctx, RequestTimeout)
		resp, err := c.Status(statusCtx, c.Endpoints()[0])
		cancel()
		if err != nil {
			continue
		}

		// Range allows for both revision has been compacted and future revision errors
		compactRev := random.RandRange(lastRev, resp.Header.Revision+5)
		_, err = c.Compact(ctx, compactRev)
		if err != nil {
			continue
		}
		lastRev = compactRev
	}
}

Review comment (suggestion):

```suggestion
	timer := time.NewTimer(period)
	defer timer.Stop()
```

Code after:
			choices := t.requests
			if shouldReturn = nonUniqueWriteLimiter.Take(); !shouldReturn {
				choices = filterOutNonUniqueEtcdWrites(choices)
			}
			requestType = random.PickRandom(choices)
		} else {
			requestType = Get
		}
		rev, err := client.Request(ctx, requestType, lastRev)
		if shouldReturn {
			nonUniqueWriteLimiter.Return()
		}
		lastOperationSucceeded = err == nil
		if err != nil {
			continue
		}
		if rev != 0 {
			lastRev = rev
		}
		limiter.Wait(ctx)
	}
}

func (t etcdTraffic) RunCompactLoop(ctx context.Context, c *client.RecordingClient, period time.Duration, finish <-chan struct{}) {
	var lastRev int64 = 2
	ticker := time.NewTicker(period)
	defer ticker.Stop()
	for {
		select {
		case <-ctx.Done():
			return
		case <-finish:
			return
		case <-ticker.C:
		}
		statusCtx, cancel := context.WithTimeout(ctx, RequestTimeout)
		resp, err := c.Status(statusCtx, c.Endpoints()[0])
		cancel()
		if err != nil {
			continue
		}

		// Range allows for both revision has been compacted and future revision errors
		compactRev := random.RandRange(lastRev, resp.Header.Revision+5)
		_, err = c.Compact(ctx, compactRev)
		if err != nil {
			continue
		}
		lastRev = compactRev
	}
}