/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
1
# Copyright (C) 2008 Canonical Ltd
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
17
"""Persistent maps from tuple_of_strings->string using CHK stores.
18
19
Overview and current status:
20
21
The CHKMap class implements a dict from tuple_of_strings->string by using a trie
22
with internal nodes of 8-bit fan out; The key tuples are mapped to strings by
23
joining them by \x00, and \x00 padding shorter keys out to the length of the
24
longest key. Leaf nodes are packed as densely as possible, and internal nodes
3735.11.1 by John Arbash Meinel
Clean up some trailing whitespace.
25
are all and additional 8-bits wide leading to a sparse upper tree.
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
26
27
Updates to a CHKMap are done preferentially via the apply_delta method, to
28
allow optimisation of the update operation; but individual map/unmap calls are
29
possible and supported. All changes via map/unmap are buffered in memory until
30
the _save method is called to force serialisation of the tree. apply_delta
31
performs a _save implicitly.
32
33
TODO:
34
-----
35
36
Densely packed upper nodes.
37
38
"""
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
39
3735.2.31 by Robert Collins
CHKMap.iter_changes
40
import heapq
3735.2.62 by Robert Collins
Create a rudimentary CHK page cache.
41
3735.9.18 by John Arbash Meinel
Make the versionedfile import lazy.
42
from bzrlib import lazy_import
43
lazy_import.lazy_import(globals(), """
3735.16.3 by John Arbash Meinel
Add functions for _search_key_16 and _search_key_255 and some basic tests for them.
44
import zlib
45
import struct
46
3735.9.18 by John Arbash Meinel
Make the versionedfile import lazy.
47
from bzrlib import versionedfile
48
""")
3735.16.7 by John Arbash Meinel
Start parameterizing CHKInventory and CHKSerializer so that we can
49
from bzrlib import (
50
    lru_cache,
3735.17.1 by John Arbash Meinel
Change the serialized form for leaf nodes.
51
    osutils,
3735.16.7 by John Arbash Meinel
Start parameterizing CHKInventory and CHKSerializer so that we can
52
    registry,
53
    )
3735.2.62 by Robert Collins
Create a rudimentary CHK page cache.
54
55
# approx 2MB
3735.14.5 by John Arbash Meinel
Change _check_remap to only page in a batch of children at a time.
56
# If each line is 50 bytes, and you have 255 internal pages, with 255-way fan
57
# out, it takes 3.1MB to cache the layer.
58
_PAGE_CACHE_SIZE = 4*1024*1024
3735.14.2 by John Arbash Meinel
Finish using the page cache as part of _check_remap, add debugging functions
59
# We are caching bytes so len(value) is perfectly accurate
60
_page_cache = lru_cache.LRUSizeCache(_PAGE_CACHE_SIZE)
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
61
62
3735.16.6 by John Arbash Meinel
Include a _search_key_plain function.
63
def _search_key_plain(key):
64
    """Map the key tuple into a search string that just uses the key bytes."""
65
    return '\x00'.join(key)
66
67
3735.16.3 by John Arbash Meinel
Add functions for _search_key_16 and _search_key_255 and some basic tests for them.
68
def _search_key_16(key):
69
    """Map the key tuple into a search key string which has 16-way fan out."""
70
    return '\x00'.join(['%08X' % abs(zlib.crc32(bit)) for bit in key])
71
72
73
def _search_key_255(key):
74
    """Map the key tuple into a search key string which has 255-way fan out.
75
76
    We use 255-way because '\n' is used as a delimiter, and causes problems
77
    while parsing.
78
    """
3735.2.83 by Vincent Ladeuil
Better fix with explanation for zlib.crc32.
79
    # Depending on python version and platform, zlib.crc32 will return either a
80
    # signed (<= 2.5 >= 3.0) or an unsigned (2.5, 2.6).
81
    # http://docs.python.org/library/zlib.html recommends using a mask to force
82
    # an unsigned value to ensure the same numeric value (unsigned) is obtained
83
    # across all python versions and platforms.
3735.2.84 by John Arbash Meinel
Comment about using using 0xFFFFFFFF as part of _search_key_255
84
    # Note: However, on 32-bit platforms this causes an upcast to PyLong, which
85
    #       are generally slower than PyInts. However, if performance becomes
86
    #       critical, we should probably write the whole thing as an extension
87
    #       anyway.
88
    #       Though we really don't need that 32nd bit of accuracy. (even 2**24
89
    #       is probably enough node fan out for realistic trees.)
3735.2.83 by Vincent Ladeuil
Better fix with explanation for zlib.crc32.
90
    bytes = '\x00'.join([struct.pack('>L', zlib.crc32(bit)&0xFFFFFFFF)
91
                         for bit in key])
3735.16.3 by John Arbash Meinel
Add functions for _search_key_16 and _search_key_255 and some basic tests for them.
92
    return bytes.replace('\n', '_')
93
94
3735.16.7 by John Arbash Meinel
Start parameterizing CHKInventory and CHKSerializer so that we can
95
search_key_registry = registry.Registry()
96
search_key_registry.register('plain', _search_key_plain)
97
search_key_registry.register('hash-16-way', _search_key_16)
98
search_key_registry.register('hash-255-way', _search_key_255)
99
100
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
101
class CHKMap(object):
102
    """A persistent map from string to string backed by a CHK store."""
103
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
104
    def __init__(self, store, root_key, search_key_func=None):
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
105
        """Create a CHKMap object.
106
107
        :param store: The store the CHKMap is stored in.
108
        :param root_key: The root key of the map. None to create an empty
109
            CHKMap.
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
110
        :param search_key_func: A function mapping a key => bytes. These bytes
111
            are then used by the internal nodes to split up leaf nodes into
112
            multiple pages.
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
113
        """
114
        self._store = store
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
115
        if search_key_func is None:
3735.16.6 by John Arbash Meinel
Include a _search_key_plain function.
116
            search_key_func = _search_key_plain
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
117
        self._search_key_func = search_key_func
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
118
        if root_key is None:
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
119
            self._root_node = LeafNode(search_key_func=search_key_func)
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
120
        else:
3735.2.41 by Robert Collins
Make the parent_id_basename index be updated during CHKInventory.apply_delta.
121
            self._root_node = self._node_key(root_key)
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
122
123
    def apply_delta(self, delta):
124
        """Apply a delta to the map.
125
126
        :param delta: An iterable of old_key, new_key, new_value tuples.
127
            If new_key is not None, then new_key->new_value is inserted
128
            into the map; if old_key is not None, then the old mapping
129
            of old_key is removed.
130
        """
131
        for old, new, value in delta:
132
            if old is not None and old != new:
133
                # unmap
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
134
                self.unmap(old)
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
135
        for old, new, value in delta:
136
            if new is not None:
137
                # map
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
138
                self.map(new, value)
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
139
        return self._save()
140
141
    def _ensure_root(self):
142
        """Ensure that the root node is an object not a key."""
143
        if type(self._root_node) == tuple:
144
            # Demand-load the root
3735.2.31 by Robert Collins
CHKMap.iter_changes
145
            self._root_node = self._get_node(self._root_node)
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
146
            # XXX: Shouldn't this be put into _deserialize?
147
            self._root_node._search_key_func = self._search_key_func
3735.2.31 by Robert Collins
CHKMap.iter_changes
148
149
    def _get_node(self, node):
150
        """Get a node.
151
152
        Node that this does not update the _items dict in objects containing a
153
        reference to this node. As such it does not prevent subsequent IO being
154
        performed.
3735.11.1 by John Arbash Meinel
Clean up some trailing whitespace.
155
3735.2.31 by Robert Collins
CHKMap.iter_changes
156
        :param node: A tuple key or node object.
157
        :return: A node object.
158
        """
159
        if type(node) == tuple:
160
            bytes = self._read_bytes(node)
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
161
            return _deserialise(bytes, node,
162
                search_key_func=self._search_key_func)
3735.2.31 by Robert Collins
CHKMap.iter_changes
163
        else:
164
            return node
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
165
166
    def _read_bytes(self, key):
167
        stream = self._store.get_record_stream([key], 'unordered', True)
168
        return stream.next().get_bytes_as('fulltext')
169
3735.15.16 by John Arbash Meinel
Properly fix up the dump_tree tests, we now suppress the keys by default.
170
    def _dump_tree(self, include_keys=False):
3735.9.2 by John Arbash Meinel
Add a _dump_tree helper that assists in debugging what is going on.
171
        """Return the tree in a string representation."""
172
        self._ensure_root()
3735.15.15 by John Arbash Meinel
Change child_child to use _dump_tree,
173
        res = self._dump_tree_node(self._root_node, prefix='', indent='',
174
                                   include_keys=include_keys)
3735.11.9 by John Arbash Meinel
Switch _dump_tree to returning trailing '\n' for nicer results
175
        res.append('') # Give a trailing '\n'
3735.9.4 by John Arbash Meinel
Some small cleanups, and fix _dump_tree to handle in-progress nodes.
176
        return '\n'.join(res)
3735.9.2 by John Arbash Meinel
Add a _dump_tree helper that assists in debugging what is going on.
177
3735.15.15 by John Arbash Meinel
Change child_child to use _dump_tree,
178
    def _dump_tree_node(self, node, prefix, indent, include_keys=True):
3735.9.2 by John Arbash Meinel
Add a _dump_tree helper that assists in debugging what is going on.
179
        """For this node and all children, generate a string representation."""
180
        result = []
3735.15.15 by John Arbash Meinel
Change child_child to use _dump_tree,
181
        if not include_keys:
182
            key_str = ''
183
        else:
184
            node_key = node.key()
185
            if node_key is not None:
186
                key_str = ' %s' % (node_key[0],)
187
            else:
188
                key_str = ' None'
189
        result.append('%s%r %s%s' % (indent, prefix, node.__class__.__name__,
190
                                     key_str))
3735.9.2 by John Arbash Meinel
Add a _dump_tree helper that assists in debugging what is going on.
191
        if isinstance(node, InternalNode):
192
            # Trigger all child nodes to get loaded
193
            list(node._iter_nodes(self._store))
3735.9.4 by John Arbash Meinel
Some small cleanups, and fix _dump_tree to handle in-progress nodes.
194
            for prefix, sub in sorted(node._items.iteritems()):
3735.15.15 by John Arbash Meinel
Change child_child to use _dump_tree,
195
                result.extend(self._dump_tree_node(sub, prefix, indent + '  ',
196
                                                   include_keys=include_keys))
3735.9.2 by John Arbash Meinel
Add a _dump_tree helper that assists in debugging what is going on.
197
        else:
3735.9.4 by John Arbash Meinel
Some small cleanups, and fix _dump_tree to handle in-progress nodes.
198
            for key, value in sorted(node._items.iteritems()):
199
                result.append('      %r %r' % (key, value))
3735.9.2 by John Arbash Meinel
Add a _dump_tree helper that assists in debugging what is going on.
200
        return result
201
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
202
    @classmethod
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
203
    def from_dict(klass, store, initial_value, maximum_size=0, key_width=1):
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
204
        """Create a CHKMap in store with initial_value as the content.
3735.11.1 by John Arbash Meinel
Clean up some trailing whitespace.
205
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
206
        :param store: The store to record initial_value in, a VersionedFiles
207
            object with 1-tuple keys supporting CHK key generation.
208
        :param initial_value: A dict to store in store. Its keys and values
209
            must be bytestrings.
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
210
        :param maximum_size: The maximum_size rule to apply to nodes. This
211
            determines the size at which no new data is added to a single node.
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
212
        :param key_width: The number of elements in each key_tuple being stored
213
            in this map.
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
214
        :return: The root chk of te resulting CHKMap.
215
        """
216
        result = CHKMap(store, None)
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
217
        result._root_node.set_maximum_size(maximum_size)
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
218
        result._root_node._key_width = key_width
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
219
        delta = []
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
220
        for key, value in initial_value.items():
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
221
            delta.append((None, key, value))
222
        result.apply_delta(delta)
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
223
        return result._save()
224
3735.2.30 by Robert Collins
Start iter_changes between CHKMap instances.
225
    def iter_changes(self, basis):
226
        """Iterate over the changes between basis and self.
227
228
        :return: An iterator of tuples: (key, old_value, new_value). Old_value
229
            is None for keys only in self; new_value is None for keys only in
230
            basis.
231
        """
3735.2.31 by Robert Collins
CHKMap.iter_changes
232
        # Overview:
233
        # Read both trees in lexographic, highest-first order.
234
        # Any identical nodes we skip
235
        # Any unique prefixes we output immediately.
236
        # values in a leaf node are treated as single-value nodes in the tree
237
        # which allows them to be not-special-cased. We know to output them
238
        # because their value is a string, not a key(tuple) or node.
239
        #
240
        # corner cases to beware of when considering this function:
241
        # *) common references are at different heights.
242
        #    consider two trees:
243
        #    {'a': LeafNode={'aaa':'foo', 'aab':'bar'}, 'b': LeafNode={'b'}}
244
        #    {'a': InternalNode={'aa':LeafNode={'aaa':'foo', 'aab':'bar'}, 'ab':LeafNode={'ab':'bar'}}
245
        #     'b': LeafNode={'b'}}
246
        #    the node with aaa/aab will only be encountered in the second tree
247
        #    after reading the 'a' subtree, but it is encountered in the first
248
        #    tree immediately. Variations on this may have read internal nodes like this.
249
        #    we want to cut the entire pending subtree when we realise we have a common node.
3735.11.1 by John Arbash Meinel
Clean up some trailing whitespace.
250
        #    For this we use a list of keys - the path to a node - and check the entire path is
3735.2.31 by Robert Collins
CHKMap.iter_changes
251
        #    clean as we process each item.
252
        if self._node_key(self._root_node) == self._node_key(basis._root_node):
253
            return
254
        self._ensure_root()
255
        basis._ensure_root()
256
        excluded_keys = set()
257
        self_node = self._root_node
258
        basis_node = basis._root_node
259
        # A heap, each element is prefix, node(tuple/NodeObject/string),
260
        # key_path (a list of tuples, tail-sharing down the tree.)
261
        self_pending = []
262
        basis_pending = []
263
        def process_node(prefix, node, path, a_map, pending):
264
            # take a node and expand it
265
            node = a_map._get_node(node)
266
            if type(node) == LeafNode:
267
                path = (node._key, path)
268
                for key, value in node._items.items():
269
                    heapq.heappush(pending, ('\x00'.join(key), value, path))
270
            else:
271
                # type(node) == InternalNode
272
                path = (node._key, path)
273
                for prefix, child in node._items.items():
274
                    heapq.heappush(pending, (prefix, child, path))
275
        process_node(None, self_node, None, self, self_pending)
276
        process_node(None, basis_node, None, basis, basis_pending)
277
        self_seen = set()
278
        basis_seen = set()
279
        excluded_keys = set()
280
        def check_excluded(key_path):
281
            # Note that this is N^2, it depends on us trimming trees
282
            # aggressively to not become slow.
283
            # A better implementation would probably have a reverse map
3735.11.1 by John Arbash Meinel
Clean up some trailing whitespace.
284
            # back to the children of a node, and jump straight to it when
3735.2.31 by Robert Collins
CHKMap.iter_changes
285
            # a common node is detected, the proceed to remove the already
286
            # pending children. bzrlib.graph has a searcher module with a
287
            # similar problem.
288
            while key_path is not None:
289
                key, key_path = key_path
290
                if key in excluded_keys:
291
                    return True
292
            return False
293
3735.2.32 by Robert Collins
Activate test for common node skipping. - 50 times performance improvement.
294
        loop_counter = 0
3735.2.31 by Robert Collins
CHKMap.iter_changes
295
        while self_pending or basis_pending:
3735.2.32 by Robert Collins
Activate test for common node skipping. - 50 times performance improvement.
296
            loop_counter += 1
3735.2.31 by Robert Collins
CHKMap.iter_changes
297
            if not self_pending:
298
                # self is exhausted: output remainder of basis
299
                for prefix, node, path in basis_pending:
300
                    if check_excluded(path):
301
                        continue
302
                    node = basis._get_node(node)
303
                    if type(node) == str:
304
                        # a value
305
                        yield (tuple(prefix.split('\x00')), node, None)
306
                    else:
307
                        # subtree - fastpath the entire thing.
308
                        for key, value in node.iteritems(basis._store):
309
                            yield (key, value, None)
310
                return
311
            elif not basis_pending:
312
                # basis is exhausted: output remainder of self.
313
                for prefix, node, path in self_pending:
314
                    if check_excluded(path):
315
                        continue
316
                    node = self._get_node(node)
317
                    if type(node) == str:
318
                        # a value
319
                        yield (tuple(prefix.split('\x00')), None, node)
320
                    else:
321
                        # subtree - fastpath the entire thing.
322
                        for key, value in node.iteritems(self._store):
323
                            yield (key, None, value)
324
                return
325
            else:
326
                # XXX: future optimisation - yield the smaller items
327
                # immediately rather than pushing everything on/off the
328
                # heaps. Applies to both internal nodes and leafnodes.
329
                if self_pending[0][0] < basis_pending[0][0]:
330
                    # expand self
331
                    prefix, node, path = heapq.heappop(self_pending)
332
                    if check_excluded(path):
333
                        continue
334
                    if type(node) == str:
335
                        # a value
336
                        yield (tuple(prefix.split('\x00')), None, node)
337
                    else:
338
                        process_node(prefix, node, path, self, self_pending)
339
                        continue
340
                elif self_pending[0][0] > basis_pending[0][0]:
341
                    # expand basis
342
                    prefix, node, path = heapq.heappop(basis_pending)
343
                    if check_excluded(path):
344
                        continue
345
                    if type(node) == str:
346
                        # a value
347
                        yield (tuple(prefix.split('\x00')), node, None)
348
                    else:
349
                        process_node(prefix, node, path, basis, basis_pending)
350
                        continue
351
                else:
352
                    # common prefix: possibly expand both
353
                    if type(self_pending[0][1]) != str:
354
                        # process next self
355
                        read_self = True
356
                    else:
357
                        read_self = False
358
                    if type(basis_pending[0][1]) != str:
359
                        # process next basis
360
                        read_basis = True
361
                    else:
362
                        read_basis = False
363
                    if not read_self and not read_basis:
364
                        # compare a common value
365
                        self_details = heapq.heappop(self_pending)
366
                        basis_details = heapq.heappop(basis_pending)
367
                        if self_details[1] != basis_details[1]:
368
                            yield (tuple(self_details[0].split('\x00')),
369
                                basis_details[1], self_details[1])
370
                        continue
3735.2.32 by Robert Collins
Activate test for common node skipping. - 50 times performance improvement.
371
                    # At least one side wasn't a string.
372
                    if (self._node_key(self_pending[0][1]) ==
373
                        self._node_key(basis_pending[0][1])):
374
                        # Identical pointers, skip (and don't bother adding to
375
                        # excluded, it won't turn up again.
376
                        heapq.heappop(self_pending)
377
                        heapq.heappop(basis_pending)
378
                        continue
379
                    # Now we need to expand this node before we can continue
3735.2.31 by Robert Collins
CHKMap.iter_changes
380
                    if read_self:
381
                        prefix, node, path = heapq.heappop(self_pending)
382
                        if check_excluded(path):
383
                            continue
384
                        process_node(prefix, node, path, self, self_pending)
385
                    if read_basis:
386
                        prefix, node, path = heapq.heappop(basis_pending)
387
                        if check_excluded(path):
388
                            continue
389
                        process_node(prefix, node, path, basis, basis_pending)
3735.2.32 by Robert Collins
Activate test for common node skipping. - 50 times performance improvement.
390
        # print loop_counter
3735.2.30 by Robert Collins
Start iter_changes between CHKMap instances.
391
3735.2.9 by Robert Collins
Get a working chk_map using inventory implementation bootstrapped.
392
    def iteritems(self, key_filter=None):
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
393
        """Iterate over the entire CHKMap's contents."""
394
        self._ensure_root()
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
395
        return self._root_node.iteritems(self._store, key_filter=key_filter)
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
396
3735.2.12 by Robert Collins
Implement commit-via-deltas for split inventory repositories.
397
    def key(self):
398
        """Return the key for this map."""
399
        if isinstance(self._root_node, tuple):
400
            return self._root_node
401
        else:
402
            return self._root_node._key
403
3735.2.17 by Robert Collins
Cache node length to avoid full iteration on __len__ calls.
404
    def __len__(self):
405
        self._ensure_root()
406
        return len(self._root_node)
407
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
408
    def map(self, key, value):
409
        """Map a key tuple to value."""
410
        # Need a root object.
411
        self._ensure_root()
412
        prefix, node_details = self._root_node.map(self._store, key, value)
413
        if len(node_details) == 1:
414
            self._root_node = node_details[0][1]
415
        else:
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
416
            self._root_node = InternalNode(prefix,
417
                                search_key_func=self._search_key_func)
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
418
            self._root_node.set_maximum_size(node_details[0][1].maximum_size)
419
            self._root_node._key_width = node_details[0][1]._key_width
420
            for split, node in node_details:
421
                self._root_node.add_node(split, node)
422
3735.2.31 by Robert Collins
CHKMap.iter_changes
423
    def _node_key(self, node):
424
        """Get the key for a node whether its a tuple o r node."""
425
        if type(node) == tuple:
426
            return node
427
        else:
428
            return node._key
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
429
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
430
    def unmap(self, key):
431
        """remove key from the map."""
432
        self._ensure_root()
3735.11.3 by John Arbash Meinel
At the end of unmap() see if children can be packed into a single Leaf.
433
        unmapped = self._root_node.unmap(self._store, key)
434
        self._root_node = unmapped
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
435
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
436
    def _save(self):
437
        """Save the map completely.
438
439
        :return: The key of the root node.
440
        """
441
        if type(self._root_node) == tuple:
442
            # Already saved.
443
            return self._root_node
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
444
        keys = list(self._root_node.serialise(self._store))
445
        return keys[-1]
3735.2.8 by Robert Collins
New chk_map module for use in tree based inventory storage.
446
447
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
448
class Node(object):
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
449
    """Base class defining the protocol for CHK Map nodes.
450
451
    :ivar _raw_size: The total size of the serialized key:value data, before
452
        adding the header bytes, and without prefix compression.
453
    """
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
454
455
    def __init__(self, key_width=1):
456
        """Create a node.
457
458
        :param key_width: The width of keys for this node.
459
        """
460
        self._key = None
461
        # Current number of elements
462
        self._len = 0
463
        self._maximum_size = 0
464
        self._key_width = 1
465
        # current size in bytes
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
466
        self._raw_size = 0
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
467
        # The pointers/values this node has - meaning defined by child classes.
468
        self._items = {}
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
469
        # The common search prefix
470
        self._search_prefix = None
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
471
3735.9.4 by John Arbash Meinel
Some small cleanups, and fix _dump_tree to handle in-progress nodes.
472
    def __repr__(self):
473
        items_str = sorted(self._items)
474
        if len(items_str) > 20:
475
            items_str = items_str[16] + '...]'
3735.15.3 by John Arbash Meinel
repr update
476
        return '%s(key:%s len:%s size:%s max:%s prefix:%s items:%s)' % (
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
477
            self.__class__.__name__, self._key, self._len, self._raw_size,
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
478
            self._maximum_size, self._search_prefix, items_str)
3735.9.4 by John Arbash Meinel
Some small cleanups, and fix _dump_tree to handle in-progress nodes.
479
3735.2.38 by Robert Collins
Sufficient fixes to allow bzr-search to index a dev3 format repository.
480
    def key(self):
481
        return self._key
482
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
483
    def __len__(self):
484
        return self._len
485
486
    @property
487
    def maximum_size(self):
488
        """What is the upper limit for adding references to a node."""
489
        return self._maximum_size
490
491
    def set_maximum_size(self, new_size):
492
        """Set the size threshold for nodes.
493
494
        :param new_size: The size at which no data is added to a node. 0 for
495
            unlimited.
496
        """
497
        self._maximum_size = new_size
498
3735.15.5 by John Arbash Meinel
Change the nomenclature.
499
    @classmethod
500
    def common_prefix(cls, prefix, key):
501
        """Given 2 strings, return the longest prefix common to both.
502
503
        :param prefix: This has been the common prefix for other keys, so it is
504
            more likely to be the common prefix in this case as well.
505
        :param key: Another string to compare to
506
        """
507
        if key.startswith(prefix):
508
            return prefix
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
509
        # Is there a better way to do this?
3735.15.5 by John Arbash Meinel
Change the nomenclature.
510
        for pos, (left, right) in enumerate(zip(prefix, key)):
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
511
            if left != right:
512
                break
3735.2.86 by Vincent Ladeuil
Stop using assert in code.
513
        common = prefix[:pos]
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
514
        return common
515
3735.15.5 by John Arbash Meinel
Change the nomenclature.
516
    @classmethod
517
    def common_prefix_for_keys(cls, keys):
518
        """Given a list of keys, find their common prefix.
519
520
        :param keys: An iterable of strings.
521
        :return: The longest common prefix of all keys.
522
        """
523
        common_prefix = None
524
        for key in keys:
525
            if common_prefix is None:
526
                common_prefix = key
527
                continue
528
            common_prefix = cls.common_prefix(common_prefix, key)
529
            if not common_prefix:
530
                # if common_prefix is the empty string, then we know it won't
531
                # change further
532
                return ''
533
        return common_prefix
534
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
535
536
class LeafNode(Node):
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
537
    """A node containing actual key:value pairs.
3735.11.1 by John Arbash Meinel
Clean up some trailing whitespace.
538
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
539
    :ivar _items: A dict of key->value items. The key is in tuple form.
3735.15.4 by John Arbash Meinel
Clean up some little bits.
540
    :ivar _size: The number of bytes that would be used by serializing all of
541
        the key/value pairs.
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
542
    """
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
543
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
544
    def __init__(self, search_key_func=None):
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
545
        Node.__init__(self)
3735.15.4 by John Arbash Meinel
Clean up some little bits.
546
        # All of the keys in this leaf node share this common prefix
3735.15.5 by John Arbash Meinel
Change the nomenclature.
547
        self._common_serialised_prefix = None
548
        self._serialise_key = '\x00'.join
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
549
        if search_key_func is None:
3735.16.6 by John Arbash Meinel
Include a _search_key_plain function.
550
            self._search_key_func = _search_key_plain
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
551
        else:
552
            self._search_key_func = search_key_func
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
553
554
    def _current_size(self):
3735.15.4 by John Arbash Meinel
Clean up some little bits.
555
        """Answer the current serialised size of this node.
556
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
557
        This differs from self._raw_size in that it includes the bytes used for
558
        the header.
3735.15.4 by John Arbash Meinel
Clean up some little bits.
559
        """
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
560
        if self._common_serialised_prefix is None:
561
            bytes_for_items = 0
3735.17.1 by John Arbash Meinel
Change the serialized form for leaf nodes.
562
            prefix_len = 0
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
563
        else:
564
            # We will store a single string with the common prefix
565
            # And then that common prefix will not be stored in any of the
566
            # entry lines
567
            prefix_len = len(self._common_serialised_prefix)
3735.17.1 by John Arbash Meinel
Change the serialized form for leaf nodes.
568
            bytes_for_items = (self._raw_size - (prefix_len * self._len))
569
        return (9 # 'chkleaf:\n'
570
            + len(str(self._maximum_size)) + 1
571
            + len(str(self._key_width)) + 1
572
            + len(str(self._len)) + 1
573
            + prefix_len + 1
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
574
            + bytes_for_items)
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
575
576
    @classmethod
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
577
    def deserialise(klass, bytes, key, search_key_func=None):
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
578
        """Deserialise bytes, with key key, into a LeafNode.
579
580
        :param bytes: The bytes of the node.
581
        :param key: The key that the serialised node has.
582
        """
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
583
        result = LeafNode(search_key_func=search_key_func)
3735.2.72 by John Arbash Meinel
Change deserialise to properly handle when there is a '\r' in the key.
584
        # Splitlines can split on '\r' so don't use it, split('\n') adds an
585
        # extra '' if the bytes ends in a final newline.
586
        lines = bytes.split('\n')
587
        assert lines[-1] == ''
588
        lines.pop(-1)
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
589
        items = {}
590
        if lines[0] != 'chkleaf:':
591
            raise ValueError("not a serialised leaf node: %r" % bytes)
592
        maximum_size = int(lines[1])
593
        width = int(lines[2])
594
        length = int(lines[3])
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
595
        prefix = lines[4]
3735.17.1 by John Arbash Meinel
Change the serialized form for leaf nodes.
596
        pos = 5
597
        while pos < len(lines):
598
            elements = (prefix + lines[pos]).split('\x00')
599
            pos += 1
600
            assert len(elements) == width + 1
601
            num_value_lines = int(elements[-1])
602
            value_lines = lines[pos:pos+num_value_lines]
603
            pos += num_value_lines
604
            value = '\n'.join(value_lines)
605
            items[tuple(elements[:-1])] = value
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
606
        if len(items) != length:
3735.14.3 by John Arbash Meinel
Properly remove keys that are found in the page cache. And add some debugging.
607
            raise AssertionError("item count (%d) mismatch for key %s,"
608
                " bytes %r" % (length, key, bytes))
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
609
        result._items = items
610
        result._len = length
611
        result._maximum_size = maximum_size
612
        result._key = key
613
        result._key_width = width
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
614
        result._raw_size = (sum(map(len, lines[5:])) # the length of the suffix
3735.17.1 by John Arbash Meinel
Change the serialized form for leaf nodes.
615
            + (length)*(len(prefix))
616
            + (len(lines)-5))
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
617
        result._compute_search_prefix()
3735.15.5 by John Arbash Meinel
Change the nomenclature.
618
        result._compute_serialised_prefix()
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
619
        if len(bytes) != result._current_size():
620
            import pdb; pdb.set_trace()
3735.15.8 by John Arbash Meinel
Add asserts so that when serializing and deserializing
621
        assert len(bytes) == result._current_size()
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
622
        return result
623
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
624
    def iteritems(self, store, key_filter=None):
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
625
        """Iterate over items in the node.
626
627
        :param key_filter: A filter to apply to the node. It should be a
628
            list/set/dict or similar repeatedly iterable container.
629
        """
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
630
        if key_filter is not None:
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
631
            # Adjust the filter - short elements go to a prefix filter. Would this
632
            # be cleaner explicitly? That would be no harder for InternalNode..
633
            # XXX: perhaps defaultdict? Profiling<rinse and repeat>
634
            filters = {}
635
            for key in key_filter:
636
                length_filter = filters.setdefault(len(key), set())
637
                length_filter.add(key)
638
            filters = filters.items()
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
639
            for item in self._items.iteritems():
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
640
                for length, length_filter in filters:
641
                    if item[0][:length] in length_filter:
642
                        yield item
643
                        break
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
644
        else:
645
            for item in self._items.iteritems():
646
                yield item
647
3735.9.4 by John Arbash Meinel
Some small cleanups, and fix _dump_tree to handle in-progress nodes.
648
    def _key_value_len(self, key, value):
649
        # TODO: Should probably be done without actually joining the key, but
650
        #       then that can be done via the C extension
3735.17.1 by John Arbash Meinel
Change the serialized form for leaf nodes.
651
        return (len(self._serialise_key(key)) + 1
652
                + len(str(value.count('\n'))) + 1
653
                + len(value) + 1)
3735.9.4 by John Arbash Meinel
Some small cleanups, and fix _dump_tree to handle in-progress nodes.
654
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
655
    def _search_key(self, key):
656
        return self._search_key_func(key)
657
3735.11.13 by John Arbash Meinel
Refactor the LeafNode.map() code so we can do _check_remap more cheaply.
658
    def _map_no_split(self, key, value):
659
        """Map a key to a value.
660
661
        This assumes either the key does not already exist, or you have already
662
        removed its size and length from self.
663
664
        :return: True if adding this node should cause us to split.
665
        """
666
        self._items[key] = value
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
667
        self._raw_size += self._key_value_len(key, value)
3735.11.13 by John Arbash Meinel
Refactor the LeafNode.map() code so we can do _check_remap more cheaply.
668
        self._len += 1
3735.15.5 by John Arbash Meinel
Change the nomenclature.
669
        serialised_key = self._serialise_key(key)
670
        if self._common_serialised_prefix is None:
671
            self._common_serialised_prefix = serialised_key
672
        else:
673
            self._common_serialised_prefix = self.common_prefix(
674
                self._common_serialised_prefix, serialised_key)
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
675
        search_key = self._search_key(key)
676
        if self._search_prefix is None:
677
            self._search_prefix = search_key
3735.15.5 by John Arbash Meinel
Change the nomenclature.
678
        else:
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
679
            self._search_prefix = self.common_prefix(
680
                self._search_prefix, search_key)
3735.11.13 by John Arbash Meinel
Refactor the LeafNode.map() code so we can do _check_remap more cheaply.
681
        if (self._len > 1
682
            and self._maximum_size
3735.16.10 by John Arbash Meinel
Don't track state for an infrequent edge case.
683
            and self._current_size() > self._maximum_size):
684
            # Check to see if all of the search_keys for this node are
685
            # identical. We allow the node to grow under that circumstance
686
            # (we could track this as common state, but it is infrequent)
687
            if (search_key != self._search_prefix
688
                or not self._are_search_keys_identical()):
689
                return True
3735.11.13 by John Arbash Meinel
Refactor the LeafNode.map() code so we can do _check_remap more cheaply.
690
        return False
691
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
692
    def _split(self, store):
693
        """We have overflowed.
694
695
        Split this node into multiple LeafNodes, return it up the stack so that
696
        the next layer creates a new InternalNode and references the new nodes.
697
3735.15.5 by John Arbash Meinel
Change the nomenclature.
698
        :return: (common_serialised_prefix, [(node_serialised_prefix, node)])
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
699
        """
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
700
        common_prefix = self._search_prefix
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
701
        split_at = len(common_prefix) + 1
702
        result = {}
703
        for key, value in self._items.iteritems():
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
704
            search_key = self._search_key(key)
705
            prefix = search_key[:split_at]
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
706
            # TODO: Generally only 1 key can be exactly the right length,
707
            #       which means we can only have 1 key in the node pointed
708
            #       at by the 'prefix\0' key. We might want to consider
709
            #       folding it into the containing InternalNode rather than
710
            #       having a fixed length-1 node.
711
            #       Note this is probably not true for hash keys, as they
712
            #       may get a '\00' node anywhere, but won't have keys of
713
            #       different lengths.
714
            if len(prefix) < split_at:
715
                prefix += '\x00'*(split_at - len(prefix))
716
            if prefix not in result:
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
717
                node = LeafNode(search_key_func=self._search_key_func)
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
718
                node.set_maximum_size(self._maximum_size)
719
                node._key_width = self._key_width
720
                result[prefix] = node
721
            else:
722
                node = result[prefix]
723
            node.map(store, key, value)
724
        return common_prefix, result.items()
725
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
726
    def map(self, store, key, value):
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
727
        """Map key to value."""
728
        if key in self._items:
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
729
            self._raw_size -= self._key_value_len(key, self._items[key])
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
730
            self._len -= 1
731
        self._key = None
3735.11.13 by John Arbash Meinel
Refactor the LeafNode.map() code so we can do _check_remap more cheaply.
732
        if self._map_no_split(key, value):
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
733
            return self._split(store)
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
734
        else:
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
735
            return self._search_prefix, [("", self)]
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
736
737
    def serialise(self, store):
738
        """Serialise the tree to store.
739
740
        :param store: A VersionedFiles honouring the CHK extensions.
741
        :return: An iterable of the keys inserted by this operation.
742
        """
743
        lines = ["chkleaf:\n"]
744
        lines.append("%d\n" % self._maximum_size)
745
        lines.append("%d\n" % self._key_width)
746
        lines.append("%d\n" % self._len)
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
747
        if self._common_serialised_prefix is None:
748
            lines.append('\n')
3735.17.1 by John Arbash Meinel
Change the serialized form for leaf nodes.
749
            assert len(self._items) == 0
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
750
        else:
751
            lines.append('%s\n' % (self._common_serialised_prefix,))
752
            prefix_len = len(self._common_serialised_prefix)
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
753
        for key, value in sorted(self._items.items()):
3735.17.1 by John Arbash Meinel
Change the serialized form for leaf nodes.
754
            # Add always add a final newline
755
            value_lines = osutils.chunks_to_lines([value + '\n'])
756
            serialized = "%s\x00%s\n" % (self._serialise_key(key),
757
                                         len(value_lines))
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
758
            assert serialized.startswith(self._common_serialised_prefix)
759
            lines.append(serialized[prefix_len:])
3735.17.1 by John Arbash Meinel
Change the serialized form for leaf nodes.
760
            lines.extend(value_lines)
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
761
        sha1, _, _ = store.add_lines((None,), (), lines)
762
        self._key = ("sha1:" + sha1,)
3735.15.8 by John Arbash Meinel
Add asserts so that when serializing and deserializing
763
        bytes = ''.join(lines)
3735.15.9 by John Arbash Meinel
(broken) Initial prototype of leaf pages which pull out their common prefix.
764
        if len(bytes) != self._current_size():
765
            import pdb; pdb.set_trace()
3735.15.8 by John Arbash Meinel
Add asserts so that when serializing and deserializing
766
        assert len(bytes) == self._current_size()
767
        _page_cache.add(self._key, bytes)
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
768
        return [self._key]
769
3735.2.26 by Robert Collins
CHKInventory migrated to new CHKMap code.
770
    def refs(self):
771
        """Return the references to other CHK's held by this node."""
772
        return []
773
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
774
    def _compute_search_prefix(self):
775
        """Determine the common search prefix for all keys in this node.
3735.15.5 by John Arbash Meinel
Change the nomenclature.
776
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
777
        :return: A bytestring of the longest search key prefix that is
3735.15.5 by John Arbash Meinel
Change the nomenclature.
778
            unique within this node.
779
        """
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
780
        search_keys = [self._search_key(key) for key in self._items]
781
        self._search_prefix = self.common_prefix_for_keys(search_keys)
782
        return self._search_prefix
3735.15.5 by John Arbash Meinel
Change the nomenclature.
783
3735.16.10 by John Arbash Meinel
Don't track state for an infrequent edge case.
784
    def _are_search_keys_identical(self):
785
        """Check to see if the search keys for all entries are the same.
786
787
        When using a hash as the search_key it is possible for non-identical
788
        keys to collide. If that happens enough, we may try overflow a
789
        LeafNode, but as all are collisions, we must not split.
790
        """
791
        common_search_key = None
792
        for key in self._items:
793
            search_key = self._search_key(key)
794
            if common_search_key is None:
795
                common_search_key = search_key
796
            elif search_key != common_search_key:
797
                return False
798
        return True
799
3735.15.5 by John Arbash Meinel
Change the nomenclature.
800
    def _compute_serialised_prefix(self):
801
        """Determine the common prefix for serialised keys in this node.
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
802
803
        :return: A bytestring of the longest serialised key prefix that is
804
            unique within this node.
805
        """
3735.15.5 by John Arbash Meinel
Change the nomenclature.
806
        serialised_keys = [self._serialise_key(key) for key in self._items]
807
        self._common_serialised_prefix = self.common_prefix_for_keys(
808
            serialised_keys)
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
809
810
    def unmap(self, store, key):
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
811
        """Unmap key from the node."""
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
812
        self._raw_size -= self._key_value_len(key, self._items[key])
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
813
        self._len -= 1
814
        del self._items[key]
815
        self._key = None
3735.15.2 by John Arbash Meinel
Change LeafNode to also cache its unique serialized prefix.
816
        # Recompute from scratch
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
817
        self._compute_search_prefix()
3735.15.5 by John Arbash Meinel
Change the nomenclature.
818
        self._compute_serialised_prefix()
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
819
        return self
820
821
822
class InternalNode(Node):
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
823
    """A node that contains references to other nodes.
3735.11.1 by John Arbash Meinel
Clean up some trailing whitespace.
824
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
825
    An InternalNode is responsible for mapping search key prefixes to child
3735.15.5 by John Arbash Meinel
Change the nomenclature.
826
    nodes.
3735.15.4 by John Arbash Meinel
Clean up some little bits.
827
3735.15.5 by John Arbash Meinel
Change the nomenclature.
828
    :ivar _items: serialised_key => node dictionary. node may be a tuple,
3735.15.4 by John Arbash Meinel
Clean up some little bits.
829
        LeafNode or InternalNode.
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
830
    """
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
831
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
832
    def __init__(self, prefix='', search_key_func=None):
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
833
        Node.__init__(self)
834
        # The size of an internalnode with default values and no children.
835
        # How many octets key prefixes within this node are.
836
        self._node_width = 0
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
837
        self._search_prefix = prefix
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
838
        if search_key_func is None:
3735.16.6 by John Arbash Meinel
Include a _search_key_plain function.
839
            self._search_key_func = _search_key_plain
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
840
        else:
841
            self._search_key_func = search_key_func
3735.9.5 by John Arbash Meinel
Don't allow an InternalNode to add a key that doesn't fit.
842
843
    def __repr__(self):
844
        items_str = sorted(self._items)
845
        if len(items_str) > 20:
846
            items_str = items_str[16] + '...]'
847
        return '%s(key:%s len:%s size:%s max:%s prefix:%s items:%s)' % (
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
848
            self.__class__.__name__, self._key, self._len, self._raw_size,
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
849
            self._maximum_size, self._search_prefix, items_str)
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
850
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
851
    def add_node(self, prefix, node):
852
        """Add a child node with prefix prefix, and node node.
853
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
854
        :param prefix: The search key prefix for node.
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
855
        :param node: The node being added.
856
        """
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
857
        assert self._search_prefix is not None
858
        assert prefix.startswith(self._search_prefix)
859
        assert len(prefix) == len(self._search_prefix) + 1
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
860
        self._len += len(node)
861
        if not len(self._items):
862
            self._node_width = len(prefix)
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
863
        assert self._node_width == len(self._search_prefix) + 1
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
864
        self._items[prefix] = node
865
        self._key = None
866
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
867
    def _current_size(self):
868
        """Answer the current serialised size of this node."""
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
869
        return (self._raw_size + len(str(self._len)) + len(str(self._key_width)) +
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
870
            len(str(self._maximum_size)))
871
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
872
    @classmethod
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
873
    def deserialise(klass, bytes, key, search_key_func=None):
3735.2.25 by Robert Collins
CHKInventory core tests passing.
874
        """Deserialise bytes to an InternalNode, with key key.
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
875
876
        :param bytes: The bytes of the node.
877
        :param key: The key that the serialised node has.
878
        :return: An InternalNode instance.
879
        """
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
880
        result = InternalNode(search_key_func=search_key_func)
3735.2.72 by John Arbash Meinel
Change deserialise to properly handle when there is a '\r' in the key.
881
        # Splitlines can split on '\r' so don't use it, remove the extra ''
882
        # from the result of split('\n') because we should have a trailing
883
        # newline
884
        lines = bytes.split('\n')
885
        assert lines[-1] == ''
886
        lines.pop(-1)
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
887
        items = {}
888
        if lines[0] != 'chknode:':
889
            raise ValueError("not a serialised internal node: %r" % bytes)
890
        maximum_size = int(lines[1])
891
        width = int(lines[2])
892
        length = int(lines[3])
3735.15.11 by John Arbash Meinel
Change the InternalNodes to also pull out the common prefix.
893
        common_prefix = lines[4]
894
        for line in lines[5:]:
895
            line = common_prefix + line
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
896
            prefix, flat_key = line.rsplit('\x00', 1)
897
            items[prefix] = (flat_key,)
898
        result._items = items
899
        result._len = length
900
        result._maximum_size = maximum_size
901
        result._key = key
902
        result._key_width = width
3735.15.6 by John Arbash Meinel
Add tests that LeafNodes track the common prefix for both their lookup keys
903
        # XXX: InternalNodes don't really care about their size, and this will
904
        #      change if we add prefix compression
905
        result._raw_size = None # len(bytes)
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
906
        result._node_width = len(prefix)
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
907
        result._compute_search_prefix()
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
908
        return result
909
910
    def iteritems(self, store, key_filter=None):
911
        for node in self._iter_nodes(store, key_filter=key_filter):
912
            for item in node.iteritems(store, key_filter=key_filter):
913
                yield item
914
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
915
    def _iter_nodes(self, store, key_filter=None, batch_size=None):
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
916
        """Iterate over node objects which match key_filter.
917
918
        :param store: A store to use for accessing content.
919
        :param key_filter: A key filter to filter nodes. Only nodes that might
920
            contain a key in key_filter will be returned.
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
921
        :param batch_size: If not None, then we will return the nodes that had
922
            to be read using get_record_stream in batches, rather than reading
923
            them all at once.
924
        :return: An iterable of nodes. This function does not have to be fully
925
            consumed.  (There will be no pending I/O when items are being returned.)
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
926
        """
3735.2.31 by Robert Collins
CHKMap.iter_changes
927
        keys = {}
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
928
        if key_filter is None:
3735.2.31 by Robert Collins
CHKMap.iter_changes
929
            for prefix, node in self._items.iteritems():
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
930
                if type(node) == tuple:
3735.2.31 by Robert Collins
CHKMap.iter_changes
931
                    keys[node] = prefix
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
932
                else:
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
933
                    yield node
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
934
        else:
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
935
            # XXX defaultdict ?
936
            length_filters = {}
937
            for key in key_filter:
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
938
                search_key = self._search_prefix_filter(key)
939
                length_filter = length_filters.setdefault(
940
                                    len(search_key), set())
941
                length_filter.add(search_key)
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
942
            length_filters = length_filters.items()
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
943
            for prefix, node in self._items.iteritems():
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
944
                for length, length_filter in length_filters:
945
                    if prefix[:length] in length_filter:
946
                        if type(node) == tuple:
947
                            keys[node] = prefix
948
                        else:
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
949
                            yield node
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
950
                        break
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
951
        if keys:
3735.2.62 by Robert Collins
Create a rudimentary CHK page cache.
952
            # Look in the page cache for some more bytes
953
            found_keys = set()
954
            for key in keys:
955
                try:
956
                    bytes = _page_cache[key]
957
                except KeyError:
958
                    continue
959
                else:
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
960
                    node = _deserialise(bytes, key,
961
                        search_key_func=self._search_key_func)
3735.2.62 by Robert Collins
Create a rudimentary CHK page cache.
962
                    self._items[keys[key]] = node
963
                    found_keys.add(key)
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
964
                    yield node
3735.2.62 by Robert Collins
Create a rudimentary CHK page cache.
965
            for key in found_keys:
966
                del keys[key]
967
        if keys:
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
968
            # demand load some pages.
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
969
            if batch_size is None:
970
                # Read all the keys in
971
                batch_size = len(keys)
972
            key_order = list(keys)
973
            for batch_start in range(0, len(key_order), batch_size):
974
                batch = key_order[batch_start:batch_start + batch_size]
975
                # We have to fully consume the stream so there is no pending
976
                # I/O, so we buffer the nodes for now.
977
                stream = store.get_record_stream(batch, 'unordered', True)
978
                nodes = []
979
                for record in stream:
980
                    bytes = record.get_bytes_as('fulltext')
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
981
                    node = _deserialise(bytes, record.key,
982
                        search_key_func=self._search_key_func)
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
983
                    nodes.append(node)
984
                    self._items[keys[record.key]] = node
985
                    _page_cache.add(record.key, bytes)
986
                for node in nodes:
987
                    yield node
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
988
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
989
    def map(self, store, key, value):
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
990
        """Map key to value."""
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
991
        if not len(self._items):
992
            raise AssertionError("cant map in an empty InternalNode.")
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
993
        search_key = self._search_key(key)
994
        assert self._node_width == len(self._search_prefix) + 1
995
        if not search_key.startswith(self._search_prefix):
3735.9.11 by John Arbash Meinel
Handle when an InternalNode decides it needs to split.
996
            # This key doesn't fit in this index, so we need to split at the
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
997
            # point where it would fit, insert self into that internal node,
998
            # and then map this key into that node.
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
999
            new_prefix = self.common_prefix(self._search_prefix,
1000
                                            search_key)
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
1001
            new_parent = InternalNode(new_prefix,
1002
                search_key_func=self._search_key_func)
3735.9.5 by John Arbash Meinel
Don't allow an InternalNode to add a key that doesn't fit.
1003
            new_parent.set_maximum_size(self._maximum_size)
1004
            new_parent._key_width = self._key_width
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1005
            new_parent.add_node(self._search_prefix[:len(new_prefix)+1],
3735.15.1 by John Arbash Meinel
Change InternalNode to always cache its serialized_prefix.
1006
                                self)
3735.9.5 by John Arbash Meinel
Don't allow an InternalNode to add a key that doesn't fit.
1007
            return new_parent.map(store, key, value)
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
1008
        children = list(self._iter_nodes(store, key_filter=[key]))
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1009
        if children:
1010
            child = children[0]
1011
        else:
1012
            # new child needed:
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1013
            child = self._new_child(search_key, LeafNode)
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
1014
        old_len = len(child)
3735.11.11 by John Arbash Meinel
Add logic to map() so that it can also collapse when necessary.
1015
        if isinstance(child, LeafNode):
1016
            old_size = child._current_size()
1017
        else:
1018
            old_size = None
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1019
        prefix, node_details = child.map(store, key, value)
1020
        if len(node_details) == 1:
3735.9.11 by John Arbash Meinel
Handle when an InternalNode decides it needs to split.
1021
            # child may have shrunk, or might be a new node
1022
            child = node_details[0][1]
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1023
            self._len = self._len - old_len + len(child)
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1024
            self._items[search_key] = child
3735.2.29 by Robert Collins
Untested code is broken code.
1025
            self._key = None
3735.11.11 by John Arbash Meinel
Add logic to map() so that it can also collapse when necessary.
1026
            new_node = self
1027
            if (isinstance(child, LeafNode)
1028
                and (old_size is None or child._current_size() < old_size)):
1029
                # The old node was an InternalNode which means it has now
1030
                # collapsed, so we need to check if it will chain to a collapse
1031
                # at this level. Or the LeafNode has shrunk in size, so we need
1032
                # to check that as well.
1033
                new_node = self._check_remap(store)
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1034
            assert new_node._search_prefix is not None
1035
            return new_node._search_prefix, [('', new_node)]
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1036
        # child has overflown - create a new intermediate node.
1037
        # XXX: This is where we might want to try and expand our depth
1038
        # to refer to more bytes of every child (which would give us
1039
        # multiple pointers to child nodes, but less intermediate nodes)
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1040
        child = self._new_child(search_key, InternalNode)
1041
        child._search_prefix = prefix
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1042
        for split, node in node_details:
1043
            child.add_node(split, node)
1044
        self._len = self._len - old_len + len(child)
3735.2.29 by Robert Collins
Untested code is broken code.
1045
        self._key = None
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1046
        return self._search_prefix, [("", self)]
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1047
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1048
    def _new_child(self, search_key, klass):
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1049
        """Create a new child node of type klass."""
1050
        child = klass()
1051
        child.set_maximum_size(self._maximum_size)
1052
        child._key_width = self._key_width
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
1053
        child._search_key_func = self._search_key_func
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1054
        self._items[search_key] = child
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1055
        return child
1056
1057
    def serialise(self, store):
1058
        """Serialise the node to store.
1059
1060
        :param store: A VersionedFiles honouring the CHK extensions.
1061
        :return: An iterable of the keys inserted by this operation.
1062
        """
1063
        for node in self._items.itervalues():
1064
            if type(node) == tuple:
1065
                # Never deserialised.
1066
                continue
1067
            if node._key is not None:
1068
                # Never altered
1069
                continue
1070
            for key in node.serialise(store):
1071
                yield key
1072
        lines = ["chknode:\n"]
1073
        lines.append("%d\n" % self._maximum_size)
1074
        lines.append("%d\n" % self._key_width)
1075
        lines.append("%d\n" % self._len)
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1076
        assert self._search_prefix is not None
1077
        lines.append('%s\n' % (self._search_prefix,))
1078
        prefix_len = len(self._search_prefix)
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1079
        for prefix, node in sorted(self._items.items()):
1080
            if type(node) == tuple:
1081
                key = node[0]
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
1082
            else:
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1083
                key = node._key[0]
3735.15.11 by John Arbash Meinel
Change the InternalNodes to also pull out the common prefix.
1084
            serialised = "%s\x00%s\n" % (prefix, key)
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1085
            assert serialised.startswith(self._search_prefix)
3735.15.11 by John Arbash Meinel
Change the InternalNodes to also pull out the common prefix.
1086
            lines.append(serialised[prefix_len:])
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1087
        sha1, _, _ = store.add_lines((None,), (), lines)
1088
        self._key = ("sha1:" + sha1,)
3735.2.63 by Robert Collins
Divert writes into the CHK page cache as well.
1089
        _page_cache.add(self._key, ''.join(lines))
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1090
        yield self._key
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
1091
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1092
    def _search_key(self, key):
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
1093
        """Return the serialised key for key in this node."""
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1094
        # search keys are fixed width. All will be self._node_width wide, so we
3735.15.5 by John Arbash Meinel
Change the nomenclature.
1095
        # pad as necessary.
3735.16.1 by John Arbash Meinel
(broken) Start tracking down more code that needs to pass around the 'search_key_func'
1096
        return (self._search_key_func(key) + '\x00'*self._node_width)[:self._node_width]
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
1097
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1098
    def _search_prefix_filter(self, key):
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
1099
        """Serialise key for use as a prefix filter in iteritems."""
1100
        if len(key) == self._key_width:
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1101
            return self._search_key(key)
3735.2.43 by Robert Collins
Teach CHKMap how to iter items in 2-tuple keyspaces.
1102
        return '\x00'.join(key)[:self._node_width]
1103
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1104
    def _split(self, offset):
1105
        """Split this node into smaller nodes starting at offset.
1106
1107
        :param offset: The offset to start the new child nodes at.
1108
        :return: An iterable of (prefix, node) tuples. prefix is a byte
1109
            prefix for reaching node.
1110
        """
1111
        if offset >= self._node_width:
1112
            for node in self._items.values():
1113
                for result in node._split(offset):
1114
                    yield result
1115
            return
1116
        for key, node in self._items.items():
1117
            pass
1118
3735.2.26 by Robert Collins
CHKInventory migrated to new CHKMap code.
1119
    def refs(self):
1120
        """Return the references to other CHK's held by this node."""
1121
        if self._key is None:
1122
            raise AssertionError("unserialised nodes have no refs.")
1123
        refs = []
1124
        for value in self._items.itervalues():
1125
            if type(value) == tuple:
1126
                refs.append(value)
1127
            else:
1128
                refs.append(value.key())
1129
        return refs
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1130
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1131
    def _compute_search_prefix(self, extra_key=None):
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1132
        """Return the unique key prefix for this node.
1133
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1134
        :return: A bytestring of the longest search key prefix that is
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1135
            unique within this node.
1136
        """
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1137
        self._search_prefix = self.common_prefix_for_keys(self._items)
1138
        return self._search_prefix
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1139
1140
    def unmap(self, store, key):
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
1141
        """Remove key from this node and it's children."""
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1142
        if not len(self._items):
1143
            raise AssertionError("cant unmap in an empty InternalNode.")
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
1144
        children = list(self._iter_nodes(store, key_filter=[key]))
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1145
        if children:
1146
            child = children[0]
1147
        else:
1148
            raise KeyError(key)
1149
        self._len -= 1
1150
        unmapped = child.unmap(store, key)
3735.11.3 by John Arbash Meinel
At the end of unmap() see if children can be packed into a single Leaf.
1151
        self._key = None
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1152
        search_key = self._search_key(key)
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1153
        if len(unmapped) == 0:
1154
            # All child nodes are gone, remove the child:
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1155
            del self._items[search_key]
3735.11.3 by John Arbash Meinel
At the end of unmap() see if children can be packed into a single Leaf.
1156
            unmapped = None
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1157
        else:
1158
            # Stash the returned node
3735.15.13 by John Arbash Meinel
Change the term 'lookup' to the term 'search', as it is closer to what Robert envisioned.
1159
            self._items[search_key] = unmapped
3735.2.23 by Robert Collins
Test unmapping with one child left but multiple keys.
1160
        if len(self._items) == 1:
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1161
            # this node is no longer needed:
1162
            return self._items.values()[0]
3735.11.10 by John Arbash Meinel
Change how _check_remap works so it doesn't have to load all keys.
1163
        if isinstance(unmapped, InternalNode):
1164
            return self
1165
        return self._check_remap(store)
1166
1167
    def _check_remap(self, store):
3735.11.11 by John Arbash Meinel
Add logic to map() so that it can also collapse when necessary.
1168
        """Check if all keys contained by children fit in a single LeafNode.
1169
1170
        :param store: A store to use for reading more nodes
1171
        :return: Either self, or a new LeafNode which should replace self.
1172
        """
3735.11.10 by John Arbash Meinel
Change how _check_remap works so it doesn't have to load all keys.
1173
        # Logic for how we determine when we need to rebuild
3735.11.3 by John Arbash Meinel
At the end of unmap() see if children can be packed into a single Leaf.
1174
        # 1) Implicitly unmap() is removing a key which means that the child
1175
        #    nodes are going to be shrinking by some extent.
1176
        # 2) If all children are LeafNodes, it is possible that they could be
1177
        #    combined into a single LeafNode, which can then completely replace
1178
        #    this internal node with a single LeafNode
1179
        # 3) If *one* child is an InternalNode, we assume it has already done
1180
        #    all the work to determine that its children cannot collapse, and
1181
        #    we can then assume that those nodes *plus* the current nodes don't
1182
        #    have a chance of collapsing either.
1183
        #    So a very cheap check is to just say if 'unmapped' is an
1184
        #    InternalNode, we don't have to check further.
3735.11.10 by John Arbash Meinel
Change how _check_remap works so it doesn't have to load all keys.
1185
3735.11.3 by John Arbash Meinel
At the end of unmap() see if children can be packed into a single Leaf.
1186
        # TODO: Another alternative is to check the total size of all known
1187
        #       LeafNodes. If there is some formula we can use to determine the
1188
        #       final size without actually having to read in any more
1189
        #       children, it would be nice to have. However, we have to be
1190
        #       careful with stuff like nodes that pull out the common prefix
1191
        #       of each key, as adding a new key can change the common prefix
1192
        #       and cause size changes greater than the length of one key.
1193
        #       So for now, we just add everything to a new Leaf until it
1194
        #       splits, as we know that will give the right answer
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
1195
        new_leaf = LeafNode(search_key_func=self._search_key_func)
3735.11.3 by John Arbash Meinel
At the end of unmap() see if children can be packed into a single Leaf.
1196
        new_leaf.set_maximum_size(self._maximum_size)
1197
        new_leaf._key_width = self._key_width
3735.14.7 by John Arbash Meinel
Change _iter_nodes into a generator.
1198
        # A batch_size of 16 was chosen because:
1199
        #   a) In testing, a 4k page held 14 times. So if we have more than 16
1200
        #      leaf nodes we are unlikely to hold them in a single new leaf
1201
        #      node. This still allows for 1 round trip
1202
        #   b) With 16-way fan out, we can still do a single round trip
1203
        #   c) With 255-way fan out, we don't want to read all 255 and destroy
1204
        #      the page cache, just to determine that we really don't need it.
1205
        for node in self._iter_nodes(store, batch_size=16):
1206
            if isinstance(node, InternalNode):
1207
                # Without looking at any leaf nodes, we are sure
1208
                return self
1209
            for key, value in node._items.iteritems():
1210
                if new_leaf._map_no_split(key, value):
3735.11.10 by John Arbash Meinel
Change how _check_remap works so it doesn't have to load all keys.
1211
                    return self
3735.11.3 by John Arbash Meinel
At the end of unmap() see if children can be packed into a single Leaf.
1212
        return new_leaf
3735.2.18 by Robert Collins
Partial multi-layer chk dictionary trees.
1213
1214
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
1215
def _deserialise(bytes, key, search_key_func):
3735.2.16 by Robert Collins
Untested extensions to support repodetails
1216
    """Helper for repositorydetails - convert bytes to a node."""
3735.2.24 by Robert Collins
test_chk_map tests all passing.
1217
    if bytes.startswith("chkleaf:\n"):
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
1218
        return LeafNode.deserialise(bytes, key, search_key_func=search_key_func)
3735.2.21 by Robert Collins
BROKEN: multi level CHKMap tries, unfinished, subsystem in flux.
1219
    elif bytes.startswith("chknode:\n"):
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
1220
        return InternalNode.deserialise(bytes, key,
1221
            search_key_func=search_key_func)
3735.2.16 by Robert Collins
Untested extensions to support repodetails
1222
    else:
1223
        raise AssertionError("Unknown node type.")
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1224
1225
3735.2.67 by John Arbash Meinel
Merge bzr.dev 3903 which brings in 'chunked' encoding.
1226
def _find_children_info(store, interesting_keys, uninteresting_keys, pb):
3735.9.7 by John Arbash Meinel
Cleanup pass.
1227
    """Read the associated records, and determine what is interesting."""
1228
    uninteresting_keys = set(uninteresting_keys)
1229
    chks_to_read = uninteresting_keys.union(interesting_keys)
1230
    next_uninteresting = set()
1231
    next_interesting = set()
1232
    uninteresting_items = set()
1233
    interesting_items = set()
1234
    interesting_records = []
3735.9.14 by John Arbash Meinel
Start using the iter_interesting_nodes.
1235
    # records_read = set()
3735.9.7 by John Arbash Meinel
Cleanup pass.
1236
    for record in store.get_record_stream(chks_to_read, 'unordered', True):
3735.9.14 by John Arbash Meinel
Start using the iter_interesting_nodes.
1237
        # records_read.add(record.key())
3735.9.17 by John Arbash Meinel
Pass around a progress bar and switch to using an adapter.
1238
        if pb is not None:
1239
            pb.tick()
3735.2.67 by John Arbash Meinel
Merge bzr.dev 3903 which brings in 'chunked' encoding.
1240
        bytes = record.get_bytes_as('fulltext')
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
1241
        # We don't care about search_key_func for this code, because we only
1242
        # care about external references.
1243
        node = _deserialise(bytes, record.key, search_key_func=None)
3735.9.7 by John Arbash Meinel
Cleanup pass.
1244
        if record.key in uninteresting_keys:
1245
            if isinstance(node, InternalNode):
3735.9.14 by John Arbash Meinel
Start using the iter_interesting_nodes.
1246
                next_uninteresting.update(node.refs())
3735.9.7 by John Arbash Meinel
Cleanup pass.
1247
            else:
3735.9.14 by John Arbash Meinel
Start using the iter_interesting_nodes.
1248
                # We know we are at a LeafNode, so we can pass None for the
1249
                # store
1250
                uninteresting_items.update(node.iteritems(None))
3735.9.7 by John Arbash Meinel
Cleanup pass.
1251
        else:
1252
            interesting_records.append(record)
1253
            if isinstance(node, InternalNode):
3735.9.14 by John Arbash Meinel
Start using the iter_interesting_nodes.
1254
                next_interesting.update(node.refs())
3735.9.7 by John Arbash Meinel
Cleanup pass.
1255
            else:
3735.9.14 by John Arbash Meinel
Start using the iter_interesting_nodes.
1256
                interesting_items.update(node.iteritems(None))
1257
    # TODO: Filter out records that have already been read, as node splitting
1258
    #       can cause us to reference the same nodes via shorter and longer
1259
    #       paths
3735.9.7 by John Arbash Meinel
Cleanup pass.
1260
    return (next_uninteresting, uninteresting_items,
1261
            next_interesting, interesting_records, interesting_items)
1262
1263
3735.9.19 by John Arbash Meinel
Refactor iter_interesting a little bit.
1264
def _find_all_uninteresting(store, interesting_root_keys,
1265
                            uninteresting_root_keys, adapter, pb):
1266
    """Determine the full set of uninteresting keys."""
1267
    # What about duplicates between interesting_root_keys and
1268
    # uninteresting_root_keys?
1269
    if not uninteresting_root_keys:
1270
        # Shortcut case. We know there is nothing uninteresting to filter out
1271
        # So we just let the rest of the algorithm do the work
1272
        # We know there is nothing uninteresting, and we didn't have to read
1273
        # any interesting records yet.
1274
        return (set(), set(), set(interesting_root_keys), [], set())
3735.9.7 by John Arbash Meinel
Cleanup pass.
1275
    all_uninteresting_chks = set(uninteresting_root_keys)
1276
    all_uninteresting_items = set()
1277
1278
    # First step, find the direct children of both the interesting and
1279
    # uninteresting set
1280
    (uninteresting_keys, uninteresting_items,
1281
     interesting_keys, interesting_records,
1282
     interesting_items) = _find_children_info(store, interesting_root_keys,
3735.9.17 by John Arbash Meinel
Pass around a progress bar and switch to using an adapter.
1283
                                              uninteresting_root_keys,
3735.2.67 by John Arbash Meinel
Merge bzr.dev 3903 which brings in 'chunked' encoding.
1284
                                              pb=pb)
3735.9.7 by John Arbash Meinel
Cleanup pass.
1285
    all_uninteresting_chks.update(uninteresting_keys)
1286
    all_uninteresting_items.update(uninteresting_items)
1287
    del uninteresting_items
1288
    # Note: Exact matches between interesting and uninteresting do not need
1289
    #       to be search further. Non-exact matches need to be searched in case
1290
    #       there is a future exact-match
1291
    uninteresting_keys.difference_update(interesting_keys)
1292
3735.9.6 by John Arbash Meinel
Add a first pass to the interesting search.
1293
    # Second, find the full set of uninteresting bits reachable by the
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1294
    # uninteresting roots
3735.9.7 by John Arbash Meinel
Cleanup pass.
1295
    chks_to_read = uninteresting_keys
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1296
    while chks_to_read:
1297
        next_chks = set()
3735.9.17 by John Arbash Meinel
Pass around a progress bar and switch to using an adapter.
1298
        for record in store.get_record_stream(chks_to_read, 'unordered', False):
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1299
            # TODO: Handle 'absent'
3735.9.17 by John Arbash Meinel
Pass around a progress bar and switch to using an adapter.
1300
            if pb is not None:
1301
                pb.tick()
3735.2.67 by John Arbash Meinel
Merge bzr.dev 3903 which brings in 'chunked' encoding.
1302
            if record.storage_kind in ('fulltext', 'chunked'):
1303
                bytes = record.get_bytes_as('fulltext')
1304
            else:
3735.9.17 by John Arbash Meinel
Pass around a progress bar and switch to using an adapter.
1305
                bytes = adapter.get_bytes(record,
1306
                            record.get_bytes_as(record.storage_kind))
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
1307
            # We don't care about search_key_func for this code, because we
1308
            # only care about external references.
1309
            node = _deserialise(bytes, record.key, search_key_func=None)
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1310
            if isinstance(node, InternalNode):
1311
                # uninteresting_prefix_chks.update(node._items.iteritems())
1312
                chks = node._items.values()
1313
                # TODO: We remove the entries that are already in
1314
                #       uninteresting_chks ?
1315
                next_chks.update(chks)
3735.9.7 by John Arbash Meinel
Cleanup pass.
1316
                all_uninteresting_chks.update(chks)
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1317
            else:
3735.9.7 by John Arbash Meinel
Cleanup pass.
1318
                all_uninteresting_items.update(node._items.iteritems())
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1319
        chks_to_read = next_chks
3735.9.19 by John Arbash Meinel
Refactor iter_interesting a little bit.
1320
    return (all_uninteresting_chks, all_uninteresting_items,
1321
            interesting_keys, interesting_records, interesting_items)
1322
1323
1324
def iter_interesting_nodes(store, interesting_root_keys,
1325
                           uninteresting_root_keys, pb=None):
1326
    """Given root keys, find interesting nodes.
1327
1328
    Evaluate nodes referenced by interesting_root_keys. Ones that are also
1329
    referenced from uninteresting_root_keys are not considered interesting.
1330
1331
    :param interesting_root_keys: keys which should be part of the
1332
        "interesting" nodes (which will be yielded)
1333
    :param uninteresting_root_keys: keys which should be filtered out of the
1334
        result set.
1335
    :return: Yield
1336
        (interesting records, interesting chk's, interesting key:values)
1337
    """
1338
    # TODO: consider that it may be more memory efficient to use the 20-byte
1339
    #       sha1 string, rather than tuples of hexidecimal sha1 strings.
3735.2.68 by John Arbash Meinel
Add a TODO about avoiding all of the get_record_stream calls.
1340
    # TODO: Try to factor out a lot of the get_record_stream() calls into a
1341
    #       helper function similar to _read_bytes. This function should be
1342
    #       able to use nodes from the _page_cache as well as actually
1343
    #       requesting bytes from the store.
3735.9.19 by John Arbash Meinel
Refactor iter_interesting a little bit.
1344
1345
    # A way to adapt from the compressed texts back into fulltexts
1346
    # In a way, this seems like a layering inversion to have CHKMap know the
1347
    # details of versionedfile
1348
    adapter_class = versionedfile.adapter_registry.get(
1349
        ('knit-ft-gz', 'fulltext'))
1350
    adapter = adapter_class(store)
1351
1352
    (all_uninteresting_chks, all_uninteresting_items, interesting_keys,
1353
     interesting_records, interesting_items) = _find_all_uninteresting(store,
1354
        interesting_root_keys, uninteresting_root_keys, adapter, pb)
3735.9.7 by John Arbash Meinel
Cleanup pass.
1355
1356
    # Now that we know everything uninteresting, we can yield information from
1357
    # our first request
1358
    interesting_items.difference_update(all_uninteresting_items)
1359
    records = dict((record.key, record) for record in interesting_records
1360
                    if record.key not in all_uninteresting_chks)
3735.9.19 by John Arbash Meinel
Refactor iter_interesting a little bit.
1361
    if records or interesting_items:
1362
        yield records, interesting_items
3735.9.7 by John Arbash Meinel
Cleanup pass.
1363
    interesting_keys.difference_update(all_uninteresting_chks)
1364
1365
    chks_to_read = interesting_keys
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1366
    while chks_to_read:
1367
        next_chks = set()
3735.9.17 by John Arbash Meinel
Pass around a progress bar and switch to using an adapter.
1368
        for record in store.get_record_stream(chks_to_read, 'unordered', False):
1369
            if pb is not None:
1370
                pb.tick()
3735.9.7 by John Arbash Meinel
Cleanup pass.
1371
            # TODO: Handle 'absent'?
3735.2.67 by John Arbash Meinel
Merge bzr.dev 3903 which brings in 'chunked' encoding.
1372
            if record.storage_kind in ('fulltext', 'chunked'):
1373
                bytes = record.get_bytes_as('fulltext')
1374
            else:
3735.9.17 by John Arbash Meinel
Pass around a progress bar and switch to using an adapter.
1375
                bytes = adapter.get_bytes(record,
1376
                            record.get_bytes_as(record.storage_kind))
3735.16.2 by John Arbash Meinel
Start passing around the search_key_func in more places.
1377
            # We don't care about search_key_func for this code, because we
1378
            # only care about external references.
1379
            node = _deserialise(bytes, record.key, search_key_func=None)
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1380
            if isinstance(node, InternalNode):
3735.9.15 by John Arbash Meinel
Found a bug in iter_interesting_nodes and its test suite.
1381
                chks = set(node.refs())
1382
                chks.difference_update(all_uninteresting_chks)
1383
                # Is set() and .difference_update better than:
1384
                # chks = [chk for chk in node.refs()
1385
                #              if chk not in all_uninteresting_chks]
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1386
                next_chks.update(chks)
1387
                # These are now uninteresting everywhere else
3735.9.7 by John Arbash Meinel
Cleanup pass.
1388
                all_uninteresting_chks.update(chks)
3735.9.19 by John Arbash Meinel
Refactor iter_interesting a little bit.
1389
                interesting_items = []
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1390
            else:
3735.9.19 by John Arbash Meinel
Refactor iter_interesting a little bit.
1391
                interesting_items = [item for item in node._items.iteritems()
1392
                                     if item not in all_uninteresting_items]
3735.9.15 by John Arbash Meinel
Found a bug in iter_interesting_nodes and its test suite.
1393
                # TODO: Do we need to filter out items that we have already
1394
                #       seen on other pages? We don't really want to buffer the
1395
                #       whole thing, but it does mean that callers need to
1396
                #       understand they may get duplicate values.
3735.9.7 by John Arbash Meinel
Cleanup pass.
1397
                # all_uninteresting_items.update(interesting_items)
3735.9.19 by John Arbash Meinel
Refactor iter_interesting a little bit.
1398
            yield {record.key: record}, interesting_items
3735.9.1 by John Arbash Meinel
Start working on an iter_interesting_nodes, which can find nodes to transmit
1399
        chks_to_read = next_chks