/brz/remove-bazaar

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