Skip to content

Commit 0968300

Browse files
committed
retain order
Signed-off-by: Huabing Zhao <[email protected]>
1 parent ddc1785 commit 0968300

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

internal/message/watchutil.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,15 +117,21 @@ func coalesceUpdates[K comparable, V any](runner string, updates []watchable.Upd
117117
result := make([]watchable.Update[K, V], 0, len(updates))
118118
indexByKey := make(map[K]int, len(updates))
119119

120-
for _, update := range updates {
121-
if idx, ok := indexByKey[update.Key]; ok {
122-
result[idx] = update
120+
for i := len(updates) - 1; i >= 0; i-- {
121+
update := updates[i]
122+
if _, ok := indexByKey[update.Key]; ok {
123123
continue
124124
}
125+
125126
indexByKey[update.Key] = len(result)
126127
result = append(result, update)
127128
}
128129

130+
// Reverse the result slice to restore the original order
131+
for left, right := 0, len(result)-1; left < right; left, right = left+1, right-1 {
132+
result[left], result[right] = result[right], result[left]
133+
}
134+
129135
logger.WithValues("runner", runner).Info("coalesced updates", "count", len(result), "before", len(updates))
130136

131137
return result

internal/message/watchutil_internal_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,15 @@ func TestMergeUpdates(t *testing.T) {
2929
name: "latest update per key delete state wins",
3030
input: []watchable.Update[string, int]{
3131
{Key: "foo", Value: 1},
32-
{Key: "foo", Value: 2},
3332
{Key: "bar", Delete: true, Value: 10},
33+
{Key: "baz", Value: 5},
3434
{Key: "bar", Delete: true, Value: 11},
35+
{Key: "foo", Value: 2},
3536
},
3637
expected: []watchable.Update[string, int]{
37-
{Key: "foo", Value: 2},
38+
{Key: "baz", Value: 5},
3839
{Key: "bar", Delete: true, Value: 11},
40+
{Key: "foo", Value: 2},
3941
},
4042
},
4143
}

0 commit comments

Comments
 (0)