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