Skip to content

Improve handling of updated items #168

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 30, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (
"github.com/dgraph-io/ristretto/z"
)

const (
var (
// TODO: find the optimal value for this or make it configurable
setBufSize = 32 * 1024
)
Expand Down Expand Up @@ -235,7 +235,10 @@ func (c *Cache) SetWithTTL(key, value interface{}, cost int64, ttl time.Duration
return true
default:
c.Metrics.add(dropSets, keyHash, 1)
return false
// Return true if this was an update operation since we've already
// updated the store. For all the other operations (set/delete), we
// return false which means the item was not inserted.
return i.flag == itemUpdate
}
}

Expand Down
56 changes: 56 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package ristretto

import (
"fmt"
"math/rand"
"strconv"
"strings"
"sync"
"testing"
Expand Down Expand Up @@ -614,3 +616,57 @@ func init() {
// Set bucketSizeSecs to 1 to avoid waiting too much during the tests.
bucketDurationSecs = 1
}

func TestUpdateBug(t *testing.T) {
originalSetBugSize := setBufSize
defer func() { setBufSize = originalSetBugSize }()

test := func() {
// dropppedMap stores the items dropped from the cache.
droppedMap := make(map[int]struct{})
lastEvictedSet := int64(-1)

var err error
handler := func(_ interface{}, value interface{}) {
v := value.(string)
lastEvictedSet, err = strconv.ParseInt(string(v), 10, 32)
require.NoError(t, err)

_, ok := droppedMap[int(lastEvictedSet)]
if ok {
panic(fmt.Sprintf("val = %+v was dropped but it got evicted. Dropped items: %+v\n",
lastEvictedSet, droppedMap))
}
}

// This is important.
setBufSize = 10

c, err := NewCache(&Config{
NumCounters: 100,
MaxCost: 10,
BufferItems: 64,
Metrics: true,
OnEvict: func(_, _ uint64, value interface{}, _ int64) {
handler(nil, value)
},
})
require.NoError(t, err)

for i := 0; i < 5*setBufSize; i++ {
v := fmt.Sprintf("%0100d", i)
// We're updating the same key.
if !c.Set(0, v, 1) {
time.Sleep(time.Microsecond)
droppedMap[i] = struct{}{}
}
}
time.Sleep(time.Millisecond)
require.True(t, c.Set(1, nil, 10))
c.Close()
}
// Run the test 100 times.
for i := 0; i < 100; i++ {
test()
}
}