ronantakizawa/codereview-bench huggingface dataset:
Repository: etcd-io/etcd
File: tests/robustness/coverage/key_pattern_test.go (Go)

Code before:
package coverage_test

import (
	"strings"
	"testing"
)

func pattern(k string) (string, bool) {
	if k == "/registry/health" || k == "compact_rev_key" {
		return k, true
	}
	k, valid := strings.CutPrefix(k, "/registry")
	if !valid {
		return k, false
	}
	slash := ""
	if strings.HasSuffix(k, "/") {
		slash = "/"
	}
	s := strings.Split(strings.Trim(k, "/"), "/")
	if len(s[0]) == 0 {
		return k, false
	}

	resource, shift := resourceOrCRD(s[0])
	s = s[shift:]

	if len(s) == 0 {
		// Listing all resources.
		return "/registry/" + resource + slash, true
	}
	if len(s) == 1 && slash == "" {
		// Get on a non-namespaced resource.
		return "/registry/" + resource + "/{name}", true
	}
	if len(s) == 1 {
		// Listing all resources in a namespace.
		return "/registry/" + resource + "/{namespace}" + slash, true
	}
	if len(s) == 2 && slash == "" {
		// Get on a namespaced resource.
		return "/registry/" + resource + "/{namespace}/{name}", true
	}

	return k, false
}

func resourceOrCRD(s string) (string, int) {
	if strings.Contains(s, ".") {
		// CRD
		return "{api-group}/{resource}", 2

Review comment (suggestion):
Maybe set the name based on what it can contain. I think `namespaceName` is more clear and accurate than `s`, because `s` here was changed.

Code after:
package coverage_test

import (
	"strings"
	"testing"
)

func pattern(key string) (string, bool) {
	if key == "/registry/health" || key == "compact_rev_key" {
		return key, true
	}
	key, valid := strings.CutPrefix(key, "/registry")
	if !valid {
		return key, false
	}
	slash := ""
	if strings.HasSuffix(key, "/") {
		slash = "/"
	}
	parts := strings.Split(strings.Trim(key, "/"), "/")
	if len(parts[0]) == 0 {
		return key, false
	}

	apiResource, shift := resourceOrCRD(parts[0])
	parts = parts[shift:]

	switch len(parts) {
	case 0:
		// Listing all resources.
		return "/registry/" + apiResource + slash, true
	case 1:
		if slash == "" {
			// Get on a non-namespaced resource.
			return "/registry/" + apiResource + "/{name}", true
		}
		// Listing all resources in a namespace.
		return "/registry/" + apiResource + "/{namespace}" + slash, true
	case 2:
		if slash == "" {
			// Get on a namespaced resource.
			return "/registry/" + apiResource + "/{namespace}/{name}", true
		}
	}

	return key, false
}

func resourceOrCRD(s string) (string, int) {
	if strings.Contains(s, ".") {
		// Group name from the Custom Resource Definition.
Repository: etcd-io/etcd
File: server/etcdserver/server.go (Go)

Code before:
// situation that EtcdServer::Start was not called (that takes care of cleanup).
func (s *EtcdServer) Cleanup() {
	// kv, lessor and backend can be nil if running without v3 enabled
	// or running unit tests.
	if s.lessor != nil {
		s.lessor.Stop()
	}
	if s.kv != nil {
		s.kv.Close()
	}
	if s.authStore != nil {
		s.authStore.Close()
	}
	if s.be != nil {
		s.be.Close()
	}
	if s.compactor != nil {
		s.compactor.Stop()
	}
}

func (s *EtcdServer) Defragment() (err error) {
	s.bemu.Lock()
	defer s.bemu.Unlock()
	err = s.be.Defrag()
	return
}

func (s *EtcdServer) applyAll(ep *etcdProgress, apply *toApply) {
	s.applySnapshot(ep, apply)
	s.applyEntries(ep, apply)
	backend.VerifyBackendConsistency(s.Backend(), s.Logger(), true, schema.AllBuckets...)

	proposalsApplied.Set(float64(ep.appliedi))
	s.applyWait.Trigger(ep.appliedi)

	// wait for the raft routine to finish the disk writes before triggering a
	// snapshot. or applied index might be greater than the last index in raft
	// storage, since the raft routine might be slower than toApply routine.
	<-apply.notifyc

	s.snapshotIfNeededAndCompactRaftLog(ep)
	select {
	// snapshot requested via send()
	case m := <-s.r.msgSnapC:
		merged := s.createMergedSnapshotMessage(m, ep.appliedt, ep.appliedi, ep.confState)
		s.sendMergedSnap(merged)
	default:
	}
}


Review comment (suggestion):
```suggestion
func (s *EtcdServer) Defragment() error {
	s.bemu.Lock()
	defer s.bemu.Unlock()
	return s.be.Defrag()
}
```

Code after:
// situation that EtcdServer::Start was not called (that takes care of cleanup).
func (s *EtcdServer) Cleanup() {
	// kv, lessor and backend can be nil if running without v3 enabled
	// or running unit tests.
	if s.lessor != nil {
		s.lessor.Stop()
	}
	if s.kv != nil {
		s.kv.Close()
	}
	if s.authStore != nil {
		s.authStore.Close()
	}
	if s.be != nil {
		s.be.Close()
	}
	if s.compactor != nil {
		s.compactor.Stop()
	}
}

func (s *EtcdServer) Defragment() error {
	s.bemu.Lock()
	defer s.bemu.Unlock()
	return s.be.Defrag()
}

func (s *EtcdServer) applyAll(ep *etcdProgress, apply *toApply) {
	s.applySnapshot(ep, apply)
	s.applyEntries(ep, apply)
	backend.VerifyBackendConsistency(s.Backend(), s.Logger(), true, schema.AllBuckets...)

	proposalsApplied.Set(float64(ep.appliedi))
	s.applyWait.Trigger(ep.appliedi)

	// wait for the raft routine to finish the disk writes before triggering a
	// snapshot. or applied index might be greater than the last index in raft
	// storage, since the raft routine might be slower than toApply routine.
	<-apply.notifyc

	s.snapshotIfNeededAndCompactRaftLog(ep)
	select {
	// snapshot requested via send()
	case m := <-s.r.msgSnapC:
		merged := s.createMergedSnapshotMessage(m, ep.appliedt, ep.appliedi, ep.confState)
		s.sendMergedSnap(merged)
	default:
	}
}

func (s *EtcdServer) applySnapshot(ep *etcdProgress, toApply *toApply) {
Repository: etcd-io/etcd
File: cache/snapshot.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.

package cache

import (
	"github.com/google/btree"

	"go.etcd.io/etcd/api/v3/mvccpb"
)

// snapshot captures a full, point-in-time view of the KV state at rev.
type snapshot struct {
	rev  int64
	tree *btree.BTree
}

func newClonedSnapshot(rev int64, t *btree.BTree) *snapshot {
	return &snapshot{rev: rev, tree: t.Clone()}
}

func (s *snapshot) Get(startKey, endKey []byte) []*mvccpb.KeyValue {
	var out []*mvccpb.KeyValue
	switch {
	case len(endKey) == 0:
		if item := s.tree.Get(probeItemFromBytes(startKey)); item != nil {
			out = append(out, item.(*kvItem).kv)
		}
	case isPrefixScan(endKey):
		s.tree.AscendGreaterOrEqual(probeItemFromBytes(startKey), func(item btree.Item) bool {
			out = append(out, item.(*kvItem).kv)
			return true
		})
	default:
		s.tree.AscendRange(probeItemFromBytes(startKey), probeItemFromBytes(endKey), func(item btree.Item) bool {
			out = append(out, item.(*kvItem).kv)
			return true
		})
	}
	return out
}

func isPrefixScan(endKey []byte) bool {
	return len(endKey) == 1 && endKey[0] == 0
}

func probeItemFromBytes(b []byte) *kvItem { return &kvItem{key: string(b)} }

Review comment (suggestion):
```suggestion
func (s *snapshot) Range(startKey, endKey []byte) []*mvccpb.KeyValue {
```

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.

package cache

import (
	"github.com/google/btree"

	"go.etcd.io/etcd/api/v3/mvccpb"
)

// snapshot captures a full, point-in-time view of the KV state at rev.
type snapshot struct {
	rev  int64
	tree *btree.BTree
}

func newClonedSnapshot(rev int64, t *btree.BTree) *snapshot {
	return &snapshot{rev: rev, tree: t.Clone()}
}

func (s *snapshot) Range(startKey, endKey []byte) []*mvccpb.KeyValue {
	var out []*mvccpb.KeyValue
	switch {
	case len(endKey) == 0:
		if item := s.tree.Get(probeItemFromKey(startKey)); item != nil {
			out = append(out, item.(*kvItem).kv)
		}
	case isPrefixScan(endKey):
		s.tree.AscendGreaterOrEqual(probeItemFromKey(startKey), func(item btree.Item) bool {
			out = append(out, item.(*kvItem).kv)
			return true
		})
	default:
		s.tree.AscendRange(probeItemFromKey(startKey), probeItemFromKey(endKey), func(item btree.Item) bool {
			out = append(out, item.(*kvItem).kv)
			return true
		})
	}
	return out
}

func isPrefixScan(endKey []byte) bool {
	return len(endKey) == 1 && endKey[0] == 0
}

func probeItemFromKey(key []byte) *kvItem { return &kvItem{key: string(key)} }
Repository: etcd-io/etcd
File: cache/store.go (Go)

Code before:
	latestRev       int64
	snapshotHistory ringBuffer[*snapshot]
}

func newStore(degree int, historyCapacity int) *store {
	return &store{
		liveTree:        btree.New(degree),
		degree:          degree,
		snapshotHistory: *newRingBuffer(historyCapacity, func(s *snapshot) int64 { return s.rev }),
	}
}

type kvItem struct {
	key string
	kv  *mvccpb.KeyValue
}

func newKVItem(kv *mvccpb.KeyValue) *kvItem {
	return &kvItem{key: string(kv.Key), kv: kv}
}

func (a *kvItem) Less(b btree.Item) bool {
	return a.key < b.(*kvItem).key
}

func (s *store) Get(startKey, endKey []byte, requestedRev int64) ([]*mvccpb.KeyValue, int64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	if s.latestRev == 0 {
		return nil, 0, ErrNotReady
	}

	if requestedRev < 0 {
		return nil, 0, fmt.Errorf("invalid revision: %d", requestedRev)
	}

	latestRev := s.latestRev
	if requestedRev > latestRev {
		return nil, 0, rpctypes.ErrFutureRev
	}

	snap, err := s.findSnapshotForRevLocked(requestedRev)
	if err != nil {
		return nil, 0, err
	}

	return snap.Get(startKey, endKey), latestRev, nil
}

func (s *store) findSnapshotForRevLocked(requestedRev int64) (*snapshot, error) {

Review comment (suggestion):
```suggestion
func (s *store) Get(startKey, endKey []byte, rev int64) ([]*mvccpb.KeyValue, int64, error) {
```

You don't call `startKey` as `requestedStartKey` so rev should not be prefixed either.

Code after:
	history ringBuffer[*snapshot] // history stores immutable cloned snapshots
}

func newStore(degree int, historyCapacity int) *store {
	tree := btree.New(degree)
	return &store{
		degree:  degree,
		latest:  snapshot{rev: 0, tree: tree},
		history: *newRingBuffer(historyCapacity, func(s *snapshot) int64 { return s.rev }),
	}
}

type kvItem struct {
	key string
	kv  *mvccpb.KeyValue
}

func newKVItem(kv *mvccpb.KeyValue) *kvItem {
	return &kvItem{key: string(kv.Key), kv: kv}
}

func (a *kvItem) Less(b btree.Item) bool {
	return a.key < b.(*kvItem).key
}

func (s *store) Get(startKey, endKey []byte, rev int64) ([]*mvccpb.KeyValue, int64, error) {
	snapshot, latestRev, err := s.getSnapshot(rev)
	if err != nil {
		return nil, 0, err
	}
	return snapshot.Range(startKey, endKey), latestRev, nil
}

func (s *store) getSnapshot(rev int64) (*snapshot, int64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	if s.latest.rev == 0 {
		return nil, 0, ErrNotReady
	}
	if rev < 0 {
		return nil, 0, fmt.Errorf("invalid revision: %d", rev)
	}
	if rev == 0 {
		rev = s.latest.rev
	}
	if rev > s.latest.rev {
		return nil, 0, rpctypes.ErrFutureRev
	}
	oldestRev := s.history.PeekOldest()
	if rev < oldestRev {
Repository: etcd-io/etcd
File: cache/store.go (Go)

Code before:
	return a.key < b.(*kvItem).key
}

func (s *store) Get(startKey, endKey []byte, requestedRev int64) ([]*mvccpb.KeyValue, int64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	if s.latestRev == 0 {
		return nil, 0, ErrNotReady
	}

	if requestedRev < 0 {
		return nil, 0, fmt.Errorf("invalid revision: %d", requestedRev)
	}

	latestRev := s.latestRev
	if requestedRev > latestRev {
		return nil, 0, rpctypes.ErrFutureRev
	}

	snap, err := s.findSnapshotForRevLocked(requestedRev)
	if err != nil {
		return nil, 0, err
	}

	return snap.Get(startKey, endKey), latestRev, nil
}

func (s *store) findSnapshotForRevLocked(requestedRev int64) (*snapshot, error) {
	latestRev := s.latestRev
	oldestRev := s.snapshotHistory.PeekOldest()

	if requestedRev == 0 || requestedRev == latestRev {
		return &snapshot{rev: latestRev, tree: s.liveTree}, nil
	}

	if requestedRev < oldestRev {
		return nil, rpctypes.ErrCompacted
	}

	var targetSnapshot *snapshot
	s.snapshotHistory.AscendGreaterOrEqual(requestedRev, func(rev int64, snap *snapshot) bool {
		targetSnapshot = snap
		return false
	})

	return targetSnapshot, nil
}

// Restore replaces state with the bootstrap snapshot and resets history.
func (s *store) Restore(kvs []*mvccpb.KeyValue, rev int64) {

Review comment (refactor):
This get can be done outside of lock. I would recommend extracting function to get snapshot:
```
func (s *store) Get(startKey, endKey []byte, rev int64) ([]*mvccpb.KeyValue, int64, error) {
  snapshot, err := s.getSnapshot(rev)
  if err != nil {
    return nil, 0, err
  } 
  return snapshot.Get(startKey, endKey)
}

func (s *store) getSnapshot(rev int64) (*snapshot, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()
	...
	retutrn s.findSnapshotForRevLocked(requestedRev)
}
```

Code after:
	return a.key < b.(*kvItem).key
}

func (s *store) Get(startKey, endKey []byte, rev int64) ([]*mvccpb.KeyValue, int64, error) {
	snapshot, latestRev, err := s.getSnapshot(rev)
	if err != nil {
		return nil, 0, err
	}
	return snapshot.Range(startKey, endKey), latestRev, nil
}

func (s *store) getSnapshot(rev int64) (*snapshot, int64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	if s.latest.rev == 0 {
		return nil, 0, ErrNotReady
	}
	if rev < 0 {
		return nil, 0, fmt.Errorf("invalid revision: %d", rev)
	}
	if rev == 0 {
		rev = s.latest.rev
	}
	if rev > s.latest.rev {
		return nil, 0, rpctypes.ErrFutureRev
	}
	oldestRev := s.history.PeekOldest()
	if rev < oldestRev {
		return nil, 0, rpctypes.ErrCompacted
	}

	var targetSnapshot *snapshot
	s.history.AscendGreaterOrEqual(rev, func(rev int64, snap *snapshot) bool {
		targetSnapshot = snap
		return false
	})

	return targetSnapshot, s.latest.rev, nil
}

// Restore replaces state with the bootstrap snapshot and resets history.
func (s *store) Restore(kvs []*mvccpb.KeyValue, rev int64) {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.latest.tree = btree.New(s.degree)
	for _, kv := range kvs {
		s.latest.tree.ReplaceOrInsert(newKVItem(kv))
	}
	s.history.RebaseHistory()
Repository: etcd-io/etcd
File: cache/store.go (Go)

Code before:
// See the License for the specific language governing permissions and
// limitations under the License.

package cache

import (
	"fmt"
	"sync"

	"github.com/google/btree"

	"go.etcd.io/etcd/api/v3/mvccpb"
	"go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
	clientv3 "go.etcd.io/etcd/client/v3"
)

var ErrNotReady = fmt.Errorf("cache: store not ready")

// The store keeps a bounded history of snapshots using ringBuffer so that
// reads at historical revisions can be served until they fall out of the window.
type store struct {
	mu              sync.RWMutex
	liveTree        *btree.BTree
	degree          int
	latestRev       int64
	snapshotHistory ringBuffer[*snapshot]
}

func newStore(degree int, historyCapacity int) *store {
	return &store{
		liveTree:        btree.New(degree),
		degree:          degree,
		snapshotHistory: *newRingBuffer(historyCapacity, func(s *snapshot) int64 { return s.rev }),
	}
}

type kvItem struct {
	key string
	kv  *mvccpb.KeyValue
}

func newKVItem(kv *mvccpb.KeyValue) *kvItem {
	return &kvItem{key: string(kv.Key), kv: kv}
}

func (a *kvItem) Less(b btree.Item) bool {
	return a.key < b.(*kvItem).key
}

func (s *store) Get(startKey, endKey []byte, requestedRev int64) ([]*mvccpb.KeyValue, int64, error) {
	s.mu.RLock()

Review comment (suggestion):
```suggestion
	degree          int
	latest snapshot
	history ringBuffer[*snapshot]
```
Combination of tree and rev is what? A snapshot.

Code after:
// See the License for the specific language governing permissions and
// limitations under the License.

package cache

import (
	"fmt"
	"sync"

	"github.com/google/btree"

	"go.etcd.io/etcd/api/v3/mvccpb"
	"go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
	clientv3 "go.etcd.io/etcd/client/v3"
)

var ErrNotReady = fmt.Errorf("cache: store not ready")

// The store keeps a bounded history of snapshots using ringBuffer so that
// reads at historical revisions can be served until they fall out of the window.
type store struct {
	mu      sync.RWMutex
	degree  int
	latest  snapshot              // latest is the mutable working snapshot
	history ringBuffer[*snapshot] // history stores immutable cloned snapshots
}

func newStore(degree int, historyCapacity int) *store {
	tree := btree.New(degree)
	return &store{
		degree:  degree,
		latest:  snapshot{rev: 0, tree: tree},
		history: *newRingBuffer(historyCapacity, func(s *snapshot) int64 { return s.rev }),
	}
}

type kvItem struct {
	key string
	kv  *mvccpb.KeyValue
}

func newKVItem(kv *mvccpb.KeyValue) *kvItem {
	return &kvItem{key: string(kv.Key), kv: kv}
}

func (a *kvItem) Less(b btree.Item) bool {
	return a.key < b.(*kvItem).key
}

func (s *store) Get(startKey, endKey []byte, rev int64) ([]*mvccpb.KeyValue, int64, error) {
	snapshot, latestRev, err := s.getSnapshot(rev)
Repository: etcd-io/etcd
File: cache/store.go (Go)

Code before:
	defer s.mu.RUnlock()

	if s.latestRev == 0 {
		return nil, 0, ErrNotReady
	}

	if requestedRev < 0 {
		return nil, 0, fmt.Errorf("invalid revision: %d", requestedRev)
	}

	latestRev := s.latestRev
	if requestedRev > latestRev {
		return nil, 0, rpctypes.ErrFutureRev
	}

	snap, err := s.findSnapshotForRevLocked(requestedRev)
	if err != nil {
		return nil, 0, err
	}

	return snap.Get(startKey, endKey), latestRev, nil
}

func (s *store) findSnapshotForRevLocked(requestedRev int64) (*snapshot, error) {
	latestRev := s.latestRev
	oldestRev := s.snapshotHistory.PeekOldest()

	if requestedRev == 0 || requestedRev == latestRev {
		return &snapshot{rev: latestRev, tree: s.liveTree}, nil
	}

	if requestedRev < oldestRev {
		return nil, rpctypes.ErrCompacted
	}

	var targetSnapshot *snapshot
	s.snapshotHistory.AscendGreaterOrEqual(requestedRev, func(rev int64, snap *snapshot) bool {
		targetSnapshot = snap
		return false
	})

	return targetSnapshot, nil
}

// Restore replaces state with the bootstrap snapshot and resets history.
func (s *store) Restore(kvs []*mvccpb.KeyValue, rev int64) {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.liveTree = btree.New(s.degree)
	for _, kv := range kvs {

Review comment (suggestion):
No need to copy, avoid defining variables far from where they are used. It forces reader to browse more code to find definitions without giving any benefits. 

Code after:
	if err != nil {
		return nil, 0, err
	}
	return snapshot.Range(startKey, endKey), latestRev, nil
}

func (s *store) getSnapshot(rev int64) (*snapshot, int64, error) {
	s.mu.RLock()
	defer s.mu.RUnlock()

	if s.latest.rev == 0 {
		return nil, 0, ErrNotReady
	}
	if rev < 0 {
		return nil, 0, fmt.Errorf("invalid revision: %d", rev)
	}
	if rev == 0 {
		rev = s.latest.rev
	}
	if rev > s.latest.rev {
		return nil, 0, rpctypes.ErrFutureRev
	}
	oldestRev := s.history.PeekOldest()
	if rev < oldestRev {
		return nil, 0, rpctypes.ErrCompacted
	}

	var targetSnapshot *snapshot
	s.history.AscendGreaterOrEqual(rev, func(rev int64, snap *snapshot) bool {
		targetSnapshot = snap
		return false
	})

	return targetSnapshot, s.latest.rev, nil
}

// Restore replaces state with the bootstrap snapshot and resets history.
func (s *store) Restore(kvs []*mvccpb.KeyValue, rev int64) {
	s.mu.Lock()
	defer s.mu.Unlock()

	s.latest.tree = btree.New(s.degree)
	for _, kv := range kvs {
		s.latest.tree.ReplaceOrInsert(newKVItem(kv))
	}
	s.history.RebaseHistory()
	s.latest.rev = rev
	s.history.Append(newClonedSnapshot(rev, s.latest.tree))
}

func (s *store) Apply(events []*clientv3.Event) error {
Repository: etcd-io/etcd
File: cache/store.go (Go)

Code before:
	for _, kv := range kvs {
		s.liveTree.ReplaceOrInsert(newKVItem(kv))
	}
	s.snapshotHistory.RebaseHistory()
	s.latestRev = rev
	s.snapshotHistory.Append(newClonedSnapshot(rev, s.liveTree))
}

func (s *store) Apply(events []*clientv3.Event) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	if err := validateRevisions(events, s.latestRev); err != nil {
		return err
	}

	curRev := int64(0)
	workingTree := s.liveTree
	for i, ev := range events {
		rev := ev.Kv.ModRevision
		if curRev != 0 && rev != curRev {
			s.snapshotHistory.Append(newClonedSnapshot(curRev, workingTree))
		}
		curRev = rev

		switch ev.Type {
		case clientv3.EventTypeDelete:
			if removed := workingTree.Delete(&kvItem{key: string(ev.Kv.Key)}); removed == nil {
				return fmt.Errorf("cache: delete non-existent key %s", string(ev.Kv.Key))
			}
		case clientv3.EventTypePut:
			workingTree.ReplaceOrInsert(newKVItem(ev.Kv))
		}

		if i == len(events)-1 {
			s.snapshotHistory.Append(newClonedSnapshot(curRev, workingTree))
		}
	}

	s.liveTree = workingTree
	s.latestRev = curRev
	return nil
}

func (s *store) LatestRev() int64 {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.latestRev
}

func validateRevisions(events []*clientv3.Event, latestRev int64) error {

Review comment (suggestion):
```suggestion
	}
	if len(events) > 0 {
		s.snapshotHistory.Append(newClonedSnapshot(curRev, workingTree))
	}
```

Code after:
func (s *store) Apply(events []*clientv3.Event) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	if err := validateRevisions(events, s.latest.rev); err != nil {
		return err
	}

	for i := 0; i < len(events); {
		rev := events[i].Kv.ModRevision

		for i < len(events) && events[i].Kv.ModRevision == rev {
			ev := events[i]
			switch ev.Type {
			case clientv3.EventTypeDelete:
				if removed := s.latest.tree.Delete(&kvItem{key: string(ev.Kv.Key)}); removed == nil {
					return fmt.Errorf("cache: delete non-existent key %s", string(ev.Kv.Key))
				}
			case clientv3.EventTypePut:
				s.latest.tree.ReplaceOrInsert(newKVItem(ev.Kv))
			}
			i++
		}
		s.latest.rev = rev
		s.history.Append(newClonedSnapshot(rev, s.latest.tree))
	}
	return nil
}

func (s *store) LatestRev() int64 {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.latest.rev
}

func validateRevisions(events []*clientv3.Event, latestRev int64) error {
	if len(events) == 0 {
		return nil
	}
	for _, ev := range events {
		r := ev.Kv.ModRevision
		if r < latestRev {
			return fmt.Errorf("cache: stale event batch (rev %d < latest %d)", r, latestRev)
		}
		if r == latestRev {
			return fmt.Errorf("cache: duplicate revision batch breaks atomic guarantee (rev %d == latest %d)", r, latestRev)
		}
	}
	return nil
}
Repository: etcd-io/etcd
File: cache/snapshot.go (Go)

Code before:
func (s *snapshot) Range(startKey, endKey []byte) []*mvccpb.KeyValue {
	var out []*mvccpb.KeyValue
	switch {
	case len(endKey) == 0:
		if item := s.tree.Get(probeItemFromBytes(startKey)); item != nil {
			out = append(out, item.(*kvItem).kv)
		}
	case isPrefixScan(endKey):
		s.tree.AscendGreaterOrEqual(probeItemFromBytes(startKey), func(item btree.Item) bool {
			out = append(out, item.(*kvItem).kv)
			return true
		})
	default:
		s.tree.AscendRange(probeItemFromBytes(startKey), probeItemFromBytes(endKey), func(item btree.Item) bool {
			out = append(out, item.(*kvItem).kv)
			return true
		})
	}
	return out
}

func isPrefixScan(endKey []byte) bool {
	return len(endKey) == 1 && endKey[0] == 0
}

func probeItemFromBytes(b []byte) *kvItem { return &kvItem{key: string(b)} }


Review comment (suggestion):
```suggestion
func probeItemFromKey(key []byte) *kvItem { return &kvItem{key: string(key)} }
```

Code after:
func (s *snapshot) Range(startKey, endKey []byte) []*mvccpb.KeyValue {
	var out []*mvccpb.KeyValue
	switch {
	case len(endKey) == 0:
		if item := s.tree.Get(probeItemFromKey(startKey)); item != nil {
			out = append(out, item.(*kvItem).kv)
		}
	case isPrefixScan(endKey):
		s.tree.AscendGreaterOrEqual(probeItemFromKey(startKey), func(item btree.Item) bool {
			out = append(out, item.(*kvItem).kv)
			return true
		})
	default:
		s.tree.AscendRange(probeItemFromKey(startKey), probeItemFromKey(endKey), func(item btree.Item) bool {
			out = append(out, item.(*kvItem).kv)
			return true
		})
	}
	return out
}

func isPrefixScan(endKey []byte) bool {
	return len(endKey) == 1 && endKey[0] == 0
}

func probeItemFromKey(key []byte) *kvItem { return &kvItem{key: string(key)} }