~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/groupcompress.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-06-10 06:25:56 UTC
  • mfrom: (4360.5.4 bzr.1.15.1)
  • Revision ID: pqm@pqm.ubuntu.com-20090610062556-r5szm3gdybs8w5nq
(tanner) Merge release 1.15.1 back to trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008, 2009, 2010 Canonical Ltd
 
1
# Copyright (C) 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
16
16
 
17
17
"""Core compression logic for compressing streams of related files."""
18
18
 
 
19
from itertools import izip
 
20
from cStringIO import StringIO
19
21
import time
20
22
import zlib
21
23
try:
26
28
from bzrlib import (
27
29
    annotate,
28
30
    debug,
 
31
    diff,
29
32
    errors,
30
33
    graph as _mod_graph,
31
34
    knit,
32
35
    osutils,
33
36
    pack,
34
 
    static_tuple,
 
37
    patiencediff,
35
38
    trace,
36
39
    )
 
40
from bzrlib.graph import Graph
37
41
from bzrlib.btree_index import BTreeBuilder
38
42
from bzrlib.lru_cache import LRUSizeCache
39
43
from bzrlib.tsort import topo_sort
45
49
    VersionedFiles,
46
50
    )
47
51
 
48
 
# Minimum number of uncompressed bytes to try fetch at once when retrieving
49
 
# groupcompress blocks.
50
 
BATCH_SIZE = 2**16
51
 
 
52
52
_USE_LZMA = False and (pylzma is not None)
53
53
 
54
54
# osutils.sha_string('')
55
55
_null_sha1 = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
56
56
 
 
57
 
57
58
def sort_gc_optimal(parent_map):
58
59
    """Sort and group the keys in parent_map into groupcompress order.
59
60
 
65
66
    # groupcompress ordering is approximately reverse topological,
66
67
    # properly grouped by file-id.
67
68
    per_prefix_map = {}
68
 
    for key, value in parent_map.iteritems():
 
69
    for item in parent_map.iteritems():
 
70
        key = item[0]
69
71
        if isinstance(key, str) or len(key) == 1:
70
72
            prefix = ''
71
73
        else:
72
74
            prefix = key[0]
73
75
        try:
74
 
            per_prefix_map[prefix][key] = value
 
76
            per_prefix_map[prefix].append(item)
75
77
        except KeyError:
76
 
            per_prefix_map[prefix] = {key: value}
 
78
            per_prefix_map[prefix] = [item]
77
79
 
78
80
    present_keys = []
79
81
    for prefix in sorted(per_prefix_map):
106
108
        self._z_content_length = None
107
109
        self._content_length = None
108
110
        self._content = None
109
 
        self._content_chunks = None
110
111
 
111
112
    def __len__(self):
112
113
        # This is the maximum number of bytes this object will reference if
120
121
        :param num_bytes: Ensure that we have extracted at least num_bytes of
121
122
            content. If None, consume everything
122
123
        """
123
 
        if self._content_length is None:
124
 
            raise AssertionError('self._content_length should never be None')
 
124
        # TODO: If we re-use the same content block at different times during
 
125
        #       get_record_stream(), it is possible that the first pass will
 
126
        #       get inserted, triggering an extract/_ensure_content() which
 
127
        #       will get rid of _z_content. And then the next use of the block
 
128
        #       will try to access _z_content (to send it over the wire), and
 
129
        #       fail because it is already extracted. Consider never releasing
 
130
        #       _z_content because of this.
125
131
        if num_bytes is None:
126
132
            num_bytes = self._content_length
127
133
        elif (self._content_length is not None
131
137
                % (num_bytes, self._content_length))
132
138
        # Expand the content if required
133
139
        if self._content is None:
134
 
            if self._content_chunks is not None:
135
 
                self._content = ''.join(self._content_chunks)
136
 
                self._content_chunks = None
137
 
        if self._content is None:
138
140
            if self._z_content is None:
139
141
                raise AssertionError('No content to decompress')
140
142
            if self._z_content == '':
144
146
                self._content = pylzma.decompress(self._z_content)
145
147
            elif self._compressor_name == 'zlib':
146
148
                # Start a zlib decompressor
147
 
                if num_bytes * 4 > self._content_length * 3:
148
 
                    # If we are requesting more that 3/4ths of the content,
149
 
                    # just extract the whole thing in a single pass
150
 
                    num_bytes = self._content_length
 
149
                if num_bytes is None:
151
150
                    self._content = zlib.decompress(self._z_content)
152
151
                else:
153
152
                    self._z_content_decompressor = zlib.decompressobj()
155
154
                    # that the rest of the code is simplified
156
155
                    self._content = self._z_content_decompressor.decompress(
157
156
                        self._z_content, num_bytes + _ZLIB_DECOMP_WINDOW)
158
 
                    if not self._z_content_decompressor.unconsumed_tail:
159
 
                        self._z_content_decompressor = None
160
157
            else:
161
158
                raise AssertionError('Unknown compressor: %r'
162
159
                                     % self._compressor_name)
164
161
        # 'unconsumed_tail'
165
162
 
166
163
        # Do we have enough bytes already?
167
 
        if len(self._content) >= num_bytes:
 
164
        if num_bytes is not None and len(self._content) >= num_bytes:
 
165
            return
 
166
        if num_bytes is None and self._z_content_decompressor is None:
 
167
            # We must have already decompressed everything
168
168
            return
169
169
        # If we got this far, and don't have a decompressor, something is wrong
170
170
        if self._z_content_decompressor is None:
171
171
            raise AssertionError(
172
172
                'No decompressor to decompress %d bytes' % num_bytes)
173
173
        remaining_decomp = self._z_content_decompressor.unconsumed_tail
174
 
        if not remaining_decomp:
175
 
            raise AssertionError('Nothing left to decompress')
176
 
        needed_bytes = num_bytes - len(self._content)
177
 
        # We always set max_size to 32kB over the minimum needed, so that
178
 
        # zlib will give us as much as we really want.
179
 
        # TODO: If this isn't good enough, we could make a loop here,
180
 
        #       that keeps expanding the request until we get enough
181
 
        self._content += self._z_content_decompressor.decompress(
182
 
            remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
183
 
        if len(self._content) < num_bytes:
184
 
            raise AssertionError('%d bytes wanted, only %d available'
185
 
                                 % (num_bytes, len(self._content)))
186
 
        if not self._z_content_decompressor.unconsumed_tail:
187
 
            # The stream is finished
188
 
            self._z_content_decompressor = None
 
174
        if num_bytes is None:
 
175
            if remaining_decomp:
 
176
                # We don't know how much is left, but we'll decompress it all
 
177
                self._content += self._z_content_decompressor.decompress(
 
178
                    remaining_decomp)
 
179
                # Note: There's what I consider a bug in zlib.decompressobj
 
180
                #       If you pass back in the entire unconsumed_tail, only
 
181
                #       this time you don't pass a max-size, it doesn't
 
182
                #       change the unconsumed_tail back to None/''.
 
183
                #       However, we know we are done with the whole stream
 
184
                self._z_content_decompressor = None
 
185
            # XXX: Why is this the only place in this routine we set this?
 
186
            self._content_length = len(self._content)
 
187
        else:
 
188
            if not remaining_decomp:
 
189
                raise AssertionError('Nothing left to decompress')
 
190
            needed_bytes = num_bytes - len(self._content)
 
191
            # We always set max_size to 32kB over the minimum needed, so that
 
192
            # zlib will give us as much as we really want.
 
193
            # TODO: If this isn't good enough, we could make a loop here,
 
194
            #       that keeps expanding the request until we get enough
 
195
            self._content += self._z_content_decompressor.decompress(
 
196
                remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
 
197
            if len(self._content) < num_bytes:
 
198
                raise AssertionError('%d bytes wanted, only %d available'
 
199
                                     % (num_bytes, len(self._content)))
 
200
            if not self._z_content_decompressor.unconsumed_tail:
 
201
                # The stream is finished
 
202
                self._z_content_decompressor = None
189
203
 
190
204
    def _parse_bytes(self, bytes, pos):
191
205
        """Read the various lengths from the header.
259
273
            bytes = apply_delta_to_source(self._content, content_start, end)
260
274
        return bytes
261
275
 
262
 
    def set_chunked_content(self, content_chunks, length):
263
 
        """Set the content of this block to the given chunks."""
264
 
        # If we have lots of short lines, it is may be more efficient to join
265
 
        # the content ahead of time. If the content is <10MiB, we don't really
266
 
        # care about the extra memory consumption, so we can just pack it and
267
 
        # be done. However, timing showed 18s => 17.9s for repacking 1k revs of
268
 
        # mysql, which is below the noise margin
269
 
        self._content_length = length
270
 
        self._content_chunks = content_chunks
271
 
        self._content = None
272
 
        self._z_content = None
273
 
 
274
276
    def set_content(self, content):
275
277
        """Set the content of this block."""
276
278
        self._content_length = len(content)
277
279
        self._content = content
278
280
        self._z_content = None
279
281
 
280
 
    def _create_z_content_using_lzma(self):
281
 
        if self._content_chunks is not None:
282
 
            self._content = ''.join(self._content_chunks)
283
 
            self._content_chunks = None
284
 
        if self._content is None:
285
 
            raise AssertionError('Nothing to compress')
286
 
        self._z_content = pylzma.compress(self._content)
287
 
        self._z_content_length = len(self._z_content)
288
 
 
289
 
    def _create_z_content_from_chunks(self):
290
 
        compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION)
291
 
        compressed_chunks = map(compressor.compress, self._content_chunks)
292
 
        compressed_chunks.append(compressor.flush())
293
 
        self._z_content = ''.join(compressed_chunks)
294
 
        self._z_content_length = len(self._z_content)
295
 
 
296
 
    def _create_z_content(self):
297
 
        if self._z_content is not None:
298
 
            return
299
 
        if _USE_LZMA:
300
 
            self._create_z_content_using_lzma()
301
 
            return
302
 
        if self._content_chunks is not None:
303
 
            self._create_z_content_from_chunks()
304
 
            return
305
 
        self._z_content = zlib.compress(self._content)
306
 
        self._z_content_length = len(self._z_content)
307
 
 
308
282
    def to_bytes(self):
309
283
        """Encode the information into a byte stream."""
310
 
        self._create_z_content()
 
284
        compress = zlib.compress
 
285
        if _USE_LZMA:
 
286
            compress = pylzma.compress
 
287
        if self._z_content is None:
 
288
            if self._content is None:
 
289
                raise AssertionError('Nothing to compress')
 
290
            self._z_content = compress(self._content)
 
291
            self._z_content_length = len(self._z_content)
311
292
        if _USE_LZMA:
312
293
            header = self.GCB_LZ_HEADER
313
294
        else:
441
422
                # There are code paths that first extract as fulltext, and then
442
423
                # extract as storage_kind (smart fetch). So we don't break the
443
424
                # refcycle here, but instead in manager.get_record_stream()
 
425
                # self._manager = None
444
426
            if storage_kind == 'fulltext':
445
427
                return self._bytes
446
428
            else:
452
434
class _LazyGroupContentManager(object):
453
435
    """This manages a group of _LazyGroupCompressFactory objects."""
454
436
 
455
 
    _max_cut_fraction = 0.75 # We allow a block to be trimmed to 75% of
456
 
                             # current size, and still be considered
457
 
                             # resuable
458
 
    _full_block_size = 4*1024*1024
459
 
    _full_mixed_block_size = 2*1024*1024
460
 
    _full_enough_block_size = 3*1024*1024 # size at which we won't repack
461
 
    _full_enough_mixed_block_size = 2*768*1024 # 1.5MB
462
 
 
463
437
    def __init__(self, block):
464
438
        self._block = block
465
439
        # We need to preserve the ordering
537
511
        # time (self._block._content) is a little expensive.
538
512
        self._block._ensure_content(self._last_byte)
539
513
 
540
 
    def _check_rebuild_action(self):
 
514
    def _check_rebuild_block(self):
541
515
        """Check to see if our block should be repacked."""
542
516
        total_bytes_used = 0
543
517
        last_byte_used = 0
544
518
        for factory in self._factories:
545
519
            total_bytes_used += factory._end - factory._start
546
 
            if last_byte_used < factory._end:
547
 
                last_byte_used = factory._end
548
 
        # If we are using more than half of the bytes from the block, we have
549
 
        # nothing else to check
 
520
            last_byte_used = max(last_byte_used, factory._end)
 
521
        # If we are using most of the bytes from the block, we have nothing
 
522
        # else to check (currently more that 1/2)
550
523
        if total_bytes_used * 2 >= self._block._content_length:
551
 
            return None, last_byte_used, total_bytes_used
552
 
        # We are using less than 50% of the content. Is the content we are
553
 
        # using at the beginning of the block? If so, we can just trim the
554
 
        # tail, rather than rebuilding from scratch.
 
524
            return
 
525
        # Can we just strip off the trailing bytes? If we are going to be
 
526
        # transmitting more than 50% of the front of the content, go ahead
555
527
        if total_bytes_used * 2 > last_byte_used:
556
 
            return 'trim', last_byte_used, total_bytes_used
 
528
            self._trim_block(last_byte_used)
 
529
            return
557
530
 
558
531
        # We are using a small amount of the data, and it isn't just packed
559
532
        # nicely at the front, so rebuild the content.
566
539
        #       expanding many deltas into fulltexts, as well.
567
540
        #       If we build a cheap enough 'strip', then we could try a strip,
568
541
        #       if that expands the content, we then rebuild.
569
 
        return 'rebuild', last_byte_used, total_bytes_used
570
 
 
571
 
    def check_is_well_utilized(self):
572
 
        """Is the current block considered 'well utilized'?
573
 
 
574
 
        This heuristic asks if the current block considers itself to be a fully
575
 
        developed group, rather than just a loose collection of data.
576
 
        """
577
 
        if len(self._factories) == 1:
578
 
            # A block of length 1 could be improved by combining with other
579
 
            # groups - don't look deeper. Even larger than max size groups
580
 
            # could compress well with adjacent versions of the same thing.
581
 
            return False
582
 
        action, last_byte_used, total_bytes_used = self._check_rebuild_action()
583
 
        block_size = self._block._content_length
584
 
        if total_bytes_used < block_size * self._max_cut_fraction:
585
 
            # This block wants to trim itself small enough that we want to
586
 
            # consider it under-utilized.
587
 
            return False
588
 
        # TODO: This code is meant to be the twin of _insert_record_stream's
589
 
        #       'start_new_block' logic. It would probably be better to factor
590
 
        #       out that logic into a shared location, so that it stays
591
 
        #       together better
592
 
        # We currently assume a block is properly utilized whenever it is >75%
593
 
        # of the size of a 'full' block. In normal operation, a block is
594
 
        # considered full when it hits 4MB of same-file content. So any block
595
 
        # >3MB is 'full enough'.
596
 
        # The only time this isn't true is when a given block has large-object
597
 
        # content. (a single file >4MB, etc.)
598
 
        # Under these circumstances, we allow a block to grow to
599
 
        # 2 x largest_content.  Which means that if a given block had a large
600
 
        # object, it may actually be under-utilized. However, given that this
601
 
        # is 'pack-on-the-fly' it is probably reasonable to not repack large
602
 
        # content blobs on-the-fly. Note that because we return False for all
603
 
        # 1-item blobs, we will repack them; we may wish to reevaluate our
604
 
        # treatment of large object blobs in the future.
605
 
        if block_size >= self._full_enough_block_size:
606
 
            return True
607
 
        # If a block is <3MB, it still may be considered 'full' if it contains
608
 
        # mixed content. The current rule is 2MB of mixed content is considered
609
 
        # full. So check to see if this block contains mixed content, and
610
 
        # set the threshold appropriately.
611
 
        common_prefix = None
612
 
        for factory in self._factories:
613
 
            prefix = factory.key[:-1]
614
 
            if common_prefix is None:
615
 
                common_prefix = prefix
616
 
            elif prefix != common_prefix:
617
 
                # Mixed content, check the size appropriately
618
 
                if block_size >= self._full_enough_mixed_block_size:
619
 
                    return True
620
 
                break
621
 
        # The content failed both the mixed check and the single-content check
622
 
        # so obviously it is not fully utilized
623
 
        # TODO: there is one other constraint that isn't being checked
624
 
        #       namely, that the entries in the block are in the appropriate
625
 
        #       order. For example, you could insert the entries in exactly
626
 
        #       reverse groupcompress order, and we would think that is ok.
627
 
        #       (all the right objects are in one group, and it is fully
628
 
        #       utilized, etc.) For now, we assume that case is rare,
629
 
        #       especially since we should always fetch in 'groupcompress'
630
 
        #       order.
631
 
        return False
632
 
 
633
 
    def _check_rebuild_block(self):
634
 
        action, last_byte_used, total_bytes_used = self._check_rebuild_action()
635
 
        if action is None:
636
 
            return
637
 
        if action == 'trim':
638
 
            self._trim_block(last_byte_used)
639
 
        elif action == 'rebuild':
640
 
            self._rebuild_block()
641
 
        else:
642
 
            raise ValueError('unknown rebuild action: %r' % (action,))
 
542
        self._rebuild_block()
643
543
 
644
544
    def _wire_bytes(self):
645
545
        """Return a byte stream suitable for transmitting over the wire."""
862
762
        #       for 'commit' down to ~1x the size of the largest file, at a
863
763
        #       cost of increased complexity within this code. 2x is still <<
864
764
        #       3x the size of the largest file, so we are doing ok.
865
 
        self._block.set_chunked_content(self.chunks, self.endpoint)
 
765
        content = ''.join(self.chunks)
866
766
        self.chunks = None
867
767
        self._delta_index = None
 
768
        self._block.set_content(content)
868
769
        return self._block
869
770
 
870
771
    def pop_last(self):
1004
905
        self.endpoint = endpoint
1005
906
 
1006
907
 
1007
 
def make_pack_factory(graph, delta, keylength, inconsistency_fatal=True):
 
908
def make_pack_factory(graph, delta, keylength):
1008
909
    """Create a factory for creating a pack based groupcompress.
1009
910
 
1010
911
    This is only functional enough to run interface tests, it doesn't try to
1025
926
        writer = pack.ContainerWriter(stream.write)
1026
927
        writer.begin()
1027
928
        index = _GCGraphIndex(graph_index, lambda:True, parents=parents,
1028
 
            add_callback=graph_index.add_nodes,
1029
 
            inconsistency_fatal=inconsistency_fatal)
 
929
            add_callback=graph_index.add_nodes)
1030
930
        access = knit._DirectPackAccess({})
1031
931
        access.set_writer(writer, graph_index, (transport, 'newpack'))
1032
932
        result = GroupCompressVersionedFiles(index, access, delta)
1041
941
    versioned_files.stream.close()
1042
942
 
1043
943
 
1044
 
class _BatchingBlockFetcher(object):
1045
 
    """Fetch group compress blocks in batches.
1046
 
    
1047
 
    :ivar total_bytes: int of expected number of bytes needed to fetch the
1048
 
        currently pending batch.
1049
 
    """
1050
 
 
1051
 
    def __init__(self, gcvf, locations):
1052
 
        self.gcvf = gcvf
1053
 
        self.locations = locations
1054
 
        self.keys = []
1055
 
        self.batch_memos = {}
1056
 
        self.memos_to_get = []
1057
 
        self.total_bytes = 0
1058
 
        self.last_read_memo = None
1059
 
        self.manager = None
1060
 
 
1061
 
    def add_key(self, key):
1062
 
        """Add another to key to fetch.
1063
 
        
1064
 
        :return: The estimated number of bytes needed to fetch the batch so
1065
 
            far.
1066
 
        """
1067
 
        self.keys.append(key)
1068
 
        index_memo, _, _, _ = self.locations[key]
1069
 
        read_memo = index_memo[0:3]
1070
 
        # Three possibilities for this read_memo:
1071
 
        #  - it's already part of this batch; or
1072
 
        #  - it's not yet part of this batch, but is already cached; or
1073
 
        #  - it's not yet part of this batch and will need to be fetched.
1074
 
        if read_memo in self.batch_memos:
1075
 
            # This read memo is already in this batch.
1076
 
            return self.total_bytes
1077
 
        try:
1078
 
            cached_block = self.gcvf._group_cache[read_memo]
1079
 
        except KeyError:
1080
 
            # This read memo is new to this batch, and the data isn't cached
1081
 
            # either.
1082
 
            self.batch_memos[read_memo] = None
1083
 
            self.memos_to_get.append(read_memo)
1084
 
            byte_length = read_memo[2]
1085
 
            self.total_bytes += byte_length
1086
 
        else:
1087
 
            # This read memo is new to this batch, but cached.
1088
 
            # Keep a reference to the cached block in batch_memos because it's
1089
 
            # certain that we'll use it when this batch is processed, but
1090
 
            # there's a risk that it would fall out of _group_cache between now
1091
 
            # and then.
1092
 
            self.batch_memos[read_memo] = cached_block
1093
 
        return self.total_bytes
1094
 
        
1095
 
    def _flush_manager(self):
1096
 
        if self.manager is not None:
1097
 
            for factory in self.manager.get_record_stream():
1098
 
                yield factory
1099
 
            self.manager = None
1100
 
            self.last_read_memo = None
1101
 
 
1102
 
    def yield_factories(self, full_flush=False):
1103
 
        """Yield factories for keys added since the last yield.  They will be
1104
 
        returned in the order they were added via add_key.
1105
 
        
1106
 
        :param full_flush: by default, some results may not be returned in case
1107
 
            they can be part of the next batch.  If full_flush is True, then
1108
 
            all results are returned.
1109
 
        """
1110
 
        if self.manager is None and not self.keys:
1111
 
            return
1112
 
        # Fetch all memos in this batch.
1113
 
        blocks = self.gcvf._get_blocks(self.memos_to_get)
1114
 
        # Turn blocks into factories and yield them.
1115
 
        memos_to_get_stack = list(self.memos_to_get)
1116
 
        memos_to_get_stack.reverse()
1117
 
        for key in self.keys:
1118
 
            index_memo, _, parents, _ = self.locations[key]
1119
 
            read_memo = index_memo[:3]
1120
 
            if self.last_read_memo != read_memo:
1121
 
                # We are starting a new block. If we have a
1122
 
                # manager, we have found everything that fits for
1123
 
                # now, so yield records
1124
 
                for factory in self._flush_manager():
1125
 
                    yield factory
1126
 
                # Now start a new manager.
1127
 
                if memos_to_get_stack and memos_to_get_stack[-1] == read_memo:
1128
 
                    # The next block from _get_blocks will be the block we
1129
 
                    # need.
1130
 
                    block_read_memo, block = blocks.next()
1131
 
                    if block_read_memo != read_memo:
1132
 
                        raise AssertionError(
1133
 
                            "block_read_memo out of sync with read_memo"
1134
 
                            "(%r != %r)" % (block_read_memo, read_memo))
1135
 
                    self.batch_memos[read_memo] = block
1136
 
                    memos_to_get_stack.pop()
1137
 
                else:
1138
 
                    block = self.batch_memos[read_memo]
1139
 
                self.manager = _LazyGroupContentManager(block)
1140
 
                self.last_read_memo = read_memo
1141
 
            start, end = index_memo[3:5]
1142
 
            self.manager.add_factory(key, parents, start, end)
1143
 
        if full_flush:
1144
 
            for factory in self._flush_manager():
1145
 
                yield factory
1146
 
        del self.keys[:]
1147
 
        self.batch_memos.clear()
1148
 
        del self.memos_to_get[:]
1149
 
        self.total_bytes = 0
1150
 
 
1151
 
 
1152
944
class GroupCompressVersionedFiles(VersionedFiles):
1153
945
    """A group-compress based VersionedFiles implementation."""
1154
946
 
1155
 
    def __init__(self, index, access, delta=True, _unadded_refs=None):
 
947
    def __init__(self, index, access, delta=True):
1156
948
        """Create a GroupCompressVersionedFiles object.
1157
949
 
1158
950
        :param index: The index object storing access and graph data.
1159
951
        :param access: The access object storing raw data.
1160
952
        :param delta: Whether to delta compress or just entropy compress.
1161
 
        :param _unadded_refs: private parameter, don't use.
1162
953
        """
1163
954
        self._index = index
1164
955
        self._access = access
1165
956
        self._delta = delta
1166
 
        if _unadded_refs is None:
1167
 
            _unadded_refs = {}
1168
 
        self._unadded_refs = _unadded_refs
 
957
        self._unadded_refs = {}
1169
958
        self._group_cache = LRUSizeCache(max_size=50*1024*1024)
1170
959
        self._fallback_vfs = []
1171
960
 
1172
 
    def without_fallbacks(self):
1173
 
        """Return a clone of this object without any fallbacks configured."""
1174
 
        return GroupCompressVersionedFiles(self._index, self._access,
1175
 
            self._delta, _unadded_refs=dict(self._unadded_refs))
1176
 
 
1177
961
    def add_lines(self, key, parents, lines, parent_texts=None,
1178
962
        left_matching_blocks=None, nostore_sha=None, random_id=False,
1179
963
        check_content=True):
1224
1008
                                               nostore_sha=nostore_sha))[0]
1225
1009
        return sha1, length, None
1226
1010
 
1227
 
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
1228
 
        """See VersionedFiles._add_text()."""
1229
 
        self._index._check_write_ok()
1230
 
        self._check_add(key, None, random_id, check_content=False)
1231
 
        if text.__class__ is not str:
1232
 
            raise errors.BzrBadParameterUnicode("text")
1233
 
        if parents is None:
1234
 
            # The caller might pass None if there is no graph data, but kndx
1235
 
            # indexes can't directly store that, so we give them
1236
 
            # an empty tuple instead.
1237
 
            parents = ()
1238
 
        # double handling for now. Make it work until then.
1239
 
        length = len(text)
1240
 
        record = FulltextContentFactory(key, parents, None, text)
1241
 
        sha1 = list(self._insert_record_stream([record], random_id=random_id,
1242
 
                                               nostore_sha=nostore_sha))[0]
1243
 
        return sha1, length, None
1244
 
 
1245
1011
    def add_fallback_versioned_files(self, a_versioned_files):
1246
1012
        """Add a source of texts for texts not present in this knit.
1247
1013
 
1251
1017
 
1252
1018
    def annotate(self, key):
1253
1019
        """See VersionedFiles.annotate."""
1254
 
        ann = annotate.Annotator(self)
1255
 
        return ann.annotate_flat(key)
1256
 
 
1257
 
    def get_annotator(self):
1258
 
        return annotate.Annotator(self)
1259
 
 
1260
 
    def check(self, progress_bar=None, keys=None):
 
1020
        graph = Graph(self)
 
1021
        parent_map = self.get_parent_map([key])
 
1022
        if not parent_map:
 
1023
            raise errors.RevisionNotPresent(key, self)
 
1024
        if parent_map[key] is not None:
 
1025
            search = graph._make_breadth_first_searcher([key])
 
1026
            keys = set()
 
1027
            while True:
 
1028
                try:
 
1029
                    present, ghosts = search.next_with_ghosts()
 
1030
                except StopIteration:
 
1031
                    break
 
1032
                keys.update(present)
 
1033
            parent_map = self.get_parent_map(keys)
 
1034
        else:
 
1035
            keys = [key]
 
1036
            parent_map = {key:()}
 
1037
        # So we used Graph(self) to load the parent_map, but now that we have
 
1038
        # it, we can just query the parent map directly, so create a new Graph
 
1039
        # object
 
1040
        graph = _mod_graph.Graph(_mod_graph.DictParentsProvider(parent_map))
 
1041
        head_cache = _mod_graph.FrozenHeadsCache(graph)
 
1042
        parent_cache = {}
 
1043
        reannotate = annotate.reannotate
 
1044
        for record in self.get_record_stream(keys, 'topological', True):
 
1045
            key = record.key
 
1046
            lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
 
1047
            parent_lines = [parent_cache[parent] for parent in parent_map[key]]
 
1048
            parent_cache[key] = list(
 
1049
                reannotate(parent_lines, lines, key, None, head_cache))
 
1050
        return parent_cache[key]
 
1051
 
 
1052
    def check(self, progress_bar=None):
1261
1053
        """See VersionedFiles.check()."""
1262
 
        if keys is None:
1263
 
            keys = self.keys()
1264
 
            for record in self.get_record_stream(keys, 'unordered', True):
1265
 
                record.get_bytes_as('fulltext')
1266
 
        else:
1267
 
            return self.get_record_stream(keys, 'unordered', True)
1268
 
 
1269
 
    def clear_cache(self):
1270
 
        """See VersionedFiles.clear_cache()"""
1271
 
        self._group_cache.clear()
1272
 
        self._index._graph_index.clear_cache()
1273
 
        self._index._int_cache.clear()
 
1054
        keys = self.keys()
 
1055
        for record in self.get_record_stream(keys, 'unordered', True):
 
1056
            record.get_bytes_as('fulltext')
1274
1057
 
1275
1058
    def _check_add(self, key, lines, random_id, check_content):
1276
1059
        """check that version_id and lines are safe to add."""
1287
1070
            self._check_lines_not_unicode(lines)
1288
1071
            self._check_lines_are_lines(lines)
1289
1072
 
1290
 
    def get_known_graph_ancestry(self, keys):
1291
 
        """Get a KnownGraph instance with the ancestry of keys."""
1292
 
        # Note that this is identical to
1293
 
        # KnitVersionedFiles.get_known_graph_ancestry, but they don't share
1294
 
        # ancestry.
1295
 
        parent_map, missing_keys = self._index.find_ancestry(keys)
1296
 
        for fallback in self._fallback_vfs:
1297
 
            if not missing_keys:
1298
 
                break
1299
 
            (f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
1300
 
                                                missing_keys)
1301
 
            parent_map.update(f_parent_map)
1302
 
            missing_keys = f_missing_keys
1303
 
        kg = _mod_graph.KnownGraph(parent_map)
1304
 
        return kg
1305
 
 
1306
1073
    def get_parent_map(self, keys):
1307
1074
        """Get a map of the graph parents of keys.
1308
1075
 
1335
1102
            missing.difference_update(set(new_result))
1336
1103
        return result, source_results
1337
1104
 
1338
 
    def _get_blocks(self, read_memos):
1339
 
        """Get GroupCompressBlocks for the given read_memos.
1340
 
 
1341
 
        :returns: a series of (read_memo, block) pairs, in the order they were
1342
 
            originally passed.
1343
 
        """
1344
 
        cached = {}
1345
 
        for read_memo in read_memos:
1346
 
            try:
1347
 
                block = self._group_cache[read_memo]
1348
 
            except KeyError:
1349
 
                pass
1350
 
            else:
1351
 
                cached[read_memo] = block
1352
 
        not_cached = []
1353
 
        not_cached_seen = set()
1354
 
        for read_memo in read_memos:
1355
 
            if read_memo in cached:
1356
 
                # Don't fetch what we already have
1357
 
                continue
1358
 
            if read_memo in not_cached_seen:
1359
 
                # Don't try to fetch the same data twice
1360
 
                continue
1361
 
            not_cached.append(read_memo)
1362
 
            not_cached_seen.add(read_memo)
1363
 
        raw_records = self._access.get_raw_records(not_cached)
1364
 
        for read_memo in read_memos:
1365
 
            try:
1366
 
                yield read_memo, cached[read_memo]
1367
 
            except KeyError:
1368
 
                # Read the block, and cache it.
1369
 
                zdata = raw_records.next()
1370
 
                block = GroupCompressBlock.from_bytes(zdata)
1371
 
                self._group_cache[read_memo] = block
1372
 
                cached[read_memo] = block
1373
 
                yield read_memo, block
 
1105
    def _get_block(self, index_memo):
 
1106
        read_memo = index_memo[0:3]
 
1107
        # get the group:
 
1108
        try:
 
1109
            block = self._group_cache[read_memo]
 
1110
        except KeyError:
 
1111
            # read the group
 
1112
            zdata = self._access.get_raw_records([read_memo]).next()
 
1113
            # decompress - whole thing - this is not a bug, as it
 
1114
            # permits caching. We might want to store the partially
 
1115
            # decompresed group and decompress object, so that recent
 
1116
            # texts are not penalised by big groups.
 
1117
            block = GroupCompressBlock.from_bytes(zdata)
 
1118
            self._group_cache[read_memo] = block
 
1119
        # cheapo debugging:
 
1120
        # print len(zdata), len(plain)
 
1121
        # parse - requires split_lines, better to have byte offsets
 
1122
        # here (but not by much - we only split the region for the
 
1123
        # recipe, and we often want to end up with lines anyway.
 
1124
        return block
1374
1125
 
1375
1126
    def get_missing_compression_parent_keys(self):
1376
1127
        """Return the keys of missing compression parents.
1542
1293
                unadded_keys, source_result)
1543
1294
        for key in missing:
1544
1295
            yield AbsentContentFactory(key)
1545
 
        # Batch up as many keys as we can until either:
1546
 
        #  - we encounter an unadded ref, or
1547
 
        #  - we run out of keys, or
1548
 
        #  - the total bytes to retrieve for this batch > BATCH_SIZE
1549
 
        batcher = _BatchingBlockFetcher(self, locations)
 
1296
        manager = None
 
1297
        last_read_memo = None
 
1298
        # TODO: This works fairly well at batching up existing groups into a
 
1299
        #       streamable format, and possibly allowing for taking one big
 
1300
        #       group and splitting it when it isn't fully utilized.
 
1301
        #       However, it doesn't allow us to find under-utilized groups and
 
1302
        #       combine them into a bigger group on the fly.
 
1303
        #       (Consider the issue with how chk_map inserts texts
 
1304
        #       one-at-a-time.) This could be done at insert_record_stream()
 
1305
        #       time, but it probably would decrease the number of
 
1306
        #       bytes-on-the-wire for fetch.
1550
1307
        for source, keys in source_keys:
1551
1308
            if source is self:
1552
1309
                for key in keys:
1553
1310
                    if key in self._unadded_refs:
1554
 
                        # Flush batch, then yield unadded ref from
1555
 
                        # self._compressor.
1556
 
                        for factory in batcher.yield_factories(full_flush=True):
1557
 
                            yield factory
 
1311
                        if manager is not None:
 
1312
                            for factory in manager.get_record_stream():
 
1313
                                yield factory
 
1314
                            last_read_memo = manager = None
1558
1315
                        bytes, sha1 = self._compressor.extract(key)
1559
1316
                        parents = self._unadded_refs[key]
1560
1317
                        yield FulltextContentFactory(key, parents, sha1, bytes)
1561
 
                        continue
1562
 
                    if batcher.add_key(key) > BATCH_SIZE:
1563
 
                        # Ok, this batch is big enough.  Yield some results.
1564
 
                        for factory in batcher.yield_factories():
1565
 
                            yield factory
 
1318
                    else:
 
1319
                        index_memo, _, parents, (method, _) = locations[key]
 
1320
                        read_memo = index_memo[0:3]
 
1321
                        if last_read_memo != read_memo:
 
1322
                            # We are starting a new block. If we have a
 
1323
                            # manager, we have found everything that fits for
 
1324
                            # now, so yield records
 
1325
                            if manager is not None:
 
1326
                                for factory in manager.get_record_stream():
 
1327
                                    yield factory
 
1328
                            # Now start a new manager
 
1329
                            block = self._get_block(index_memo)
 
1330
                            manager = _LazyGroupContentManager(block)
 
1331
                            last_read_memo = read_memo
 
1332
                        start, end = index_memo[3:5]
 
1333
                        manager.add_factory(key, parents, start, end)
1566
1334
            else:
1567
 
                for factory in batcher.yield_factories(full_flush=True):
1568
 
                    yield factory
 
1335
                if manager is not None:
 
1336
                    for factory in manager.get_record_stream():
 
1337
                        yield factory
 
1338
                    last_read_memo = manager = None
1569
1339
                for record in source.get_record_stream(keys, ordering,
1570
1340
                                                       include_delta_closure):
1571
1341
                    yield record
1572
 
        for factory in batcher.yield_factories(full_flush=True):
1573
 
            yield factory
 
1342
        if manager is not None:
 
1343
            for factory in manager.get_record_stream():
 
1344
                yield factory
1574
1345
 
1575
1346
    def get_sha1s(self, keys):
1576
1347
        """See VersionedFiles.get_sha1s()."""
1631
1402
        keys_to_add = []
1632
1403
        def flush():
1633
1404
            bytes = self._compressor.flush().to_bytes()
1634
 
            self._compressor = GroupCompressor()
1635
1405
            index, start, length = self._access.add_raw_records(
1636
1406
                [(None, len(bytes))], bytes)[0]
1637
1407
            nodes = []
1640
1410
            self._index.add_records(nodes, random_id=random_id)
1641
1411
            self._unadded_refs = {}
1642
1412
            del keys_to_add[:]
 
1413
            self._compressor = GroupCompressor()
1643
1414
 
1644
1415
        last_prefix = None
1645
1416
        max_fulltext_len = 0
1649
1420
        block_length = None
1650
1421
        # XXX: TODO: remove this, it is just for safety checking for now
1651
1422
        inserted_keys = set()
1652
 
        reuse_this_block = reuse_blocks
1653
1423
        for record in stream:
1654
1424
            # Raise an error when a record is missing.
1655
1425
            if record.storage_kind == 'absent':
1663
1433
            if reuse_blocks:
1664
1434
                # If the reuse_blocks flag is set, check to see if we can just
1665
1435
                # copy a groupcompress block as-is.
1666
 
                # We only check on the first record (groupcompress-block) not
1667
 
                # on all of the (groupcompress-block-ref) entries.
1668
 
                # The reuse_this_block flag is then kept for as long as
1669
 
                if record.storage_kind == 'groupcompress-block':
1670
 
                    # Check to see if we really want to re-use this block
1671
 
                    insert_manager = record._manager
1672
 
                    reuse_this_block = insert_manager.check_is_well_utilized()
1673
 
            else:
1674
 
                reuse_this_block = False
1675
 
            if reuse_this_block:
1676
 
                # We still want to reuse this block
1677
1436
                if record.storage_kind == 'groupcompress-block':
1678
1437
                    # Insert the raw block into the target repo
1679
1438
                    insert_manager = record._manager
 
1439
                    insert_manager._check_rebuild_block()
1680
1440
                    bytes = record._manager._block.to_bytes()
1681
1441
                    _, start, length = self._access.add_raw_records(
1682
1442
                        [(None, len(bytes))], bytes)[0]
1687
1447
                                           'groupcompress-block-ref'):
1688
1448
                    if insert_manager is None:
1689
1449
                        raise AssertionError('No insert_manager set')
1690
 
                    if insert_manager is not record._manager:
1691
 
                        raise AssertionError('insert_manager does not match'
1692
 
                            ' the current record, we cannot be positive'
1693
 
                            ' that the appropriate content was inserted.'
1694
 
                            )
1695
1450
                    value = "%d %d %d %d" % (block_start, block_length,
1696
1451
                                             record._start, record._end)
1697
1452
                    nodes = [(record.key, value, (record.parents,))]
1747
1502
                key = record.key
1748
1503
            self._unadded_refs[key] = record.parents
1749
1504
            yield found_sha1
1750
 
            as_st = static_tuple.StaticTuple.from_sequence
1751
 
            if record.parents is not None:
1752
 
                parents = as_st([as_st(p) for p in record.parents])
1753
 
            else:
1754
 
                parents = None
1755
 
            refs = static_tuple.StaticTuple(parents)
1756
 
            keys_to_add.append((key, '%d %d' % (start_point, end_point), refs))
 
1505
            keys_to_add.append((key, '%d %d' % (start_point, end_point),
 
1506
                (record.parents,)))
1757
1507
        if len(keys_to_add):
1758
1508
            flush()
1759
1509
        self._compressor = None
1779
1529
 
1780
1530
        :return: An iterator over (line, key).
1781
1531
        """
 
1532
        if pb is None:
 
1533
            pb = progress.DummyProgress()
1782
1534
        keys = set(keys)
1783
1535
        total = len(keys)
1784
1536
        # we don't care about inclusions, the caller cares.
1788
1540
            'unordered', True)):
1789
1541
            # XXX: todo - optimise to use less than full texts.
1790
1542
            key = record.key
1791
 
            if pb is not None:
1792
 
                pb.update('Walking content', key_idx, total)
 
1543
            pb.update('Walking content', key_idx, total)
1793
1544
            if record.storage_kind == 'absent':
1794
1545
                raise errors.RevisionNotPresent(key, self)
1795
1546
            lines = osutils.split_lines(record.get_bytes_as('fulltext'))
1796
1547
            for line in lines:
1797
1548
                yield line, key
1798
 
        if pb is not None:
1799
 
            pb.update('Walking content', total, total)
 
1549
        pb.update('Walking content', total, total)
1800
1550
 
1801
1551
    def keys(self):
1802
1552
        """See VersionedFiles.keys."""
1813
1563
    """Mapper from GroupCompressVersionedFiles needs into GraphIndex storage."""
1814
1564
 
1815
1565
    def __init__(self, graph_index, is_locked, parents=True,
1816
 
        add_callback=None, track_external_parent_refs=False,
1817
 
        inconsistency_fatal=True, track_new_keys=False):
 
1566
        add_callback=None, track_external_parent_refs=False):
1818
1567
        """Construct a _GCGraphIndex on a graph_index.
1819
1568
 
1820
1569
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
1828
1577
        :param track_external_parent_refs: As keys are added, keep track of the
1829
1578
            keys they reference, so that we can query get_missing_parents(),
1830
1579
            etc.
1831
 
        :param inconsistency_fatal: When asked to add records that are already
1832
 
            present, and the details are inconsistent with the existing
1833
 
            record, raise an exception instead of warning (and skipping the
1834
 
            record).
1835
1580
        """
1836
1581
        self._add_callback = add_callback
1837
1582
        self._graph_index = graph_index
1838
1583
        self._parents = parents
1839
1584
        self.has_graph = parents
1840
1585
        self._is_locked = is_locked
1841
 
        self._inconsistency_fatal = inconsistency_fatal
1842
 
        # GroupCompress records tend to have the same 'group' start + offset
1843
 
        # repeated over and over, this creates a surplus of ints
1844
 
        self._int_cache = {}
1845
1586
        if track_external_parent_refs:
1846
 
            self._key_dependencies = knit._KeyRefs(
1847
 
                track_new_keys=track_new_keys)
 
1587
            self._key_dependencies = knit._KeyRefs()
1848
1588
        else:
1849
1589
            self._key_dependencies = None
1850
1590
 
1873
1613
                if refs:
1874
1614
                    for ref in refs:
1875
1615
                        if ref:
1876
 
                            raise errors.KnitCorrupt(self,
 
1616
                            raise KnitCorrupt(self,
1877
1617
                                "attempt to add node with parents "
1878
1618
                                "in parentless index.")
1879
1619
                    refs = ()
1883
1623
        if not random_id:
1884
1624
            present_nodes = self._get_entries(keys)
1885
1625
            for (index, key, value, node_refs) in present_nodes:
1886
 
                # Sometimes these are passed as a list rather than a tuple
1887
 
                node_refs = static_tuple.as_tuples(node_refs)
1888
 
                passed = static_tuple.as_tuples(keys[key])
1889
 
                if node_refs != passed[1]:
1890
 
                    details = '%s %s %s' % (key, (value, node_refs), passed)
1891
 
                    if self._inconsistency_fatal:
1892
 
                        raise errors.KnitCorrupt(self, "inconsistent details"
1893
 
                                                 " in add_records: %s" %
1894
 
                                                 details)
1895
 
                    else:
1896
 
                        trace.warning("inconsistent details in skipped"
1897
 
                                      " record: %s", details)
 
1626
                if node_refs != keys[key][1]:
 
1627
                    raise errors.KnitCorrupt(self, "inconsistent details in add_records"
 
1628
                        ": %s %s" % ((value, node_refs), keys[key]))
1898
1629
                del keys[key]
1899
1630
                changed = True
1900
1631
        if changed:
1907
1638
                    result.append((key, value))
1908
1639
            records = result
1909
1640
        key_dependencies = self._key_dependencies
1910
 
        if key_dependencies is not None:
1911
 
            if self._parents:
1912
 
                for key, value, refs in records:
1913
 
                    parents = refs[0]
1914
 
                    key_dependencies.add_references(key, parents)
1915
 
            else:
1916
 
                for key, value, refs in records:
1917
 
                    new_keys.add_key(key)
 
1641
        if key_dependencies is not None and self._parents:
 
1642
            for key, value, refs in records:
 
1643
                parents = refs[0]
 
1644
                key_dependencies.add_references(key, parents)
1918
1645
        self._add_callback(records)
1919
1646
 
1920
1647
    def _check_read(self):
1949
1676
        if check_present:
1950
1677
            missing_keys = keys.difference(found_keys)
1951
1678
            if missing_keys:
1952
 
                raise errors.RevisionNotPresent(missing_keys.pop(), self)
1953
 
 
1954
 
    def find_ancestry(self, keys):
1955
 
        """See CombinedGraphIndex.find_ancestry"""
1956
 
        return self._graph_index.find_ancestry(keys, 0)
 
1679
                raise RevisionNotPresent(missing_keys.pop(), self)
1957
1680
 
1958
1681
    def get_parent_map(self, keys):
1959
1682
        """Get a map of the parents of keys.
1977
1700
        """Return the keys of missing parents."""
1978
1701
        # Copied from _KnitGraphIndex.get_missing_parents
1979
1702
        # We may have false positives, so filter those out.
1980
 
        self._key_dependencies.satisfy_refs_for_keys(
 
1703
        self._key_dependencies.add_keys(
1981
1704
            self.get_parent_map(self._key_dependencies.get_unsatisfied_refs()))
1982
1705
        return frozenset(self._key_dependencies.get_unsatisfied_refs())
1983
1706
 
2026
1749
        """Convert an index value to position details."""
2027
1750
        bits = node[2].split(' ')
2028
1751
        # It would be nice not to read the entire gzip.
2029
 
        # start and stop are put into _int_cache because they are very common.
2030
 
        # They define the 'group' that an entry is in, and many groups can have
2031
 
        # thousands of objects.
2032
 
        # Branching Launchpad, for example, saves ~600k integers, at 12 bytes
2033
 
        # each, or about 7MB. Note that it might be even more when you consider
2034
 
        # how PyInt is allocated in separate slabs. And you can't return a slab
2035
 
        # to the OS if even 1 int on it is in use. Note though that Python uses
2036
 
        # a LIFO when re-using PyInt slots, which probably causes more
2037
 
        # fragmentation.
2038
1752
        start = int(bits[0])
2039
 
        start = self._int_cache.setdefault(start, start)
2040
1753
        stop = int(bits[1])
2041
 
        stop = self._int_cache.setdefault(stop, stop)
2042
1754
        basis_end = int(bits[2])
2043
1755
        delta_end = int(bits[3])
2044
 
        # We can't use StaticTuple here, because node[0] is a BTreeGraphIndex
2045
 
        # instance...
2046
 
        return (node[0], start, stop, basis_end, delta_end)
 
1756
        return node[0], start, stop, basis_end, delta_end
2047
1757
 
2048
1758
    def scan_unvalidated_index(self, graph_index):
2049
1759
        """Inform this _GCGraphIndex that there is an unvalidated index.
2050
1760
 
2051
1761
        This allows this _GCGraphIndex to keep track of any missing
2052
1762
        compression parents we may want to have filled in to make those
2053
 
        indices valid.  It also allows _GCGraphIndex to track any new keys.
 
1763
        indices valid.
2054
1764
 
2055
1765
        :param graph_index: A GraphIndex
2056
1766
        """
2057
 
        key_dependencies = self._key_dependencies
2058
 
        if key_dependencies is None:
2059
 
            return
2060
 
        for node in graph_index.iter_all_entries():
2061
 
            # Add parent refs from graph_index (and discard parent refs
2062
 
            # that the graph_index has).
2063
 
            key_dependencies.add_references(node[1], node[3][0])
 
1767
        if self._key_dependencies is not None:
 
1768
            # Add parent refs from graph_index (and discard parent refs that
 
1769
            # the graph_index has).
 
1770
            add_refs = self._key_dependencies.add_references
 
1771
            for node in graph_index.iter_all_entries():
 
1772
                add_refs(node[1], node[3][0])
 
1773
 
2064
1774
 
2065
1775
 
2066
1776
from bzrlib._groupcompress_py import (
2080
1790
        decode_base128_int,
2081
1791
        )
2082
1792
    GroupCompressor = PyrexGroupCompressor
2083
 
except ImportError, e:
2084
 
    osutils.failed_to_load_extension(e)
 
1793
except ImportError:
2085
1794
    GroupCompressor = PythonGroupCompressor
2086
1795