fix(storage): release replaced bytes when a key is overwritten

Put added the new size to the usage counter without subtracting the file it
replaced. Each overwrite inflated usage until restart and could trip the
quota on a cache that was not full.
This commit is contained in:
2026-11-23 13:15:33 +00:00
parent 4713524778
commit 1f31256769
2 changed files with 45 additions and 2 deletions
+7 -2
View File
@@ -162,7 +162,12 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
// only successfully renamed files. Quota check happens before increment
// to avoid transient inflation seen by concurrent Puts.
fs.mu.Lock()
if fs.quota > 0 && fs.used+written > fs.quota {
// An overwrite releases the bytes of the file it replaces.
var replaced int64
if info, statErr := root.Stat(relPath); statErr == nil {
replaced = info.Size()
}
if fs.quota > 0 && fs.used-replaced+written > fs.quota {
fs.mu.Unlock()
_ = root.Remove(tempPath)
metrics.RecordStorageOperation("filesystem", "put", "quota_exceeded")
@@ -174,7 +179,7 @@ func (fs *FilesystemStorage) Put(ctx context.Context, key string, data io.Reader
metrics.RecordStorageOperation("filesystem", "put", "error")
return errors.Wrap(err, errors.ErrCodeStorageFailure, "failed to rename temp file")
}
fs.used += written
fs.used += written - replaced
currentUsed := fs.used
fs.mu.Unlock()
@@ -0,0 +1,38 @@
package filesystem
import (
"context"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
// Used bytes must equal the bytes on disk after a key is overwritten.
func TestPutOverwriteKeepsUsageExact(t *testing.T) {
ctx := context.Background()
fs, err := New(t.TempDir(), 1000)
require.NoError(t, err)
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("x", 400)), nil))
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("y", 300)), nil))
quota, err := fs.GetQuota(ctx)
require.NoError(t, err)
require.EqualValues(t, 300, quota.Used)
require.NoError(t, fs.Delete(ctx, "npm/a/metadata"))
quota, err = fs.GetQuota(ctx)
require.NoError(t, err)
require.EqualValues(t, 0, quota.Used)
}
// An overwrite that fits once the old bytes are released must not hit the quota.
func TestPutOverwriteWithinQuota(t *testing.T) {
ctx := context.Background()
fs, err := New(t.TempDir(), 500)
require.NoError(t, err)
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("x", 400)), nil))
require.NoError(t, fs.Put(ctx, "npm/a/metadata", strings.NewReader(strings.Repeat("y", 450)), nil))
}