~bzr-pqm/bzr/bzr.dev

4516.2.1 by John Arbash Meinel
Fix bug #396838, Update LRUCache to maintain invariant even
1
# Copyright (C) 2006, 2008, 2009 Canonical Ltd
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
16
17
"""A simple least-recently-used (LRU) cache."""
18
4178.3.7 by John Arbash Meinel
Review tweaks from Ian.
19
from bzrlib import (
6215.1.1 by Martin Packman
Rename confusing LRUCache.items method that doesn't act like dict.items to as_dict
20
    symbol_versioning,
4178.3.7 by John Arbash Meinel
Review tweaks from Ian.
21
    trace,
22
    )
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
23
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
24
_null_key = object()
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
25
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
26
class _LRUNode(object):
27
    """This maintains the linked-list which is the lru internals."""
28
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
29
    __slots__ = ('prev', 'next_key', 'key', 'value')
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
30
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
31
    def __init__(self, key, value):
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
32
        self.prev = None
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
33
        self.next_key = _null_key
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
34
        self.key = key
35
        self.value = value
36
37
    def __repr__(self):
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
38
        if self.prev is None:
39
            prev_key = None
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
40
        else:
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
41
            prev_key = self.prev.key
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
42
        return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
43
                                     self.next_key, prev_key)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
44
45
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
46
class LRUCache(object):
47
    """A class which manages a cache of entries, removing unused ones."""
48
5346.1.4 by Vincent Ladeuil
Delete the after_cleanup_size parameter from the LRUCache constructor.
49
    def __init__(self, max_cache=100, after_cleanup_count=None):
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
50
        self._cache = {}
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
51
        # The "HEAD" of the lru linked list
52
        self._most_recently_used = None
53
        # The "TAIL" of the lru linked list
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
54
        self._least_recently_used = None
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
55
        self._update_max_cache(max_cache, after_cleanup_count)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
56
57
    def __contains__(self, key):
58
        return key in self._cache
59
60
    def __getitem__(self, key):
4287.1.6 by John Arbash Meinel
Remove the double getattr() for self._cache.
61
        cache = self._cache
62
        node = cache[key]
4178.3.4 by John Arbash Meinel
Shave off approx 100ms by inlining _record_access into __getitem__,
63
        # Inlined from _record_access to decrease the overhead of __getitem__
64
        # We also have more knowledge about structure if __getitem__ is
65
        # succeeding, then we know that self._most_recently_used must not be
66
        # None, etc.
67
        mru = self._most_recently_used
68
        if node is mru:
69
            # Nothing to do, this node is already at the head of the queue
70
            return node.value
71
        # Remove this node from the old location
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
72
        node_prev = node.prev
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
73
        next_key = node.next_key
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
74
        # benchmarking shows that the lookup of _null_key in globals is faster
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
75
        # than the attribute lookup for (node is self._least_recently_used)
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
76
        if next_key is _null_key:
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
77
            # 'node' is the _least_recently_used, because it doesn't have a
4287.1.7 by John Arbash Meinel
Fairly significant savings... avoid looking at self._last_recently_used.
78
            # 'next' item. So move the current lru to the previous node.
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
79
            self._least_recently_used = node_prev
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
80
        else:
4287.1.6 by John Arbash Meinel
Remove the double getattr() for self._cache.
81
            node_next = cache[next_key]
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
82
            node_next.prev = node_prev
4287.1.7 by John Arbash Meinel
Fairly significant savings... avoid looking at self._last_recently_used.
83
        node_prev.next_key = next_key
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
84
        # Insert this node at the front of the list
85
        node.next_key = mru.key
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
86
        mru.prev = node
4178.3.4 by John Arbash Meinel
Shave off approx 100ms by inlining _record_access into __getitem__,
87
        self._most_recently_used = node
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
88
        node.prev = None
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
89
        return node.value
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
90
91
    def __len__(self):
92
        return len(self._cache)
93
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
94
    @symbol_versioning.deprecated_method(
95
        symbol_versioning.deprecated_in((2, 5, 0)))
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
96
    def add(self, key, value, cleanup=None):
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
97
        if cleanup is not None:
98
            raise ValueError("Per-node cleanup functions no longer supported")
99
        return self.__setitem__(key, value)
100
101
    def __setitem__(self, key, value):
102
        """Add a new value to the cache"""
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
103
        if key is _null_key:
104
            raise ValueError('cannot use _null_key as a key')
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
105
        if key in self._cache:
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
106
            node = self._cache[key]
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
107
            node.value = value
108
            self._record_access(node)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
109
        else:
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
110
            node = _LRUNode(key, value)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
111
            self._cache[key] = node
4516.2.1 by John Arbash Meinel
Fix bug #396838, Update LRUCache to maintain invariant even
112
            self._record_access(node)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
113
114
        if len(self._cache) > self._max_cache:
115
            # Trigger the cleanup
116
            self.cleanup()
117
4178.3.1 by John Arbash Meinel
Implement LRUCache.cache_size(), so that it can trivially substitute for FIFOCache.
118
    def cache_size(self):
119
        """Get the number of entries we will cache."""
120
        return self._max_cache
121
2998.2.1 by John Arbash Meinel
Implement LRUCache.get() which acts like dict.get()
122
    def get(self, key, default=None):
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
123
        node = self._cache.get(key, None)
124
        if node is None:
125
            return default
4178.3.5 by John Arbash Meinel
Add tests that LRUCache.get() properly tracks accesses.
126
        self._record_access(node)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
127
        return node.value
2998.2.1 by John Arbash Meinel
Implement LRUCache.get() which acts like dict.get()
128
3763.8.10 by John Arbash Meinel
Add a .keys() member to LRUCache and LRUSizeCache.
129
    def keys(self):
130
        """Get the list of keys currently cached.
131
132
        Note that values returned here may not be available by the time you
133
        request them later. This is simply meant as a peak into the current
134
        state.
135
136
        :return: An unordered list of keys that are currently cached.
137
        """
138
        return self._cache.keys()
139
6215.1.1 by Martin Packman
Rename confusing LRUCache.items method that doesn't act like dict.items to as_dict
140
    def as_dict(self):
141
        """Get a new dict with the same key:value pairs as the cache"""
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
142
        return dict((k, n.value) for k, n in self._cache.iteritems())
143
6215.1.1 by Martin Packman
Rename confusing LRUCache.items method that doesn't act like dict.items to as_dict
144
    items = symbol_versioning.deprecated_method(
145
        symbol_versioning.deprecated_in((2, 5, 0)))(as_dict)
146
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
147
    def cleanup(self):
148
        """Clear the cache until it shrinks to the requested size.
149
150
        This does not completely wipe the cache, just makes sure it is under
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
151
        the after_cleanup_count.
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
152
        """
153
        # Make sure the cache is shrunk to the correct size
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
154
        while len(self._cache) > self._after_cleanup_count:
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
155
            self._remove_lru()
156
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
157
    def _record_access(self, node):
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
158
        """Record that key was accessed."""
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
159
        # Move 'node' to the front of the queue
160
        if self._most_recently_used is None:
161
            self._most_recently_used = node
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
162
            self._least_recently_used = node
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
163
            return
164
        elif node is self._most_recently_used:
165
            # Nothing to do, this node is already at the head of the queue
166
            return
167
        # We've taken care of the tail pointer, remove the node, and insert it
168
        # at the front
169
        # REMOVE
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
170
        if node is self._least_recently_used:
171
            self._least_recently_used = node.prev
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
172
        if node.prev is not None:
173
            node.prev.next_key = node.next_key
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
174
        if node.next_key is not _null_key:
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
175
            node_next = self._cache[node.next_key]
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
176
            node_next.prev = node.prev
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
177
        # INSERT
4287.1.4 by John Arbash Meinel
use indirection on both next and prev.
178
        node.next_key = self._most_recently_used.key
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
179
        self._most_recently_used.prev = node
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
180
        self._most_recently_used = node
4287.1.5 by John Arbash Meinel
Switch to using prev as the object and next_key as the pointer.
181
        node.prev = None
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
182
183
    def _remove_node(self, node):
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
184
        if node is self._least_recently_used:
185
            self._least_recently_used = node.prev
4178.3.6 by John Arbash Meinel
Remove the asserts, and change some to AssertionError.
186
        self._cache.pop(node.key)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
187
        # If we have removed all entries, remove the head pointer as well
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
188
        if self._least_recently_used is None:
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
189
            self._most_recently_used = None
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
190
        if node.prev is not None:
191
            node.prev.next_key = node.next_key
192
        if node.next_key is not _null_key:
193
            node_next = self._cache[node.next_key]
194
            node_next.prev = node.prev
195
        # And remove this node's pointers
196
        node.prev = None
197
        node.next_key = _null_key
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
198
199
    def _remove_lru(self):
200
        """Remove one entry from the lru, and handle consequences.
201
202
        If there are no more references to the lru, then this entry should be
203
        removed from the cache.
204
        """
4287.1.11 by John Arbash Meinel
Small tweaks from Ian.
205
        self._remove_node(self._least_recently_used)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
206
207
    def clear(self):
208
        """Clear out all of the cache."""
209
        # Clean up in LRU order
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
210
        while self._cache:
211
            self._remove_lru()
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
212
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
213
    def resize(self, max_cache, after_cleanup_count=None):
214
        """Change the number of entries that will be cached."""
215
        self._update_max_cache(max_cache,
216
                               after_cleanup_count=after_cleanup_count)
217
218
    def _update_max_cache(self, max_cache, after_cleanup_count=None):
219
        self._max_cache = max_cache
220
        if after_cleanup_count is None:
221
            self._after_cleanup_count = self._max_cache * 8 / 10
222
        else:
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
223
            self._after_cleanup_count = min(after_cleanup_count,
224
                                            self._max_cache)
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
225
        self.cleanup()
226
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
227
228
class LRUSizeCache(LRUCache):
229
    """An LRUCache that removes things based on the size of the values.
230
231
    This differs in that it doesn't care how many actual items there are,
232
    it just restricts the cache to be cleaned up after so much data is stored.
233
4178.3.7 by John Arbash Meinel
Review tweaks from Ian.
234
    The size of items added will be computed using compute_size(value), which
235
    defaults to len() if not supplied.
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
236
    """
237
238
    def __init__(self, max_size=1024*1024, after_cleanup_size=None,
239
                 compute_size=None):
240
        """Create a new LRUSizeCache.
241
242
        :param max_size: The max number of bytes to store before we start
243
            clearing out entries.
244
        :param after_cleanup_size: After cleaning up, shrink everything to this
245
            size.
246
        :param compute_size: A function to compute the size of the values. We
247
            use a function here, so that you can pass 'len' if you are just
248
            using simple strings, or a more complex function if you are using
249
            something like a list of strings, or even a custom object.
250
            The function should take the form "compute_size(value) => integer".
251
            If not supplied, it defaults to 'len()'
252
        """
253
        self._value_size = 0
254
        self._compute_size = compute_size
255
        if compute_size is None:
256
            self._compute_size = len
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
257
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
258
        LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
259
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
260
    def __setitem__(self, key, value):
261
        """Add a new value to the cache"""
4287.1.10 by John Arbash Meinel
Restore the ability to handle None as a key.
262
        if key is _null_key:
263
            raise ValueError('cannot use _null_key as a key')
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
264
        node = self._cache.get(key, None)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
265
        value_len = self._compute_size(value)
266
        if value_len >= self._after_cleanup_size:
4178.3.7 by John Arbash Meinel
Review tweaks from Ian.
267
            # The new value is 'too big to fit', as it would fill up/overflow
268
            # the cache all by itself
269
            trace.mutter('Adding the key %r to an LRUSizeCache failed.'
270
                         ' value %d is too big to fit in a the cache'
271
                         ' with size %d %d', key, value_len,
272
                         self._after_cleanup_size, self._max_size)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
273
            if node is not None:
4178.3.7 by John Arbash Meinel
Review tweaks from Ian.
274
                # We won't be replacing the old node, so just remove it
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
275
                self._remove_node(node)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
276
            return
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
277
        if node is None:
6215.1.4 by Martin Packman
Remove unneeded _LRUNode.cleanup callback ability and deprecate LRUCache.add
278
            node = _LRUNode(key, value)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
279
            self._cache[key] = node
280
        else:
6215.1.3 by Martin Packman
Recompute size rather than storing on _LRUNode.size
281
            self._value_size -= self._compute_size(node.value)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
282
        self._value_size += value_len
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
283
        self._record_access(node)
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
284
285
        if self._value_size > self._max_size:
286
            # Time to cleanup
287
            self.cleanup()
288
289
    def cleanup(self):
290
        """Clear the cache until it shrinks to the requested size.
291
292
        This does not completely wipe the cache, just makes sure it is under
293
        the after_cleanup_size.
294
        """
295
        # Make sure the cache is shrunk to the correct size
296
        while self._value_size > self._after_cleanup_size:
297
            self._remove_lru()
298
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
299
    def _remove_node(self, node):
6215.1.3 by Martin Packman
Recompute size rather than storing on _LRUNode.size
300
        self._value_size -= self._compute_size(node.value)
4178.3.3 by John Arbash Meinel
LRUCache is now implemented with a dict to a linked list,
301
        LRUCache._remove_node(self, node)
3882.3.1 by John Arbash Meinel
Add LRUCache.resize(), and change the init arguments for LRUCache.
302
303
    def resize(self, max_size, after_cleanup_size=None):
304
        """Change the number of bytes that will be cached."""
305
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
306
        max_cache = max(int(max_size/512), 1)
307
        self._update_max_cache(max_cache)
308
309
    def _update_max_size(self, max_size, after_cleanup_size=None):
310
        self._max_size = max_size
311
        if after_cleanup_size is None:
312
            self._after_cleanup_size = self._max_size * 8 / 10
313
        else:
314
            self._after_cleanup_size = min(after_cleanup_size, self._max_size)