ronantakizawa/codereview-bench huggingface dataset:
Repository: etcd-io/etcd
File: tests/integration/cache_test.go (Go)

Code before:
	}
	if err := c.WaitForRevision(ctx, putResp.Header.Revision); err != nil {
		t.Fatalf("cache never caught up to rev %d: %v", putResp.Header.Revision, err)
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			resp, err := c.Get(ctx, tc.key, tc.opts...)
			if tc.expectError {
				if !errors.Is(err, cache.ErrKeyRangeInvalid) {
					t.Fatalf("expected ErrKeyRangeInvalid for Get %q, got: %v", tc.key, err)
				}
				return
			}
			if err != nil {
				t.Fatalf("Get %q failed: %v", tc.key, err)
			}
			if len(resp.Kvs) == 0 {
				t.Fatalf("Get %q returned no KVs, expected at least one", tc.key)
			}
		})
	}
}

func TestCacheGetAtRevisionBeyondAppliedRev(t *testing.T) {
	integration.BeforeTest(t)
	clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 1})
	t.Cleanup(func() { clus.Terminate(t) })
	client := clus.Client(0)
	ctx := t.Context()

	c, err := cache.New(client, "/foo")
	if err != nil {
		t.Fatalf("cache.New: %v", err)
	}
	t.Cleanup(c.Close)
	if err = c.WaitReady(ctx); err != nil {
		t.Fatalf("cache.WaitReady: %v", err)
	}

	put1, putErr1 := client.Put(ctx, "/foo/a", "v1")
	if putErr1 != nil {
		t.Fatalf("Put(/foo/a): %v", putErr1)
	}
	if waitErr := c.WaitForRevision(ctx, put1.Header.Revision); waitErr != nil {
		t.Fatalf("cache never caught up to rev %d: %v", put1.Header.Revision, waitErr)
	}
	applied := put1.Header.Revision

	var lastRev int64

Review comment (performance):
I don't understand the reason for new tests, we have existing scenario `TestCacheWithPrefixGet` that needs to be expanded.

Code after:
			t.Fatalf("cache.WaitReady: %v", err)
		}
		return c
	})
}

func TestWithPrefixGet(t *testing.T) {
	integration.BeforeTest(t)
	clus := integration.NewCluster(t, &integration.ClusterConfig{Size: 1})
	t.Cleanup(func() { clus.Terminate(t) })
	cli := clus.Client(0)

	testWithPrefixGet(t, cli, func() Getter { return cli.KV })
}

func testWithPrefixGet(t *testing.T, cli *clientv3.Client, getReader func() Getter) {
	ctx := t.Context()
	seedResp, err := cli.Put(ctx, "/foo/a", "val")
	if err != nil {
		t.Fatalf("seed put: %v", err)
	}
	seedRev := seedResp.Header.Revision

	reader := getReader()

	var latestRev int64
	for i := 0; i < 5; i++ {
		r, err := cli.Put(ctx, fmt.Sprintf("/bar/x%d", i), fmt.Sprintf("%d", i))
		if err != nil {
			t.Fatalf("advance put: %v", err)
		}
		latestRev = r.Header.Revision
	}

	if err := cli.RequestProgress(ctx); err != nil {
		t.Fatalf("RequestProgress: %v", err)
	}

	if c, ok := reader.(*cache.Cache); ok {
		if err := c.WaitForRevision(ctx, latestRev); err != nil {
			t.Fatalf("cache didn’t observe progress to rev %d: %v", latestRev, err)
		}
	}

	expectedFooA := &mvccpb.KeyValue{
		Key:            []byte("/foo/a"),
		Value:          []byte("val"),
		CreateRevision: seedRev,
		ModRevision:    seedRev,
		Version:        1,
	}
Repository: etcd-io/etcd
File: cache/demux.go (Go)

Code before:
		return
	}

	// Special case: 0 means “newest”.
	if startingRev == 0 {
		startingRev = latestRev + 1
	}

	if startingRev <= latestRev {
		d.laggingWatchers[w] = startingRev
	} else {
		d.activeWatchers[w] = startingRev
	}
}

func (d *demux) Unregister(w *watcher) {
	func() {
		d.mu.Lock()
		defer d.mu.Unlock()
		delete(d.activeWatchers, w)
		delete(d.laggingWatchers, w)
	}()
	w.Stop()
}

func (d *demux) Broadcast(resp clientv3.WatchResponse) {
	if resp.IsProgressNotify() {
		d.mu.Lock()
		if resp.Header.Revision > d.latestRev {
			d.latestRev = resp.Header.Revision
		}
		d.mu.Unlock()
		return
	}

	events := resp.Events
	if len(events) == 0 {
		return
	}

	d.mu.Lock()
	defer d.mu.Unlock()

	batchStart := 0
	for end := 1; end < len(events); end++ {
		if events[end].Kv.ModRevision != events[batchStart].Kv.ModRevision {
			if end > batchStart {
				d.history.Append(events[batchStart:end])
			}
			batchStart = end
		}

Review comment (refactor):
Would be good to refactor this function into two subfunctions:
* updateStoreLocked
* broadcastLocked

That's something for a separate PR.

Code after:
			d.activeWatchers[w] = 0
		} else {
			d.laggingWatchers[w] = startingRev
		}
		return
	}

	// Special case: 0 means “newest”.
	if startingRev == 0 {
		startingRev = d.maxRev + 1
	}

	if startingRev <= d.maxRev {
		d.laggingWatchers[w] = startingRev
	} else {
		d.activeWatchers[w] = startingRev
	}
}

func (d *demux) Unregister(w *watcher) {
	func() {
		d.mu.Lock()
		defer d.mu.Unlock()
		delete(d.activeWatchers, w)
		delete(d.laggingWatchers, w)
	}()
	w.Stop()
}

func (d *demux) Init(minRev int64) {
	d.mu.Lock()
	defer d.mu.Unlock()
	if minRev == 0 {
		return
	}
	if d.minRev == 0 {
		// Watch started for empty demux
		d.minRev = minRev
		return
	}
	if d.maxRev == 0 {
		// Watch started on initialized demux that never got any event.
		d.purge()
		d.minRev = minRev
		return
	}
	if minRev == d.maxRev+1 {
		// Watch continuing from last revision it observed.
		return
	}
	// Watch opened on revision mismatching dmux last observed revision.
Repository: etcd-io/etcd
File: cache/cache.go (Go)

Code before:

	if _, err := c.validateGet(key, op); err != nil {
		return nil, err
	}

	readRev, headerRev, err := c.resolveRevisions(op.Rev())
	if err != nil {
		return nil, err
	}

	startKey := []byte(key)
	endKey := op.RangeBytes()

	kvs, _, err := c.store.Get(startKey, endKey, readRev)
	if err != nil {
		return nil, err
	}

	return &clientv3.GetResponse{
		Header: &pb.ResponseHeader{Revision: headerRev},
		Kvs:    kvs,
		Count:  int64(len(kvs)),
	}, nil
}

func (c *Cache) resolveRevisions(requestedRev int64) (readRev, headerRev int64, err error) {
	latestSeenRev := c.demux.LatestRev()
	appliedRev := c.store.LatestRev()

	if !c.Ready() || latestSeenRev == 0 { // serving reads from preserved store data during rebuilding
		if requestedRev == 0 {
			return appliedRev, appliedRev, nil
		}
		if requestedRev > appliedRev {
			return 0, 0, rpctypes.ErrFutureRev
		}
		return requestedRev, appliedRev, nil
	}

	targetRev := requestedRev
	if requestedRev == 0 {
		targetRev = max(latestSeenRev, appliedRev)
	}
	if targetRev > latestSeenRev {
		return 0, 0, rpctypes.ErrFutureRev
	}

	readRev = min(targetRev, appliedRev)
	headerRev = max(latestSeenRev, appliedRev)

	return readRev, headerRev, nil

Review comment (suggestion):
I don't understand this code at all. We never discussed this, you never asked how to implement it. I don't think it makes any sense. Please stop writing random code, first start from understanding what is your problem, writing it down in a issue/on chat, considering different solutions and let's get agreement.

Code after:
	if _, err := c.validateGet(key, op); err != nil {
		return nil, err
	}

	startKey := []byte(key)
	endKey := op.RangeBytes()
	requestedRev := op.Rev()

	kvs, latestRev, err := c.store.Get(startKey, endKey, requestedRev)
	if err != nil {
		return nil, err
	}

	return &clientv3.GetResponse{
		Header: &pb.ResponseHeader{Revision: latestRev},
		Kvs:    kvs,
		Count:  int64(len(kvs)),
	}, nil
}

// Ready returns true if the snapshot has been loaded and the first watch has been confirmed.
func (c *Cache) Ready() bool {
	return c.ready.Ready()
}

// WaitReady blocks until the cache is ready or the ctx is cancelled.
func (c *Cache) WaitReady(ctx context.Context) error {
	return c.ready.WaitReady(ctx)
}

func (c *Cache) WaitForRevision(ctx context.Context, rev int64) error {
	for {
		if c.store.LatestRev() >= rev {
			return nil
		}
		select {
		case <-time.After(10 * time.Millisecond):
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}

// Close cancels the private context and blocks until all goroutines return.
func (c *Cache) Close() {
	c.stop()
	c.waitGroup.Wait()
}

func (c *Cache) getWatchLoop() {
	cfg := defaultConfig()
Repository: etcd-io/etcd
File: cache/demux.go (Go)

Code before:
func (d *demux) updateStoreLocked(resp clientv3.WatchResponse) {
	if resp.IsProgressNotify() {
		d.maxRev = resp.Header.Revision
		return
	}
	if len(resp.Events) == 0 {
		return
	}
	events := resp.Events
	batchStart := 0
	for end := 1; end < len(events); end++ {
		if events[end].Kv.ModRevision != events[batchStart].Kv.ModRevision {
			if end > batchStart {
				if end+1 == len(events) && d.history.full() {
					d.minRev = d.history.PeekOldest() + 1
				}
				d.history.Append(events[batchStart:end])
			}
			batchStart = end
		}
	}
	if batchStart < len(events) {
		if d.history.full() {
			d.minRev = d.history.PeekOldest() + 1
		}
		d.history.Append(events[batchStart:])
	}
	d.maxRev = events[len(events)-1].Kv.ModRevision
}

func (d *demux) broadcastLocked(resp clientv3.WatchResponse) {
	if resp.IsProgressNotify() {
		for w, nextRev := range d.activeWatchers {
			if nextRev >= resp.Header.Revision {
				continue
			}
			if !w.enqueueResponse(clientv3.WatchResponse{
				Header: etcdserverpb.ResponseHeader{
					Revision: resp.Header.Revision,
				},
			}) { // overflow → lagging
				d.laggingWatchers[w] = nextRev
				delete(d.activeWatchers, w)
			} else {
				d.activeWatchers[w] = resp.Header.Revision + 1
			}
		}
		return
	}
	if len(resp.Events) == 0 {
		return

Review comment (suggestion):
I don't remember why I removed it, but now I'm thinking it might not be safe to do so. At least without more consideration.

Code after:

func (d *demux) LatestRev() int64 {
	d.mu.RLock()
	defer d.mu.RUnlock()
	return d.maxRev
}

func (d *demux) updateStoreLocked(resp clientv3.WatchResponse) {
	if resp.IsProgressNotify() {
		d.maxRev = resp.Header.Revision
		return
	}
	if len(resp.Events) == 0 {
		return
	}
	events := resp.Events
	batchStart := 0
	for end := 1; end < len(events); end++ {
		if events[end].Kv.ModRevision != events[batchStart].Kv.ModRevision {
			if end > batchStart {
				if end+1 == len(events) && d.history.full() {
					d.minRev = d.history.PeekOldest() + 1
				}
				d.history.Append(events[batchStart:end])
			}
			batchStart = end
		}
	}
	if batchStart < len(events) {
		if d.history.full() {
			d.minRev = d.history.PeekOldest() + 1
		}
		d.history.Append(events[batchStart:])
	}
	d.maxRev = events[len(events)-1].Kv.ModRevision
}

func (d *demux) broadcastLocked(resp clientv3.WatchResponse) {
	switch {
	case resp.IsProgressNotify():
		d.broadcastProgressLocked(resp.Header.Revision)
	case len(resp.Events) != 0:
		d.broadcastEventsLocked(resp.Events)
	default:
	}
}

func (d *demux) broadcastProgressLocked(progressRev int64) {
	for w, nextRev := range d.activeWatchers {
		if nextRev >= progressRev {
			continue
Repository: etcd-io/etcd
File: cache/demux.go (Go)

Code before:
			if end > batchStart {
				if end+1 == len(events) && d.history.full() {
					d.minRev = d.history.PeekOldest() + 1
				}
				d.history.Append(events[batchStart:end])
			}
			batchStart = end
		}
	}
	if batchStart < len(events) {
		if d.history.full() {
			d.minRev = d.history.PeekOldest() + 1
		}
		d.history.Append(events[batchStart:])
	}
	d.maxRev = events[len(events)-1].Kv.ModRevision
}

func (d *demux) broadcastLocked(resp clientv3.WatchResponse) {
	if resp.IsProgressNotify() {
		for w, nextRev := range d.activeWatchers {
			if nextRev >= resp.Header.Revision {
				continue
			}
			if !w.enqueueResponse(clientv3.WatchResponse{
				Header: etcdserverpb.ResponseHeader{
					Revision: resp.Header.Revision,
				},
			}) { // overflow → lagging
				d.laggingWatchers[w] = nextRev
				delete(d.activeWatchers, w)
			} else {
				d.activeWatchers[w] = resp.Header.Revision + 1
			}
		}
		return
	}
	if len(resp.Events) == 0 {
		return
	}

	events := resp.Events
	lastRev := events[len(events)-1].Kv.ModRevision
	for w, nextRev := range d.activeWatchers {
		sendStart := len(events)
		for i, ev := range events {
			if ev.Kv.ModRevision >= nextRev {
				sendStart = i
				break
			}
		}

Review comment (suggestion):

Note for readability. To make control flow easier to follow I would recomend to structure the function the following way:
```
func (d *demux) broadcastLocked(resp clientv3.WatchResponse) {
	switch {
	case resp.IsProgressNotify():
			d.broadcastProgressLocked(resp.Header.Revision)
	case len(resp.Events) != 0:
			d.broadcastEventsLocked(resp.Events)
	default:
	}
}
```

Code after:
	if len(resp.Events) == 0 {
		return
	}
	events := resp.Events
	batchStart := 0
	for end := 1; end < len(events); end++ {
		if events[end].Kv.ModRevision != events[batchStart].Kv.ModRevision {
			if end > batchStart {
				if end+1 == len(events) && d.history.full() {
					d.minRev = d.history.PeekOldest() + 1
				}
				d.history.Append(events[batchStart:end])
			}
			batchStart = end
		}
	}
	if batchStart < len(events) {
		if d.history.full() {
			d.minRev = d.history.PeekOldest() + 1
		}
		d.history.Append(events[batchStart:])
	}
	d.maxRev = events[len(events)-1].Kv.ModRevision
}

func (d *demux) broadcastLocked(resp clientv3.WatchResponse) {
	switch {
	case resp.IsProgressNotify():
		d.broadcastProgressLocked(resp.Header.Revision)
	case len(resp.Events) != 0:
		d.broadcastEventsLocked(resp.Events)
	default:
	}
}

func (d *demux) broadcastProgressLocked(progressRev int64) {
	for w, nextRev := range d.activeWatchers {
		if nextRev >= progressRev {
			continue
		}
		resp := clientv3.WatchResponse{
			Header: etcdserverpb.ResponseHeader{
				Revision: progressRev,
			},
		}
		if w.enqueueResponse(resp) {
			d.activeWatchers[w] = progressRev + 1
		}
	}
}
Repository: etcd-io/etcd
File: cache/demux.go (Go)

Code before:
		w.Stop()
	}
	for w := range d.laggingWatchers {
		w.Stop()
	}
	d.activeWatchers = make(map[*watcher]int64)
	d.laggingWatchers = make(map[*watcher]int64)
}

// Compact is called when etcd reports a compaction at compactRev to rebase history;
// it keeps provably-too-old watchers for later cancellation, stops others, and clients should resubscribe.
func (d *demux) Compact(compactRev int64) {
	d.mu.Lock()
	defer d.mu.Unlock()
	d.purge()
}

func (d *demux) resyncLaggingWatchers() {
	d.mu.Lock()
	defer d.mu.Unlock()

	if d.minRev == 0 {
		return
	}
	// If truly nothing happen yet, we can continue to unstick laggers via progress
	if d.history.PeekOldest() == 0 && d.maxRev == 0 {
		return
	}

	for w, nextRev := range d.laggingWatchers {
		if nextRev < d.minRev {
			w.Compact(nextRev)
			delete(d.laggingWatchers, w)
			continue
		}
		// TODO: re-enable key‐predicate in Filter when non‐zero startRev or performance tuning is needed
		enqueueFailed := false
		d.history.AscendGreaterOrEqual(nextRev, func(rev int64, eventBatch []*clientv3.Event) bool {
			if !w.enqueueResponse(clientv3.WatchResponse{
				Events: eventBatch,
			}) { // buffer overflow: watcher still lagging
				enqueueFailed = true
				return false
			}
			nextRev = rev + 1
			return true
		})
		// Send progress to just resync.
		if !enqueueFailed && d.maxRev > nextRev {
			if w.enqueueResponse(clientv3.WatchResponse{
				Header: etcdserverpb.ResponseHeader{Revision: d.maxRev},

Review comment (suggestion):
```suggestion
	if d.minRev == 0 && d.maxRev == 0 {
```

Code after:
			d.laggingWatchers[w] = nextRev
			delete(d.activeWatchers, w)
		} else {
			d.activeWatchers[w] = lastRev + 1
		}
	}
}

// Purge stops all watchers and rebase history on watch errors
func (d *demux) Purge() {
	d.mu.Lock()
	defer d.mu.Unlock()
	d.purge()
}

func (d *demux) purge() {
	d.maxRev = 0
	d.minRev = 0
	d.history.RebaseHistory()
	for w := range d.activeWatchers {
		w.Stop()
	}
	for w := range d.laggingWatchers {
		w.Stop()
	}
	d.activeWatchers = make(map[*watcher]int64)
	d.laggingWatchers = make(map[*watcher]int64)
}

// Compact is called when etcd reports a compaction at compactRev to rebase history;
// it keeps provably-too-old watchers for later cancellation, stops others, and clients should resubscribe.
func (d *demux) Compact(compactRev int64) {
	d.mu.Lock()
	defer d.mu.Unlock()
	d.purge()
}

func (d *demux) resyncLaggingWatchers() {
	d.mu.Lock()
	defer d.mu.Unlock()

	if d.minRev == 0 {
		return
	}

	for w, nextRev := range d.laggingWatchers {
		if nextRev < d.minRev {
			w.Compact(nextRev)
			delete(d.laggingWatchers, w)
			continue
		}
Repository: etcd-io/etcd
File: cache/store.go (Go)

Code before:
		targetSnapshot = snap
		return false
	})
	// If s.history < rev < s.latest.rev serve latest.
	if targetSnapshot == nil {
		targetSnapshot = &s.latest
	}

	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(resp clientv3.WatchResponse) error {
	if resp.Canceled {
		return errors.New("canceled")
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if err := validateRevisions(resp, s.latest.rev); err != nil {
		return err
	}
	if resp.IsProgressNotify() {
		if s.latest.rev == 0 {
			return nil
		}
		s.latest.rev = resp.Header.Revision
		return nil
	}
	if len(resp.Events) == 0 {
		return nil
	}

	events := resp.Events

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

		for i < len(events) && events[i].Kv.ModRevision == rev {

Review comment (suggestion):
Ditto like in broadcast. 

```
func (s *store) Apply(resp clientv3.WatchResponse) error {
	if resp.Canceled {
		return errors.New("canceled")
	}
	s.mu.Lock()
	defer s.mu.Unlock()
	if err := validateRevisions(resp, s.latest.rev); err != nil {
		return err
	}
	switch {
	case resp.IsProgressNotify():
		s.applyProgressNotifyLocked(resp.Header.Revision)
	case len(resp.Events) != 0:
		s.applyEventsLocked(resp.Events)
	default:
	}
} 
```

Code after:
		targetSnapshot = snap
		return false
	})
	// If s.history < rev < s.latest.rev serve latest.
	if targetSnapshot == nil {
		targetSnapshot = &s.latest
	}

	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(resp clientv3.WatchResponse) error {
	if resp.Canceled {
		return errors.New("canceled")
	}

	s.mu.Lock()
	defer s.mu.Unlock()
	if err := validateRevisions(resp, s.latest.rev); err != nil {
		return err
	}

	switch {
	case resp.IsProgressNotify():
		s.applyProgressNotifyLocked(resp.Header.Revision)
		return nil
	case len(resp.Events) != 0:
		return s.applyEventsLocked(resp.Events)
	default:
		return nil
	}
}

func (s *store) applyProgressNotifyLocked(revision int64) {
	if s.latest.rev == 0 {
		return
	}
Repository: etcd-io/etcd
File: cache/demux.go (Go)

Code before:
	defer d.mu.Unlock()
	if d.minRev == 0 {
		// Watch started for empty demux
		d.minRev = minRev
		return
	}
	if d.maxRev == 0 {
		// Watch started on initialized demux that never got any event.
		d.purge()
		d.minRev = minRev
		return
	}
	if minRev == d.maxRev+1 {
		// Watch continuing from last revision it observed.
		return
	}
	// Watch opened on revision mismatching dmux last observed revision.
	d.purge()
	d.minRev = minRev
}

func (d *demux) Broadcast(resp clientv3.WatchResponse) error {
	d.mu.Lock()
	defer d.mu.Unlock()
	err := validateRevisions(resp, d.maxRev)
	if err != nil {
		return err
	}
	d.updateStoreLocked(resp)
	d.broadcastLocked(resp)
	return nil
}

func (d *demux) LatestRev() int64 {
	d.mu.RLock()
	defer d.mu.RUnlock()
	return d.maxRev
}

func (d *demux) updateStoreLocked(resp clientv3.WatchResponse) {
	if resp.IsProgressNotify() {
		d.maxRev = resp.Header.Revision
		return
	}
	if len(resp.Events) == 0 {
		return
	}
	events := resp.Events
	batchStart := 0
	for end := 1; end < len(events); end++ {
		if events[end].Kv.ModRevision != events[batchStart].Kv.ModRevision {

Review comment (suggestion):
Maybe add a safeguard that Broadcast can only called after `minRev` is set. Error if not.

Code after:
	d.mu.Lock()
	defer d.mu.Unlock()
	if minRev == 0 {
		return
	}
	if d.minRev == 0 {
		// Watch started for empty demux
		d.minRev = minRev
		return
	}
	if d.maxRev == 0 {
		// Watch started on initialized demux that never got any event.
		d.purge()
		d.minRev = minRev
		return
	}
	if minRev == d.maxRev+1 {
		// Watch continuing from last revision it observed.
		return
	}
	// Watch opened on revision mismatching dmux last observed revision.
	d.purge()
	d.minRev = minRev
}

func (d *demux) Broadcast(resp clientv3.WatchResponse) error {
	d.mu.Lock()
	defer d.mu.Unlock()
	if d.minRev == 0 {
		return errors.New("demux: not initialized")
	}
	err := validateRevisions(resp, d.maxRev)
	if err != nil {
		return err
	}
	d.updateStoreLocked(resp)
	d.broadcastLocked(resp)
	return nil
}

func (d *demux) LatestRev() int64 {
	d.mu.RLock()
	defer d.mu.RUnlock()
	return d.maxRev
}

func (d *demux) updateStoreLocked(resp clientv3.WatchResponse) {
	if resp.IsProgressNotify() {
		d.maxRev = resp.Header.Revision
		return
	}
Repository: etcd-io/etcd
File: cache/demux.go (Go)

Code before:
	}
	d.maxRev = events[len(events)-1].Kv.ModRevision
}

func (d *demux) broadcastLocked(resp clientv3.WatchResponse) {
	switch {
	case resp.IsProgressNotify():
		d.broadcastProgressLocked(resp.Header.Revision)
	case len(resp.Events) != 0:
		d.broadcastEventsLocked(resp.Events)
	default:
	}
}

func (d *demux) broadcastProgressLocked(progressRev int64) {
	for w, nextRev := range d.activeWatchers {
		if nextRev >= progressRev {
			continue
		}
		if !w.enqueueResponse(clientv3.WatchResponse{
			Header: etcdserverpb.ResponseHeader{
				Revision: progressRev,
			},
		}) {
			d.activeWatchers[w] = progressRev + 1
		}
	}
}

func (d *demux) broadcastEventsLocked(events []*clientv3.Event) {
	firstRev := events[0].Kv.ModRevision
	lastRev := events[len(events)-1].Kv.ModRevision

	for w, nextRev := range d.activeWatchers {
		if nextRev != 0 && firstRev > nextRev {
			d.laggingWatchers[w] = nextRev
			delete(d.activeWatchers, w)
			continue
		}

		sendStart := len(events)
		for i, ev := range events {
			if ev.Kv.ModRevision >= nextRev {
				sendStart = i
				break
			}
		}

		if sendStart == len(events) {
			continue
		}

Review comment (suggestion):
```suggestion
		resp := clientv3.WatchResponse{
			Header: etcdserverpb.ResponseHeader{
				Revision: progressRev,
			},
		}
		if w.enqueueResponse(resp) {
			d.activeWatchers[w] = progressRev + 1
		}
```

Code after:
		}
	}
	if batchStart < len(events) {
		if d.history.full() {
			d.minRev = d.history.PeekOldest() + 1
		}
		d.history.Append(events[batchStart:])
	}
	d.maxRev = events[len(events)-1].Kv.ModRevision
}

func (d *demux) broadcastLocked(resp clientv3.WatchResponse) {
	switch {
	case resp.IsProgressNotify():
		d.broadcastProgressLocked(resp.Header.Revision)
	case len(resp.Events) != 0:
		d.broadcastEventsLocked(resp.Events)
	default:
	}
}

func (d *demux) broadcastProgressLocked(progressRev int64) {
	for w, nextRev := range d.activeWatchers {
		if nextRev >= progressRev {
			continue
		}
		resp := clientv3.WatchResponse{
			Header: etcdserverpb.ResponseHeader{
				Revision: progressRev,
			},
		}
		if w.enqueueResponse(resp) {
			d.activeWatchers[w] = progressRev + 1
		}
	}
}

func (d *demux) broadcastEventsLocked(events []*clientv3.Event) {
	firstRev := events[0].Kv.ModRevision
	lastRev := events[len(events)-1].Kv.ModRevision

	for w, nextRev := range d.activeWatchers {
		if nextRev != 0 && firstRev > nextRev {
			d.laggingWatchers[w] = nextRev
			delete(d.activeWatchers, w)
			continue
		}

		sendStart := len(events)
		for i, ev := range events {
			if ev.Kv.ModRevision >= nextRev {