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