~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/chk_map.py

  • Committer: Vincent Ladeuil
  • Date: 2010-01-25 15:55:48 UTC
  • mto: (4985.1.4 add-attr-cleanup)
  • mto: This revision was merged to the branch mainline in revision 4988.
  • Revision ID: v.ladeuil+lp@free.fr-20100125155548-0l352pujvt5bzl5e
Deploy addAttrCleanup on the whole test suite.

Several use case worth mentioning:

- setting a module or any other object attribute is the majority
by far. In some cases the setting itself is deferred but most of
the time we want to set at the same time we add the cleanup.

- there multiple occurrences of protecting hooks or ui factory
which are now useless (the test framework takes care of that now),

- there was some lambda uses that can now be avoided.

That first cleanup already simplifies things a lot.

Show diffs side-by-side

added added

removed removed

Lines of Context:
50
50
    lru_cache,
51
51
    osutils,
52
52
    registry,
 
53
    static_tuple,
53
54
    trace,
54
55
    )
 
56
from bzrlib.static_tuple import StaticTuple
55
57
 
56
58
# approx 4MB
57
59
# If each line is 50 bytes, and you have 255 internal pages, with 255-way fan
60
62
# We are caching bytes so len(value) is perfectly accurate
61
63
_page_cache = lru_cache.LRUSizeCache(_PAGE_CACHE_SIZE)
62
64
 
 
65
def clear_cache():
 
66
    _page_cache.clear()
 
67
 
63
68
# If a ChildNode falls below this many bytes, we check for a remap
64
69
_INTERESTING_NEW_SIZE = 50
65
70
# If a ChildNode shrinks by more than this amount, we check for a remap
80
85
class CHKMap(object):
81
86
    """A persistent map from string to string backed by a CHK store."""
82
87
 
 
88
    __slots__ = ('_store', '_root_node', '_search_key_func')
 
89
 
83
90
    def __init__(self, store, root_key, search_key_func=None):
84
91
        """Create a CHKMap object.
85
92
 
109
116
        """
110
117
        delete_count = 0
111
118
        # Check preconditions first.
112
 
        new_items = set([key for (old, key, value) in delta if key is not None
113
 
            and old is None])
 
119
        as_st = StaticTuple.from_sequence
 
120
        new_items = set([as_st(key) for (old, key, value) in delta
 
121
                         if key is not None and old is None])
114
122
        existing_new = list(self.iteritems(key_filter=new_items))
115
123
        if existing_new:
116
124
            raise errors.InconsistentDeltaDelta(delta,
130
138
 
131
139
    def _ensure_root(self):
132
140
        """Ensure that the root node is an object not a key."""
133
 
        if type(self._root_node) is tuple:
 
141
        if type(self._root_node) is StaticTuple:
134
142
            # Demand-load the root
135
143
            self._root_node = self._get_node(self._root_node)
136
144
 
144
152
        :param node: A tuple key or node object.
145
153
        :return: A node object.
146
154
        """
147
 
        if type(node) is tuple:
 
155
        if type(node) is StaticTuple:
148
156
            bytes = self._read_bytes(node)
149
157
            return _deserialise(bytes, node,
150
158
                search_key_func=self._search_key_func)
191
199
            for key, value in sorted(node._items.iteritems()):
192
200
                # Don't use prefix nor indent here to line up when used in
193
201
                # tests in conjunction with assertEqualDiff
194
 
                result.append('      %r %r' % (key, value))
 
202
                result.append('      %r %r' % (tuple(key), value))
195
203
        return result
196
204
 
197
205
    @classmethod
215
223
        root_key = klass._create_directly(store, initial_value,
216
224
            maximum_size=maximum_size, key_width=key_width,
217
225
            search_key_func=search_key_func)
 
226
        if type(root_key) is not StaticTuple:
 
227
            raise AssertionError('we got a %s instead of a StaticTuple'
 
228
                                 % (type(root_key),))
218
229
        return root_key
219
230
 
220
231
    @classmethod
235
246
        node = LeafNode(search_key_func=search_key_func)
236
247
        node.set_maximum_size(maximum_size)
237
248
        node._key_width = key_width
238
 
        node._items = dict(initial_value)
 
249
        as_st = StaticTuple.from_sequence
 
250
        node._items = dict([(as_st(key), val) for key, val
 
251
                                               in initial_value.iteritems()])
239
252
        node._raw_size = sum([node._key_value_len(key, value)
240
 
                              for key,value in initial_value.iteritems()])
 
253
                              for key,value in node._items.iteritems()])
241
254
        node._len = len(node._items)
242
255
        node._compute_search_prefix()
243
256
        node._compute_serialised_prefix()
479
492
    def iteritems(self, key_filter=None):
480
493
        """Iterate over the entire CHKMap's contents."""
481
494
        self._ensure_root()
 
495
        if key_filter is not None:
 
496
            as_st = StaticTuple.from_sequence
 
497
            key_filter = [as_st(key) for key in key_filter]
482
498
        return self._root_node.iteritems(self._store, key_filter=key_filter)
483
499
 
484
500
    def key(self):
485
501
        """Return the key for this map."""
486
 
        if type(self._root_node) is tuple:
 
502
        if type(self._root_node) is StaticTuple:
487
503
            return self._root_node
488
504
        else:
489
505
            return self._root_node._key
498
514
        :param key: A key to map.
499
515
        :param value: The value to assign to key.
500
516
        """
 
517
        key = StaticTuple.from_sequence(key)
501
518
        # Need a root object.
502
519
        self._ensure_root()
503
520
        prefix, node_details = self._root_node.map(self._store, key, value)
514
531
    def _node_key(self, node):
515
532
        """Get the key for a node whether it's a tuple or node."""
516
533
        if type(node) is tuple:
 
534
            node = StaticTuple.from_sequence(node)
 
535
        if type(node) is StaticTuple:
517
536
            return node
518
537
        else:
519
538
            return node._key
520
539
 
521
540
    def unmap(self, key, check_remap=True):
522
541
        """remove key from the map."""
 
542
        key = StaticTuple.from_sequence(key)
523
543
        self._ensure_root()
524
544
        if type(self._root_node) is InternalNode:
525
545
            unmapped = self._root_node.unmap(self._store, key,
539
559
 
540
560
        :return: The key of the root node.
541
561
        """
542
 
        if type(self._root_node) is tuple:
 
562
        if type(self._root_node) is StaticTuple:
543
563
            # Already saved.
544
564
            return self._root_node
545
565
        keys = list(self._root_node.serialise(self._store))
553
573
        adding the header bytes, and without prefix compression.
554
574
    """
555
575
 
 
576
    __slots__ = ('_key', '_len', '_maximum_size', '_key_width',
 
577
                 '_raw_size', '_items', '_search_prefix', '_search_key_func'
 
578
                )
 
579
 
556
580
    def __init__(self, key_width=1):
557
581
        """Create a node.
558
582
 
647
671
        the key/value pairs.
648
672
    """
649
673
 
 
674
    __slots__ = ('_common_serialised_prefix', '_serialise_key')
 
675
 
650
676
    def __init__(self, search_key_func=None):
651
677
        Node.__init__(self)
652
678
        # All of the keys in this leaf node share this common prefix
695
721
        :param bytes: The bytes of the node.
696
722
        :param key: The key that the serialised node has.
697
723
        """
 
724
        key = static_tuple.expect_static_tuple(key)
698
725
        return _deserialise_leaf_node(bytes, key,
699
726
                                      search_key_func=search_key_func)
700
727
 
870
897
            lines.append(serialized[prefix_len:])
871
898
            lines.extend(value_lines)
872
899
        sha1, _, _ = store.add_lines((None,), (), lines)
873
 
        self._key = ("sha1:" + sha1,)
 
900
        self._key = StaticTuple("sha1:" + sha1,).intern()
874
901
        bytes = ''.join(lines)
875
902
        if len(bytes) != self._current_size():
876
903
            raise AssertionError('Invalid _current_size')
944
971
        LeafNode or InternalNode.
945
972
    """
946
973
 
 
974
    __slots__ = ('_node_width',)
 
975
 
947
976
    def __init__(self, prefix='', search_key_func=None):
948
977
        Node.__init__(self)
949
978
        # The size of an internalnode with default values and no children.
991
1020
        :param key: The key that the serialised node has.
992
1021
        :return: An InternalNode instance.
993
1022
        """
 
1023
        key = static_tuple.expect_static_tuple(key)
994
1024
        return _deserialise_internal_node(bytes, key,
995
1025
                                          search_key_func=search_key_func)
996
1026
 
1021
1051
            # for whatever we are missing
1022
1052
            shortcut = True
1023
1053
            for prefix, node in self._items.iteritems():
1024
 
                if node.__class__ is tuple:
 
1054
                if node.__class__ is StaticTuple:
1025
1055
                    keys[node] = (prefix, None)
1026
1056
                else:
1027
1057
                    yield node, None
1056
1086
                    # A given key can only match 1 child node, if it isn't
1057
1087
                    # there, then we can just return nothing
1058
1088
                    return
1059
 
                if node.__class__ is tuple:
 
1089
                if node.__class__ is StaticTuple:
1060
1090
                    keys[node] = (search_prefix, [key])
1061
1091
                else:
1062
1092
                    # This is loaded, and the only thing that can match,
1089
1119
                        # We can ignore this one
1090
1120
                        continue
1091
1121
                    node_key_filter = prefix_to_keys[search_prefix]
1092
 
                    if node.__class__ is tuple:
 
1122
                    if node.__class__ is StaticTuple:
1093
1123
                        keys[node] = (search_prefix, node_key_filter)
1094
1124
                    else:
1095
1125
                        yield node, node_key_filter
1104
1134
                        if sub_prefix in length_filter:
1105
1135
                            node_key_filter.extend(prefix_to_keys[sub_prefix])
1106
1136
                    if node_key_filter: # this key matched something, yield it
1107
 
                        if node.__class__ is tuple:
 
1137
                        if node.__class__ is StaticTuple:
1108
1138
                            keys[node] = (prefix, node_key_filter)
1109
1139
                        else:
1110
1140
                            yield node, node_key_filter
1242
1272
        :return: An iterable of the keys inserted by this operation.
1243
1273
        """
1244
1274
        for node in self._items.itervalues():
1245
 
            if type(node) is tuple:
 
1275
            if type(node) is StaticTuple:
1246
1276
                # Never deserialised.
1247
1277
                continue
1248
1278
            if node._key is not None:
1259
1289
        lines.append('%s\n' % (self._search_prefix,))
1260
1290
        prefix_len = len(self._search_prefix)
1261
1291
        for prefix, node in sorted(self._items.items()):
1262
 
            if type(node) is tuple:
 
1292
            if type(node) is StaticTuple:
1263
1293
                key = node[0]
1264
1294
            else:
1265
1295
                key = node._key[0]
1269
1299
                    % (serialised, self._search_prefix))
1270
1300
            lines.append(serialised[prefix_len:])
1271
1301
        sha1, _, _ = store.add_lines((None,), (), lines)
1272
 
        self._key = ("sha1:" + sha1,)
 
1302
        self._key = StaticTuple("sha1:" + sha1,).intern()
1273
1303
        _page_cache.add(self._key, ''.join(lines))
1274
1304
        yield self._key
1275
1305
 
1304
1334
            raise AssertionError("unserialised nodes have no refs.")
1305
1335
        refs = []
1306
1336
        for value in self._items.itervalues():
1307
 
            if type(value) is tuple:
 
1337
            if type(value) is StaticTuple:
1308
1338
                refs.append(value)
1309
1339
            else:
1310
1340
                refs.append(value.key())
1424
1454
 
1425
1455
    def __init__(self, store, new_root_keys, old_root_keys,
1426
1456
                 search_key_func, pb=None):
 
1457
        # TODO: Should we add a StaticTuple barrier here? It would be nice to
 
1458
        #       force callers to use StaticTuple, because there will often be
 
1459
        #       lots of keys passed in here. And even if we cast it locally,
 
1460
        #       that just meanst that we will have *both* a StaticTuple and a
 
1461
        #       tuple() in memory, referring to the same object. (so a net
 
1462
        #       increase in memory, not a decrease.)
1427
1463
        self._store = store
1428
1464
        self._new_root_keys = new_root_keys
1429
1465
        self._old_root_keys = old_root_keys
1431
1467
        # All uninteresting chks that we have seen. By the time they are added
1432
1468
        # here, they should be either fully ignored, or queued up for
1433
1469
        # processing
 
1470
        # TODO: This might grow to a large size if there are lots of merge
 
1471
        #       parents, etc. However, it probably doesn't scale to O(history)
 
1472
        #       like _processed_new_refs does.
1434
1473
        self._all_old_chks = set(self._old_root_keys)
1435
1474
        # All items that we have seen from the old_root_keys
1436
1475
        self._all_old_items = set()
1437
1476
        # These are interesting items which were either read, or already in the
1438
1477
        # interesting queue (so we don't need to walk them again)
 
1478
        # TODO: processed_new_refs becomes O(all_chks), consider switching to
 
1479
        #       SimpleSet here.
1439
1480
        self._processed_new_refs = set()
1440
1481
        self._search_key_func = search_key_func
1441
1482
 
1453
1494
        # this code. (We may want to evaluate saving the raw bytes into the
1454
1495
        # page cache, which would allow a working tree update after the fetch
1455
1496
        # to not have to read the bytes again.)
 
1497
        as_st = StaticTuple.from_sequence
1456
1498
        stream = self._store.get_record_stream(keys, 'unordered', True)
1457
1499
        for record in stream:
1458
1500
            if self._pb is not None:
1465
1507
            if type(node) is InternalNode:
1466
1508
                # Note we don't have to do node.refs() because we know that
1467
1509
                # there are no children that have been pushed into this node
 
1510
                # Note: Using as_st() here seemed to save 1.2MB, which would
 
1511
                #       indicate that we keep 100k prefix_refs around while
 
1512
                #       processing. They *should* be shorter lived than that...
 
1513
                #       It does cost us ~10s of processing time
 
1514
                #prefix_refs = [as_st(item) for item in node._items.iteritems()]
1468
1515
                prefix_refs = node._items.items()
1469
1516
                items = []
1470
1517
            else:
1471
1518
                prefix_refs = []
 
1519
                # Note: We don't use a StaticTuple here. Profiling showed a
 
1520
                #       minor memory improvement (0.8MB out of 335MB peak 0.2%)
 
1521
                #       But a significant slowdown (15s / 145s, or 10%)
1472
1522
                items = node._items.items()
1473
1523
            yield record, node, prefix_refs, items
1474
1524
 
1482
1532
                                if p_r[1] not in all_old_chks]
1483
1533
            new_refs = [p_r[1] for p_r in prefix_refs]
1484
1534
            all_old_chks.update(new_refs)
 
1535
            # TODO: This might be a good time to turn items into StaticTuple
 
1536
            #       instances and possibly intern them. However, this does not
 
1537
            #       impact 'initial branch' performance, so I'm not worrying
 
1538
            #       about this yet
1485
1539
            self._all_old_items.update(items)
1486
1540
            # Queue up the uninteresting references
1487
1541
            # Don't actually put them in the 'to-read' queue until we have
1540
1594
            #       current design allows for this, as callers will do the work
1541
1595
            #       to make the results unique. We might profile whether we
1542
1596
            #       gain anything by ensuring unique return values for items
 
1597
            # TODO: This might be a good time to cast to StaticTuple, as
 
1598
            #       self._new_item_queue will hold the contents of multiple
 
1599
            #       records for an extended lifetime
1543
1600
            new_items = [item for item in items
1544
1601
                               if item not in self._all_old_items]
1545
1602
            self._new_item_queue.extend(new_items)
1570
1627
        if new_items:
1571
1628
            yield None, new_items
1572
1629
        refs = refs.difference(all_old_chks)
 
1630
        processed_new_refs.update(refs)
1573
1631
        while refs:
 
1632
            # TODO: Using a SimpleSet for self._processed_new_refs and
 
1633
            #       saved as much as 10MB of peak memory. However, it requires
 
1634
            #       implementing a non-pyrex version.
1574
1635
            next_refs = set()
1575
1636
            next_refs_update = next_refs.update
1576
1637
            # Inlining _read_nodes_from_store improves 'bzr branch bzr.dev'
1577
1638
            # from 1m54s to 1m51s. Consider it.
1578
1639
            for record, _, p_refs, items in self._read_nodes_from_store(refs):
1579
 
                items = [item for item in items
1580
 
                         if item not in all_old_items]
 
1640
                if all_old_items:
 
1641
                    # using the 'if' check saves about 145s => 141s, when
 
1642
                    # streaming initial branch of Launchpad data.
 
1643
                    items = [item for item in items
 
1644
                             if item not in all_old_items]
1581
1645
                yield record, items
1582
1646
                next_refs_update([p_r[1] for p_r in p_refs])
 
1647
                del p_refs
 
1648
            # set1.difference(set/dict) walks all of set1, and checks if it
 
1649
            # exists in 'other'.
 
1650
            # set1.difference(iterable) walks all of iterable, and does a
 
1651
            # 'difference_update' on a clone of set1. Pick wisely based on the
 
1652
            # expected sizes of objects.
 
1653
            # in our case it is expected that 'new_refs' will always be quite
 
1654
            # small.
1583
1655
            next_refs = next_refs.difference(all_old_chks)
1584
1656
            next_refs = next_refs.difference(processed_new_refs)
1585
1657
            processed_new_refs.update(next_refs)
1592
1664
        self._old_queue = []
1593
1665
        all_old_chks = self._all_old_chks
1594
1666
        for record, _, prefix_refs, items in self._read_nodes_from_store(refs):
 
1667
            # TODO: Use StaticTuple here?
1595
1668
            self._all_old_items.update(items)
1596
1669
            refs = [r for _,r in prefix_refs if r not in all_old_chks]
1597
1670
            self._old_queue.extend(refs)
1637
1710
        _deserialise_leaf_node,
1638
1711
        _deserialise_internal_node,
1639
1712
        )
1640
 
except ImportError:
 
1713
except ImportError, e:
 
1714
    osutils.failed_to_load_extension(e)
1641
1715
    from bzrlib._chk_map_py import (
1642
1716
        _search_key_16,
1643
1717
        _search_key_255,
1646
1720
        )
1647
1721
search_key_registry.register('hash-16-way', _search_key_16)
1648
1722
search_key_registry.register('hash-255-way', _search_key_255)
 
1723
 
 
1724
 
 
1725
def _check_key(key):
 
1726
    """Helper function to assert that a key is properly formatted.
 
1727
 
 
1728
    This generally shouldn't be used in production code, but it can be helpful
 
1729
    to debug problems.
 
1730
    """
 
1731
    if type(key) is not StaticTuple:
 
1732
        raise TypeError('key %r is not StaticTuple but %s' % (key, type(key)))
 
1733
    if len(key) != 1:
 
1734
        raise ValueError('key %r should have length 1, not %d' % (key, len(key),))
 
1735
    if type(key[0]) is not str:
 
1736
        raise TypeError('key %r should hold a str, not %r'
 
1737
                        % (key, type(key[0])))
 
1738
    if not key[0].startswith('sha1:'):
 
1739
        raise ValueError('key %r should point to a sha1:' % (key,))
 
1740
 
 
1741