From c96d043f16662312f6f01623056d6d42f9e27205 Mon Sep 17 00:00:00 2001 From: Bilal Akhtar Date: Fri, 18 Oct 2019 15:44:33 -0400 Subject: [PATCH] cache: Update cache targetSize to always return a positive int Noticed when ingesting SSTables as part of a cockroach snapshot apply. reservedSize would exceed maxSize, leading to an infinite loop in evict(). --- internal/cache/clockpro.go | 9 ++++++++- internal/cache/clockpro_test.go | 10 ++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/internal/cache/clockpro.go b/internal/cache/clockpro.go index b5fa8270f2..1e47d22dfb 100644 --- a/internal/cache/clockpro.go +++ b/internal/cache/clockpro.go @@ -372,7 +372,14 @@ func (c *shard) Size() int64 { } func (c *shard) targetSize() int64 { - return c.maxSize - c.reservedSize + target := c.maxSize - c.reservedSize + // Always return a positive integer for targetSize. This is so that we don't + // end up in an infinite loop in evict(), in cases where reservedSize is + // greater than or equal to maxSize. + if target < 1 { + return 1 + } + return target } // Add the entry to the cache, returning true if the entry was added and false diff --git a/internal/cache/clockpro_test.go b/internal/cache/clockpro_test.go index 963b8bbf71..5c535092dd 100644 --- a/internal/cache/clockpro_test.go +++ b/internal/cache/clockpro_test.go @@ -154,7 +154,7 @@ func TestZeroSize(t *testing.T) { } func TestReserve(t *testing.T) { - cache := newShards(2, 2) + cache := newShards(4, 2) cache.Set(1, 0, 0, []byte("a")) cache.Set(2, 0, 0, []byte("a")) require.EqualValues(t, 2, cache.Size()) @@ -162,12 +162,14 @@ func TestReserve(t *testing.T) { require.EqualValues(t, 0, cache.Size()) cache.Set(1, 0, 0, []byte("a")) cache.Set(2, 0, 0, []byte("a")) - require.EqualValues(t, 0, cache.Size()) + cache.Set(3, 0, 0, []byte("a")) + cache.Set(4, 0, 0, []byte("a")) + require.EqualValues(t, 2, cache.Size()) r() - require.EqualValues(t, 0, cache.Size()) + require.EqualValues(t, 2, cache.Size()) cache.Set(1, 0, 0, []byte("a")) cache.Set(2, 0, 0, []byte("a")) - require.EqualValues(t, 2, cache.Size()) + require.EqualValues(t, 4, cache.Size()) } func TestReserveDoubleRelease(t *testing.T) {