Skip to content
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

fix(LRUCache): copy using deepcopy, and ensure the get_all function always terminates #3861

Merged
merged 1 commit into from
Dec 6, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
14 changes: 11 additions & 3 deletions sentry_sdk/_lru_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@

"""

from copy import copy
from copy import copy, deepcopy

SENTINEL = object()

Expand Down Expand Up @@ -95,7 +95,7 @@ def __copy__(self):
cache = LRUCache(self.max_size)
cache.full = self.full
cache.cache = copy(self.cache)
cache.root = copy(self.root)
cache.root = deepcopy(self.root)
return cache

def set(self, key, value):
Expand Down Expand Up @@ -167,7 +167,15 @@ def get(self, key, default=None):
def get_all(self):
nodes = []
node = self.root[NEXT]
while node is not self.root:

# To ensure the loop always terminates we iterate to the maximum
# size of the LRU cache.
for _ in range(self.max_size):
# The cache may not be full. We exit early if we've wrapped
# around to the head.
if node is self.root:
break
nodes.append((node[KEY], node[VALUE]))
node = node[NEXT]

return nodes
18 changes: 18 additions & 0 deletions tests/test_lru_cache.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest
from copy import copy

from sentry_sdk._lru_cache import LRUCache

Expand Down Expand Up @@ -58,3 +59,20 @@ def test_cache_get_all():
assert cache.get_all() == [(1, 1), (2, 2), (3, 3)]
cache.get(1)
assert cache.get_all() == [(2, 2), (3, 3), (1, 1)]


def test_cache_copy():
cache = LRUCache(3)
cache.set(0, 0)
cache.set(1, 1)

copied = copy(cache)
cache.set(2, 2)
cache.set(3, 3)
assert copied.get_all() == [(0, 0), (1, 1)]
assert cache.get_all() == [(1, 1), (2, 2), (3, 3)]

copied = copy(cache)
cache.get(1)
assert copied.get_all() == [(1, 1), (2, 2), (3, 3)]
assert cache.get_all() == [(2, 2), (3, 3), (1, 1)]
Loading