~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-07-25 03:40:12 UTC
  • mfrom: (4568.1.1 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20090725034012-2fnpljnq7uvk9ss2
(igc) Support doc generation via sphinx

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008-2011 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
23
23
except ImportError:
24
24
    pylzma = None
25
25
 
26
 
from bzrlib.lazy_import import lazy_import
27
 
lazy_import(globals(), """
28
26
from bzrlib import (
29
27
    annotate,
30
 
    config,
31
28
    debug,
32
29
    errors,
33
30
    graph as _mod_graph,
 
31
    knit,
34
32
    osutils,
35
33
    pack,
36
 
    static_tuple,
37
34
    trace,
38
 
    tsort,
39
35
    )
40
 
 
41
 
from bzrlib.repofmt import pack_repo
42
 
from bzrlib.i18n import gettext
43
 
""")
44
 
 
 
36
from bzrlib.graph import Graph
45
37
from bzrlib.btree_index import BTreeBuilder
46
38
from bzrlib.lru_cache import LRUSizeCache
 
39
from bzrlib.tsort import topo_sort
47
40
from bzrlib.versionedfile import (
48
 
    _KeyRefs,
49
41
    adapter_registry,
50
42
    AbsentContentFactory,
51
43
    ChunkedContentFactory,
52
44
    FulltextContentFactory,
53
 
    VersionedFilesWithFallbacks,
 
45
    VersionedFiles,
54
46
    )
55
47
 
56
 
# Minimum number of uncompressed bytes to try fetch at once when retrieving
57
 
# groupcompress blocks.
58
 
BATCH_SIZE = 2**16
59
 
 
60
48
_USE_LZMA = False and (pylzma is not None)
61
49
 
62
50
# osutils.sha_string('')
63
51
_null_sha1 = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
64
52
 
 
53
 
65
54
def sort_gc_optimal(parent_map):
66
55
    """Sort and group the keys in parent_map into groupcompress order.
67
56
 
73
62
    # groupcompress ordering is approximately reverse topological,
74
63
    # properly grouped by file-id.
75
64
    per_prefix_map = {}
76
 
    for key, value in parent_map.iteritems():
 
65
    for item in parent_map.iteritems():
 
66
        key = item[0]
77
67
        if isinstance(key, str) or len(key) == 1:
78
68
            prefix = ''
79
69
        else:
80
70
            prefix = key[0]
81
71
        try:
82
 
            per_prefix_map[prefix][key] = value
 
72
            per_prefix_map[prefix].append(item)
83
73
        except KeyError:
84
 
            per_prefix_map[prefix] = {key: value}
 
74
            per_prefix_map[prefix] = [item]
85
75
 
86
76
    present_keys = []
87
77
    for prefix in sorted(per_prefix_map):
88
 
        present_keys.extend(reversed(tsort.topo_sort(per_prefix_map[prefix])))
 
78
        present_keys.extend(reversed(topo_sort(per_prefix_map[prefix])))
89
79
    return present_keys
90
80
 
91
81
 
109
99
    def __init__(self):
110
100
        # map by key? or just order in file?
111
101
        self._compressor_name = None
112
 
        self._z_content_chunks = None
 
102
        self._z_content = None
113
103
        self._z_content_decompressor = None
114
104
        self._z_content_length = None
115
105
        self._content_length = None
128
118
        :param num_bytes: Ensure that we have extracted at least num_bytes of
129
119
            content. If None, consume everything
130
120
        """
131
 
        if self._content_length is None:
132
 
            raise AssertionError('self._content_length should never be None')
 
121
        # TODO: If we re-use the same content block at different times during
 
122
        #       get_record_stream(), it is possible that the first pass will
 
123
        #       get inserted, triggering an extract/_ensure_content() which
 
124
        #       will get rid of _z_content. And then the next use of the block
 
125
        #       will try to access _z_content (to send it over the wire), and
 
126
        #       fail because it is already extracted. Consider never releasing
 
127
        #       _z_content because of this.
133
128
        if num_bytes is None:
134
129
            num_bytes = self._content_length
135
130
        elif (self._content_length is not None
143
138
                self._content = ''.join(self._content_chunks)
144
139
                self._content_chunks = None
145
140
        if self._content is None:
146
 
            # We join self._z_content_chunks here, because if we are
147
 
            # decompressing, then it is *very* likely that we have a single
148
 
            # chunk
149
 
            if self._z_content_chunks is None:
 
141
            if self._z_content is None:
150
142
                raise AssertionError('No content to decompress')
151
 
            z_content = ''.join(self._z_content_chunks)
152
 
            if z_content == '':
 
143
            if self._z_content == '':
153
144
                self._content = ''
154
145
            elif self._compressor_name == 'lzma':
155
146
                # We don't do partial lzma decomp yet
156
 
                self._content = pylzma.decompress(z_content)
 
147
                self._content = pylzma.decompress(self._z_content)
157
148
            elif self._compressor_name == 'zlib':
158
149
                # Start a zlib decompressor
159
 
                if num_bytes * 4 > self._content_length * 3:
160
 
                    # If we are requesting more that 3/4ths of the content,
161
 
                    # just extract the whole thing in a single pass
162
 
                    num_bytes = self._content_length
163
 
                    self._content = zlib.decompress(z_content)
 
150
                if num_bytes is None:
 
151
                    self._content = zlib.decompress(self._z_content)
164
152
                else:
165
153
                    self._z_content_decompressor = zlib.decompressobj()
166
154
                    # Seed the decompressor with the uncompressed bytes, so
167
155
                    # that the rest of the code is simplified
168
156
                    self._content = self._z_content_decompressor.decompress(
169
 
                        z_content, num_bytes + _ZLIB_DECOMP_WINDOW)
170
 
                    if not self._z_content_decompressor.unconsumed_tail:
171
 
                        self._z_content_decompressor = None
 
157
                        self._z_content, num_bytes + _ZLIB_DECOMP_WINDOW)
172
158
            else:
173
159
                raise AssertionError('Unknown compressor: %r'
174
160
                                     % self._compressor_name)
176
162
        # 'unconsumed_tail'
177
163
 
178
164
        # Do we have enough bytes already?
179
 
        if len(self._content) >= num_bytes:
 
165
        if num_bytes is not None and len(self._content) >= num_bytes:
 
166
            return
 
167
        if num_bytes is None and self._z_content_decompressor is None:
 
168
            # We must have already decompressed everything
180
169
            return
181
170
        # If we got this far, and don't have a decompressor, something is wrong
182
171
        if self._z_content_decompressor is None:
183
172
            raise AssertionError(
184
173
                'No decompressor to decompress %d bytes' % num_bytes)
185
174
        remaining_decomp = self._z_content_decompressor.unconsumed_tail
186
 
        if not remaining_decomp:
187
 
            raise AssertionError('Nothing left to decompress')
188
 
        needed_bytes = num_bytes - len(self._content)
189
 
        # We always set max_size to 32kB over the minimum needed, so that
190
 
        # zlib will give us as much as we really want.
191
 
        # TODO: If this isn't good enough, we could make a loop here,
192
 
        #       that keeps expanding the request until we get enough
193
 
        self._content += self._z_content_decompressor.decompress(
194
 
            remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
195
 
        if len(self._content) < num_bytes:
196
 
            raise AssertionError('%d bytes wanted, only %d available'
197
 
                                 % (num_bytes, len(self._content)))
198
 
        if not self._z_content_decompressor.unconsumed_tail:
199
 
            # The stream is finished
200
 
            self._z_content_decompressor = None
 
175
        if num_bytes is None:
 
176
            if remaining_decomp:
 
177
                # We don't know how much is left, but we'll decompress it all
 
178
                self._content += self._z_content_decompressor.decompress(
 
179
                    remaining_decomp)
 
180
                # Note: There's what I consider a bug in zlib.decompressobj
 
181
                #       If you pass back in the entire unconsumed_tail, only
 
182
                #       this time you don't pass a max-size, it doesn't
 
183
                #       change the unconsumed_tail back to None/''.
 
184
                #       However, we know we are done with the whole stream
 
185
                self._z_content_decompressor = None
 
186
            # XXX: Why is this the only place in this routine we set this?
 
187
            self._content_length = len(self._content)
 
188
        else:
 
189
            if not remaining_decomp:
 
190
                raise AssertionError('Nothing left to decompress')
 
191
            needed_bytes = num_bytes - len(self._content)
 
192
            # We always set max_size to 32kB over the minimum needed, so that
 
193
            # zlib will give us as much as we really want.
 
194
            # TODO: If this isn't good enough, we could make a loop here,
 
195
            #       that keeps expanding the request until we get enough
 
196
            self._content += self._z_content_decompressor.decompress(
 
197
                remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
 
198
            if len(self._content) < num_bytes:
 
199
                raise AssertionError('%d bytes wanted, only %d available'
 
200
                                     % (num_bytes, len(self._content)))
 
201
            if not self._z_content_decompressor.unconsumed_tail:
 
202
                # The stream is finished
 
203
                self._z_content_decompressor = None
201
204
 
202
205
    def _parse_bytes(self, bytes, pos):
203
206
        """Read the various lengths from the header.
219
222
            # XXX: Define some GCCorrupt error ?
220
223
            raise AssertionError('Invalid bytes: (%d) != %d + %d' %
221
224
                                 (len(bytes), pos, self._z_content_length))
222
 
        self._z_content_chunks = (bytes[pos:],)
223
 
 
224
 
    @property
225
 
    def _z_content(self):
226
 
        """Return z_content_chunks as a simple string.
227
 
 
228
 
        Meant only to be used by the test suite.
229
 
        """
230
 
        if self._z_content_chunks is not None:
231
 
            return ''.join(self._z_content_chunks)
232
 
        return None
 
225
        self._z_content = bytes[pos:]
233
226
 
234
227
    @classmethod
235
228
    def from_bytes(cls, bytes):
291
284
        self._content_length = length
292
285
        self._content_chunks = content_chunks
293
286
        self._content = None
294
 
        self._z_content_chunks = None
 
287
        self._z_content = None
295
288
 
296
289
    def set_content(self, content):
297
290
        """Set the content of this block."""
298
291
        self._content_length = len(content)
299
292
        self._content = content
300
 
        self._z_content_chunks = None
 
293
        self._z_content = None
301
294
 
302
295
    def _create_z_content_using_lzma(self):
303
296
        if self._content_chunks is not None:
305
298
            self._content_chunks = None
306
299
        if self._content is None:
307
300
            raise AssertionError('Nothing to compress')
308
 
        z_content = pylzma.compress(self._content)
309
 
        self._z_content_chunks = (z_content,)
310
 
        self._z_content_length = len(z_content)
 
301
        self._z_content = pylzma.compress(self._content)
 
302
        self._z_content_length = len(self._z_content)
311
303
 
312
 
    def _create_z_content_from_chunks(self, chunks):
 
304
    def _create_z_content_from_chunks(self):
313
305
        compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION)
314
 
        # Peak in this point is 1 fulltext, 1 compressed text, + zlib overhead
315
 
        # (measured peak is maybe 30MB over the above...)
316
 
        compressed_chunks = map(compressor.compress, chunks)
 
306
        compressed_chunks = map(compressor.compress, self._content_chunks)
317
307
        compressed_chunks.append(compressor.flush())
318
 
        # Ignore empty chunks
319
 
        self._z_content_chunks = [c for c in compressed_chunks if c]
320
 
        self._z_content_length = sum(map(len, self._z_content_chunks))
 
308
        self._z_content = ''.join(compressed_chunks)
 
309
        self._z_content_length = len(self._z_content)
321
310
 
322
311
    def _create_z_content(self):
323
 
        if self._z_content_chunks is not None:
 
312
        if self._z_content is not None:
324
313
            return
325
314
        if _USE_LZMA:
326
315
            self._create_z_content_using_lzma()
327
316
            return
328
317
        if self._content_chunks is not None:
329
 
            chunks = self._content_chunks
330
 
        else:
331
 
            chunks = (self._content,)
332
 
        self._create_z_content_from_chunks(chunks)
 
318
            self._create_z_content_from_chunks()
 
319
            return
 
320
        self._z_content = zlib.compress(self._content)
 
321
        self._z_content_length = len(self._z_content)
333
322
 
334
 
    def to_chunks(self):
335
 
        """Create the byte stream as a series of 'chunks'"""
 
323
    def to_bytes(self):
 
324
        """Encode the information into a byte stream."""
336
325
        self._create_z_content()
337
326
        if _USE_LZMA:
338
327
            header = self.GCB_LZ_HEADER
339
328
        else:
340
329
            header = self.GCB_HEADER
341
 
        chunks = ['%s%d\n%d\n'
342
 
                  % (header, self._z_content_length, self._content_length),
 
330
        chunks = [header,
 
331
                  '%d\n%d\n' % (self._z_content_length, self._content_length),
 
332
                  self._z_content,
343
333
                 ]
344
 
        chunks.extend(self._z_content_chunks)
345
 
        total_len = sum(map(len, chunks))
346
 
        return total_len, chunks
347
 
 
348
 
    def to_bytes(self):
349
 
        """Encode the information into a byte stream."""
350
 
        total_len, chunks = self.to_chunks()
351
334
        return ''.join(chunks)
352
335
 
353
336
    def _dump(self, include_text=False):
467
450
                # Grab and cache the raw bytes for this entry
468
451
                # and break the ref-cycle with _manager since we don't need it
469
452
                # anymore
470
 
                try:
471
 
                    self._manager._prepare_for_extract()
472
 
                except zlib.error as value:
473
 
                    raise errors.DecompressCorruption("zlib: " + str(value))
 
453
                self._manager._prepare_for_extract()
474
454
                block = self._manager._block
475
455
                self._bytes = block.extract(self.key, self._start, self._end)
476
456
                # There are code paths that first extract as fulltext, and then
477
457
                # extract as storage_kind (smart fetch). So we don't break the
478
458
                # refcycle here, but instead in manager.get_record_stream()
 
459
                # self._manager = None
479
460
            if storage_kind == 'fulltext':
480
461
                return self._bytes
481
462
            else:
487
468
class _LazyGroupContentManager(object):
488
469
    """This manages a group of _LazyGroupCompressFactory objects."""
489
470
 
490
 
    _max_cut_fraction = 0.75 # We allow a block to be trimmed to 75% of
491
 
                             # current size, and still be considered
492
 
                             # resuable
493
 
    _full_block_size = 4*1024*1024
494
 
    _full_mixed_block_size = 2*1024*1024
495
 
    _full_enough_block_size = 3*1024*1024 # size at which we won't repack
496
 
    _full_enough_mixed_block_size = 2*768*1024 # 1.5MB
497
 
 
498
 
    def __init__(self, block, get_compressor_settings=None):
 
471
    def __init__(self, block):
499
472
        self._block = block
500
473
        # We need to preserve the ordering
501
474
        self._factories = []
502
475
        self._last_byte = 0
503
 
        self._get_settings = get_compressor_settings
504
 
        self._compressor_settings = None
505
 
 
506
 
    def _get_compressor_settings(self):
507
 
        if self._compressor_settings is not None:
508
 
            return self._compressor_settings
509
 
        settings = None
510
 
        if self._get_settings is not None:
511
 
            settings = self._get_settings()
512
 
        if settings is None:
513
 
            vf = GroupCompressVersionedFiles
514
 
            settings = vf._DEFAULT_COMPRESSOR_SETTINGS
515
 
        self._compressor_settings = settings
516
 
        return self._compressor_settings
517
476
 
518
477
    def add_factory(self, key, parents, start, end):
519
478
        if not self._factories:
552
511
        new_block.set_content(self._block._content[:last_byte])
553
512
        self._block = new_block
554
513
 
555
 
    def _make_group_compressor(self):
556
 
        return GroupCompressor(self._get_compressor_settings())
557
 
 
558
514
    def _rebuild_block(self):
559
515
        """Create a new GroupCompressBlock with only the referenced texts."""
560
 
        compressor = self._make_group_compressor()
 
516
        compressor = GroupCompressor()
561
517
        tstart = time.time()
562
518
        old_length = self._block._content_length
563
519
        end_point = 0
575
531
        #       block? It seems hard to come up with a method that it would
576
532
        #       expand, since we do full compression again. Perhaps based on a
577
533
        #       request that ends up poorly ordered?
578
 
        # TODO: If the content would have expanded, then we would want to
579
 
        #       handle a case where we need to split the block.
580
 
        #       Now that we have a user-tweakable option
581
 
        #       (max_bytes_to_index), it is possible that one person set it
582
 
        #       to a very low value, causing poor compression.
583
534
        delta = time.time() - tstart
584
535
        self._block = new_block
585
536
        trace.mutter('creating new compressed block on-the-fly in %.3fs'
594
545
        # time (self._block._content) is a little expensive.
595
546
        self._block._ensure_content(self._last_byte)
596
547
 
597
 
    def _check_rebuild_action(self):
 
548
    def _check_rebuild_block(self):
598
549
        """Check to see if our block should be repacked."""
599
550
        total_bytes_used = 0
600
551
        last_byte_used = 0
601
552
        for factory in self._factories:
602
553
            total_bytes_used += factory._end - factory._start
603
 
            if last_byte_used < factory._end:
604
 
                last_byte_used = factory._end
605
 
        # If we are using more than half of the bytes from the block, we have
606
 
        # nothing else to check
 
554
            last_byte_used = max(last_byte_used, factory._end)
 
555
        # If we are using most of the bytes from the block, we have nothing
 
556
        # else to check (currently more that 1/2)
607
557
        if total_bytes_used * 2 >= self._block._content_length:
608
 
            return None, last_byte_used, total_bytes_used
609
 
        # We are using less than 50% of the content. Is the content we are
610
 
        # using at the beginning of the block? If so, we can just trim the
611
 
        # tail, rather than rebuilding from scratch.
 
558
            return
 
559
        # Can we just strip off the trailing bytes? If we are going to be
 
560
        # transmitting more than 50% of the front of the content, go ahead
612
561
        if total_bytes_used * 2 > last_byte_used:
613
 
            return 'trim', last_byte_used, total_bytes_used
 
562
            self._trim_block(last_byte_used)
 
563
            return
614
564
 
615
565
        # We are using a small amount of the data, and it isn't just packed
616
566
        # nicely at the front, so rebuild the content.
623
573
        #       expanding many deltas into fulltexts, as well.
624
574
        #       If we build a cheap enough 'strip', then we could try a strip,
625
575
        #       if that expands the content, we then rebuild.
626
 
        return 'rebuild', last_byte_used, total_bytes_used
627
 
 
628
 
    def check_is_well_utilized(self):
629
 
        """Is the current block considered 'well utilized'?
630
 
 
631
 
        This heuristic asks if the current block considers itself to be a fully
632
 
        developed group, rather than just a loose collection of data.
633
 
        """
634
 
        if len(self._factories) == 1:
635
 
            # A block of length 1 could be improved by combining with other
636
 
            # groups - don't look deeper. Even larger than max size groups
637
 
            # could compress well with adjacent versions of the same thing.
638
 
            return False
639
 
        action, last_byte_used, total_bytes_used = self._check_rebuild_action()
640
 
        block_size = self._block._content_length
641
 
        if total_bytes_used < block_size * self._max_cut_fraction:
642
 
            # This block wants to trim itself small enough that we want to
643
 
            # consider it under-utilized.
644
 
            return False
645
 
        # TODO: This code is meant to be the twin of _insert_record_stream's
646
 
        #       'start_new_block' logic. It would probably be better to factor
647
 
        #       out that logic into a shared location, so that it stays
648
 
        #       together better
649
 
        # We currently assume a block is properly utilized whenever it is >75%
650
 
        # of the size of a 'full' block. In normal operation, a block is
651
 
        # considered full when it hits 4MB of same-file content. So any block
652
 
        # >3MB is 'full enough'.
653
 
        # The only time this isn't true is when a given block has large-object
654
 
        # content. (a single file >4MB, etc.)
655
 
        # Under these circumstances, we allow a block to grow to
656
 
        # 2 x largest_content.  Which means that if a given block had a large
657
 
        # object, it may actually be under-utilized. However, given that this
658
 
        # is 'pack-on-the-fly' it is probably reasonable to not repack large
659
 
        # content blobs on-the-fly. Note that because we return False for all
660
 
        # 1-item blobs, we will repack them; we may wish to reevaluate our
661
 
        # treatment of large object blobs in the future.
662
 
        if block_size >= self._full_enough_block_size:
663
 
            return True
664
 
        # If a block is <3MB, it still may be considered 'full' if it contains
665
 
        # mixed content. The current rule is 2MB of mixed content is considered
666
 
        # full. So check to see if this block contains mixed content, and
667
 
        # set the threshold appropriately.
668
 
        common_prefix = None
669
 
        for factory in self._factories:
670
 
            prefix = factory.key[:-1]
671
 
            if common_prefix is None:
672
 
                common_prefix = prefix
673
 
            elif prefix != common_prefix:
674
 
                # Mixed content, check the size appropriately
675
 
                if block_size >= self._full_enough_mixed_block_size:
676
 
                    return True
677
 
                break
678
 
        # The content failed both the mixed check and the single-content check
679
 
        # so obviously it is not fully utilized
680
 
        # TODO: there is one other constraint that isn't being checked
681
 
        #       namely, that the entries in the block are in the appropriate
682
 
        #       order. For example, you could insert the entries in exactly
683
 
        #       reverse groupcompress order, and we would think that is ok.
684
 
        #       (all the right objects are in one group, and it is fully
685
 
        #       utilized, etc.) For now, we assume that case is rare,
686
 
        #       especially since we should always fetch in 'groupcompress'
687
 
        #       order.
688
 
        return False
689
 
 
690
 
    def _check_rebuild_block(self):
691
 
        action, last_byte_used, total_bytes_used = self._check_rebuild_action()
692
 
        if action is None:
693
 
            return
694
 
        if action == 'trim':
695
 
            self._trim_block(last_byte_used)
696
 
        elif action == 'rebuild':
697
 
            self._rebuild_block()
698
 
        else:
699
 
            raise ValueError('unknown rebuild action: %r' % (action,))
 
576
        self._rebuild_block()
700
577
 
701
578
    def _wire_bytes(self):
702
579
        """Return a byte stream suitable for transmitting over the wire."""
736
613
        z_header_bytes = zlib.compress(header_bytes)
737
614
        del header_bytes
738
615
        z_header_bytes_len = len(z_header_bytes)
739
 
        block_bytes_len, block_chunks = self._block.to_chunks()
 
616
        block_bytes = self._block.to_bytes()
740
617
        lines.append('%d\n%d\n%d\n' % (z_header_bytes_len, header_bytes_len,
741
 
                                       block_bytes_len))
 
618
                                       len(block_bytes)))
742
619
        lines.append(z_header_bytes)
743
 
        lines.extend(block_chunks)
744
 
        del z_header_bytes, block_chunks
745
 
        # TODO: This is a point where we will double the memory consumption. To
746
 
        #       avoid this, we probably have to switch to a 'chunked' api
 
620
        lines.append(block_bytes)
 
621
        del z_header_bytes, block_bytes
747
622
        return ''.join(lines)
748
623
 
749
624
    @classmethod
750
625
    def from_bytes(cls, bytes):
751
626
        # TODO: This does extra string copying, probably better to do it a
752
 
        #       different way. At a minimum this creates 2 copies of the
753
 
        #       compressed content
 
627
        #       different way
754
628
        (storage_kind, z_header_len, header_len,
755
629
         block_len, rest) = bytes.split('\n', 4)
756
630
        del bytes
808
682
 
809
683
class _CommonGroupCompressor(object):
810
684
 
811
 
    def __init__(self, settings=None):
 
685
    def __init__(self):
812
686
        """Create a GroupCompressor."""
813
687
        self.chunks = []
814
688
        self._last = None
817
691
        self.labels_deltas = {}
818
692
        self._delta_index = None # Set by the children
819
693
        self._block = GroupCompressBlock()
820
 
        if settings is None:
821
 
            self._settings = {}
822
 
        else:
823
 
            self._settings = settings
824
694
 
825
695
    def compress(self, key, bytes, expected_sha, nostore_sha=None, soft=False):
826
696
        """Compress lines with label key.
918
788
 
919
789
        After calling this, the compressor should no longer be used
920
790
        """
 
791
        # TODO: this causes us to 'bloat' to 2x the size of content in the
 
792
        #       group. This has an impact for 'commit' of large objects.
 
793
        #       One possibility is to use self._content_chunks, and be lazy and
 
794
        #       only fill out self._content as a full string when we actually
 
795
        #       need it. That would at least drop the peak memory consumption
 
796
        #       for 'commit' down to ~1x the size of the largest file, at a
 
797
        #       cost of increased complexity within this code. 2x is still <<
 
798
        #       3x the size of the largest file, so we are doing ok.
921
799
        self._block.set_chunked_content(self.chunks, self.endpoint)
922
800
        self.chunks = None
923
801
        self._delta_index = None
941
819
 
942
820
class PythonGroupCompressor(_CommonGroupCompressor):
943
821
 
944
 
    def __init__(self, settings=None):
 
822
    def __init__(self):
945
823
        """Create a GroupCompressor.
946
824
 
947
825
        Used only if the pyrex version is not available.
948
826
        """
949
 
        super(PythonGroupCompressor, self).__init__(settings)
 
827
        super(PythonGroupCompressor, self).__init__()
950
828
        self._delta_index = LinesDeltaIndex([])
951
829
        # The actual content is managed by LinesDeltaIndex
952
830
        self.chunks = self._delta_index.lines
989
867
 
990
868
    It contains code very similar to SequenceMatcher because of having a similar
991
869
    task. However some key differences apply:
992
 
 
993
 
    * there is no junk, we want a minimal edit not a human readable diff.
994
 
    * we don't filter very common lines (because we don't know where a good
995
 
      range will start, and after the first text we want to be emitting minmal
996
 
      edits only.
997
 
    * we chain the left side, not the right side
998
 
    * we incrementally update the adjacency matrix as new lines are provided.
999
 
    * we look for matches in all of the left side, so the routine which does
1000
 
      the analagous task of find_longest_match does not need to filter on the
1001
 
      left side.
 
870
     - there is no junk, we want a minimal edit not a human readable diff.
 
871
     - we don't filter very common lines (because we don't know where a good
 
872
       range will start, and after the first text we want to be emitting minmal
 
873
       edits only.
 
874
     - we chain the left side, not the right side
 
875
     - we incrementally update the adjacency matrix as new lines are provided.
 
876
     - we look for matches in all of the left side, so the routine which does
 
877
       the analagous task of find_longest_match does not need to filter on the
 
878
       left side.
1002
879
    """
1003
880
 
1004
 
    def __init__(self, settings=None):
1005
 
        super(PyrexGroupCompressor, self).__init__(settings)
1006
 
        max_bytes_to_index = self._settings.get('max_bytes_to_index', 0)
1007
 
        self._delta_index = DeltaIndex(max_bytes_to_index=max_bytes_to_index)
 
881
    def __init__(self):
 
882
        super(PyrexGroupCompressor, self).__init__()
 
883
        self._delta_index = DeltaIndex()
1008
884
 
1009
885
    def _compress(self, key, bytes, max_delta_size, soft=False):
1010
886
        """see _CommonGroupCompressor._compress"""
1085
961
        index = _GCGraphIndex(graph_index, lambda:True, parents=parents,
1086
962
            add_callback=graph_index.add_nodes,
1087
963
            inconsistency_fatal=inconsistency_fatal)
1088
 
        access = pack_repo._DirectPackAccess({})
 
964
        access = knit._DirectPackAccess({})
1089
965
        access.set_writer(writer, graph_index, (transport, 'newpack'))
1090
966
        result = GroupCompressVersionedFiles(index, access, delta)
1091
967
        result.stream = stream
1099
975
    versioned_files.stream.close()
1100
976
 
1101
977
 
1102
 
class _BatchingBlockFetcher(object):
1103
 
    """Fetch group compress blocks in batches.
1104
 
 
1105
 
    :ivar total_bytes: int of expected number of bytes needed to fetch the
1106
 
        currently pending batch.
1107
 
    """
1108
 
 
1109
 
    def __init__(self, gcvf, locations, get_compressor_settings=None):
1110
 
        self.gcvf = gcvf
1111
 
        self.locations = locations
1112
 
        self.keys = []
1113
 
        self.batch_memos = {}
1114
 
        self.memos_to_get = []
1115
 
        self.total_bytes = 0
1116
 
        self.last_read_memo = None
1117
 
        self.manager = None
1118
 
        self._get_compressor_settings = get_compressor_settings
1119
 
 
1120
 
    def add_key(self, key):
1121
 
        """Add another to key to fetch.
1122
 
 
1123
 
        :return: The estimated number of bytes needed to fetch the batch so
1124
 
            far.
1125
 
        """
1126
 
        self.keys.append(key)
1127
 
        index_memo, _, _, _ = self.locations[key]
1128
 
        read_memo = index_memo[0:3]
1129
 
        # Three possibilities for this read_memo:
1130
 
        #  - it's already part of this batch; or
1131
 
        #  - it's not yet part of this batch, but is already cached; or
1132
 
        #  - it's not yet part of this batch and will need to be fetched.
1133
 
        if read_memo in self.batch_memos:
1134
 
            # This read memo is already in this batch.
1135
 
            return self.total_bytes
1136
 
        try:
1137
 
            cached_block = self.gcvf._group_cache[read_memo]
1138
 
        except KeyError:
1139
 
            # This read memo is new to this batch, and the data isn't cached
1140
 
            # either.
1141
 
            self.batch_memos[read_memo] = None
1142
 
            self.memos_to_get.append(read_memo)
1143
 
            byte_length = read_memo[2]
1144
 
            self.total_bytes += byte_length
1145
 
        else:
1146
 
            # This read memo is new to this batch, but cached.
1147
 
            # Keep a reference to the cached block in batch_memos because it's
1148
 
            # certain that we'll use it when this batch is processed, but
1149
 
            # there's a risk that it would fall out of _group_cache between now
1150
 
            # and then.
1151
 
            self.batch_memos[read_memo] = cached_block
1152
 
        return self.total_bytes
1153
 
 
1154
 
    def _flush_manager(self):
1155
 
        if self.manager is not None:
1156
 
            for factory in self.manager.get_record_stream():
1157
 
                yield factory
1158
 
            self.manager = None
1159
 
            self.last_read_memo = None
1160
 
 
1161
 
    def yield_factories(self, full_flush=False):
1162
 
        """Yield factories for keys added since the last yield.  They will be
1163
 
        returned in the order they were added via add_key.
1164
 
 
1165
 
        :param full_flush: by default, some results may not be returned in case
1166
 
            they can be part of the next batch.  If full_flush is True, then
1167
 
            all results are returned.
1168
 
        """
1169
 
        if self.manager is None and not self.keys:
1170
 
            return
1171
 
        # Fetch all memos in this batch.
1172
 
        blocks = self.gcvf._get_blocks(self.memos_to_get)
1173
 
        # Turn blocks into factories and yield them.
1174
 
        memos_to_get_stack = list(self.memos_to_get)
1175
 
        memos_to_get_stack.reverse()
1176
 
        for key in self.keys:
1177
 
            index_memo, _, parents, _ = self.locations[key]
1178
 
            read_memo = index_memo[:3]
1179
 
            if self.last_read_memo != read_memo:
1180
 
                # We are starting a new block. If we have a
1181
 
                # manager, we have found everything that fits for
1182
 
                # now, so yield records
1183
 
                for factory in self._flush_manager():
1184
 
                    yield factory
1185
 
                # Now start a new manager.
1186
 
                if memos_to_get_stack and memos_to_get_stack[-1] == read_memo:
1187
 
                    # The next block from _get_blocks will be the block we
1188
 
                    # need.
1189
 
                    block_read_memo, block = blocks.next()
1190
 
                    if block_read_memo != read_memo:
1191
 
                        raise AssertionError(
1192
 
                            "block_read_memo out of sync with read_memo"
1193
 
                            "(%r != %r)" % (block_read_memo, read_memo))
1194
 
                    self.batch_memos[read_memo] = block
1195
 
                    memos_to_get_stack.pop()
1196
 
                else:
1197
 
                    block = self.batch_memos[read_memo]
1198
 
                self.manager = _LazyGroupContentManager(block,
1199
 
                    get_compressor_settings=self._get_compressor_settings)
1200
 
                self.last_read_memo = read_memo
1201
 
            start, end = index_memo[3:5]
1202
 
            self.manager.add_factory(key, parents, start, end)
1203
 
        if full_flush:
1204
 
            for factory in self._flush_manager():
1205
 
                yield factory
1206
 
        del self.keys[:]
1207
 
        self.batch_memos.clear()
1208
 
        del self.memos_to_get[:]
1209
 
        self.total_bytes = 0
1210
 
 
1211
 
 
1212
 
class GroupCompressVersionedFiles(VersionedFilesWithFallbacks):
 
978
class GroupCompressVersionedFiles(VersionedFiles):
1213
979
    """A group-compress based VersionedFiles implementation."""
1214
980
 
1215
 
    # This controls how the GroupCompress DeltaIndex works. Basically, we
1216
 
    # compute hash pointers into the source blocks (so hash(text) => text).
1217
 
    # However each of these references costs some memory in trade against a
1218
 
    # more accurate match result. For very large files, they either are
1219
 
    # pre-compressed and change in bulk whenever they change, or change in just
1220
 
    # local blocks. Either way, 'improved resolution' is not very helpful,
1221
 
    # versus running out of memory trying to track everything. The default max
1222
 
    # gives 100% sampling of a 1MB file.
1223
 
    _DEFAULT_MAX_BYTES_TO_INDEX = 1024 * 1024
1224
 
    _DEFAULT_COMPRESSOR_SETTINGS = {'max_bytes_to_index':
1225
 
                                     _DEFAULT_MAX_BYTES_TO_INDEX}
1226
 
 
1227
 
    def __init__(self, index, access, delta=True, _unadded_refs=None,
1228
 
                 _group_cache=None):
 
981
    def __init__(self, index, access, delta=True):
1229
982
        """Create a GroupCompressVersionedFiles object.
1230
983
 
1231
984
        :param index: The index object storing access and graph data.
1232
985
        :param access: The access object storing raw data.
1233
986
        :param delta: Whether to delta compress or just entropy compress.
1234
 
        :param _unadded_refs: private parameter, don't use.
1235
 
        :param _group_cache: private parameter, don't use.
1236
987
        """
1237
988
        self._index = index
1238
989
        self._access = access
1239
990
        self._delta = delta
1240
 
        if _unadded_refs is None:
1241
 
            _unadded_refs = {}
1242
 
        self._unadded_refs = _unadded_refs
1243
 
        if _group_cache is None:
1244
 
            _group_cache = LRUSizeCache(max_size=50*1024*1024)
1245
 
        self._group_cache = _group_cache
1246
 
        self._immediate_fallback_vfs = []
1247
 
        self._max_bytes_to_index = None
1248
 
 
1249
 
    def without_fallbacks(self):
1250
 
        """Return a clone of this object without any fallbacks configured."""
1251
 
        return GroupCompressVersionedFiles(self._index, self._access,
1252
 
            self._delta, _unadded_refs=dict(self._unadded_refs),
1253
 
            _group_cache=self._group_cache)
 
991
        self._unadded_refs = {}
 
992
        self._group_cache = LRUSizeCache(max_size=50*1024*1024)
 
993
        self._fallback_vfs = []
1254
994
 
1255
995
    def add_lines(self, key, parents, lines, parent_texts=None,
1256
996
        left_matching_blocks=None, nostore_sha=None, random_id=False,
1260
1000
        :param key: The key tuple of the text to add.
1261
1001
        :param parents: The parents key tuples of the text to add.
1262
1002
        :param lines: A list of lines. Each line must be a bytestring. And all
1263
 
            of them except the last must be terminated with \\n and contain no
1264
 
            other \\n's. The last line may either contain no \\n's or a single
1265
 
            terminating \\n. If the lines list does meet this constraint the
1266
 
            add routine may error or may succeed - but you will be unable to
1267
 
            read the data back accurately. (Checking the lines have been split
 
1003
            of them except the last must be terminated with \n and contain no
 
1004
            other \n's. The last line may either contain no \n's or a single
 
1005
            terminating \n. If the lines list does meet this constraint the add
 
1006
            routine may error or may succeed - but you will be unable to read
 
1007
            the data back accurately. (Checking the lines have been split
1268
1008
            correctly is expensive and extremely unlikely to catch bugs so it
1269
1009
            is not done at runtime unless check_content is True.)
1270
1010
        :param parent_texts: An optional dictionary containing the opaque
1325
1065
 
1326
1066
        :param a_versioned_files: A VersionedFiles object.
1327
1067
        """
1328
 
        self._immediate_fallback_vfs.append(a_versioned_files)
 
1068
        self._fallback_vfs.append(a_versioned_files)
1329
1069
 
1330
1070
    def annotate(self, key):
1331
1071
        """See VersionedFiles.annotate."""
1335
1075
    def get_annotator(self):
1336
1076
        return annotate.Annotator(self)
1337
1077
 
1338
 
    def check(self, progress_bar=None, keys=None):
 
1078
    def check(self, progress_bar=None):
1339
1079
        """See VersionedFiles.check()."""
1340
 
        if keys is None:
1341
 
            keys = self.keys()
1342
 
            for record in self.get_record_stream(keys, 'unordered', True):
1343
 
                record.get_bytes_as('fulltext')
1344
 
        else:
1345
 
            return self.get_record_stream(keys, 'unordered', True)
1346
 
 
1347
 
    def clear_cache(self):
1348
 
        """See VersionedFiles.clear_cache()"""
1349
 
        self._group_cache.clear()
1350
 
        self._index._graph_index.clear_cache()
1351
 
        self._index._int_cache.clear()
 
1080
        keys = self.keys()
 
1081
        for record in self.get_record_stream(keys, 'unordered', True):
 
1082
            record.get_bytes_as('fulltext')
1352
1083
 
1353
1084
    def _check_add(self, key, lines, random_id, check_content):
1354
1085
        """check that version_id and lines are safe to add."""
1385
1116
            and so on.
1386
1117
        """
1387
1118
        result = {}
1388
 
        sources = [self._index] + self._immediate_fallback_vfs
 
1119
        sources = [self._index] + self._fallback_vfs
1389
1120
        source_results = []
1390
1121
        missing = set(keys)
1391
1122
        for source in sources:
1397
1128
            missing.difference_update(set(new_result))
1398
1129
        return result, source_results
1399
1130
 
1400
 
    def _get_blocks(self, read_memos):
1401
 
        """Get GroupCompressBlocks for the given read_memos.
1402
 
 
1403
 
        :returns: a series of (read_memo, block) pairs, in the order they were
1404
 
            originally passed.
1405
 
        """
1406
 
        cached = {}
1407
 
        for read_memo in read_memos:
1408
 
            try:
1409
 
                block = self._group_cache[read_memo]
1410
 
            except KeyError:
1411
 
                pass
1412
 
            else:
1413
 
                cached[read_memo] = block
1414
 
        not_cached = []
1415
 
        not_cached_seen = set()
1416
 
        for read_memo in read_memos:
1417
 
            if read_memo in cached:
1418
 
                # Don't fetch what we already have
1419
 
                continue
1420
 
            if read_memo in not_cached_seen:
1421
 
                # Don't try to fetch the same data twice
1422
 
                continue
1423
 
            not_cached.append(read_memo)
1424
 
            not_cached_seen.add(read_memo)
1425
 
        raw_records = self._access.get_raw_records(not_cached)
1426
 
        for read_memo in read_memos:
1427
 
            try:
1428
 
                yield read_memo, cached[read_memo]
1429
 
            except KeyError:
1430
 
                # Read the block, and cache it.
1431
 
                zdata = raw_records.next()
1432
 
                block = GroupCompressBlock.from_bytes(zdata)
1433
 
                self._group_cache[read_memo] = block
1434
 
                cached[read_memo] = block
1435
 
                yield read_memo, block
 
1131
    def _get_block(self, index_memo):
 
1132
        read_memo = index_memo[0:3]
 
1133
        # get the group:
 
1134
        try:
 
1135
            block = self._group_cache[read_memo]
 
1136
        except KeyError:
 
1137
            # read the group
 
1138
            zdata = self._access.get_raw_records([read_memo]).next()
 
1139
            # decompress - whole thing - this is not a bug, as it
 
1140
            # permits caching. We might want to store the partially
 
1141
            # decompresed group and decompress object, so that recent
 
1142
            # texts are not penalised by big groups.
 
1143
            block = GroupCompressBlock.from_bytes(zdata)
 
1144
            self._group_cache[read_memo] = block
 
1145
        # cheapo debugging:
 
1146
        # print len(zdata), len(plain)
 
1147
        # parse - requires split_lines, better to have byte offsets
 
1148
        # here (but not by much - we only split the region for the
 
1149
        # recipe, and we often want to end up with lines anyway.
 
1150
        return block
1436
1151
 
1437
1152
    def get_missing_compression_parent_keys(self):
1438
1153
        """Return the keys of missing compression parents.
1492
1207
        parent_map = {}
1493
1208
        key_to_source_map = {}
1494
1209
        source_results = []
1495
 
        for source in self._immediate_fallback_vfs:
 
1210
        for source in self._fallback_vfs:
1496
1211
            if not missing:
1497
1212
                break
1498
1213
            source_parents = source.get_parent_map(missing)
1508
1223
 
1509
1224
        The returned objects should be in the order defined by 'ordering',
1510
1225
        which can weave between different sources.
1511
 
 
1512
1226
        :param ordering: Must be one of 'topological' or 'groupcompress'
1513
1227
        :return: List of [(source, [keys])] tuples, such that all keys are in
1514
1228
            the defined order, regardless of source.
1515
1229
        """
1516
1230
        if ordering == 'topological':
1517
 
            present_keys = tsort.topo_sort(parent_map)
 
1231
            present_keys = topo_sort(parent_map)
1518
1232
        else:
1519
1233
            # ordering == 'groupcompress'
1520
1234
            # XXX: This only optimizes for the target ordering. We may need
1605
1319
                unadded_keys, source_result)
1606
1320
        for key in missing:
1607
1321
            yield AbsentContentFactory(key)
1608
 
        # Batch up as many keys as we can until either:
1609
 
        #  - we encounter an unadded ref, or
1610
 
        #  - we run out of keys, or
1611
 
        #  - the total bytes to retrieve for this batch > BATCH_SIZE
1612
 
        batcher = _BatchingBlockFetcher(self, locations,
1613
 
            get_compressor_settings=self._get_compressor_settings)
 
1322
        manager = None
 
1323
        last_read_memo = None
 
1324
        # TODO: This works fairly well at batching up existing groups into a
 
1325
        #       streamable format, and possibly allowing for taking one big
 
1326
        #       group and splitting it when it isn't fully utilized.
 
1327
        #       However, it doesn't allow us to find under-utilized groups and
 
1328
        #       combine them into a bigger group on the fly.
 
1329
        #       (Consider the issue with how chk_map inserts texts
 
1330
        #       one-at-a-time.) This could be done at insert_record_stream()
 
1331
        #       time, but it probably would decrease the number of
 
1332
        #       bytes-on-the-wire for fetch.
1614
1333
        for source, keys in source_keys:
1615
1334
            if source is self:
1616
1335
                for key in keys:
1617
1336
                    if key in self._unadded_refs:
1618
 
                        # Flush batch, then yield unadded ref from
1619
 
                        # self._compressor.
1620
 
                        for factory in batcher.yield_factories(full_flush=True):
1621
 
                            yield factory
 
1337
                        if manager is not None:
 
1338
                            for factory in manager.get_record_stream():
 
1339
                                yield factory
 
1340
                            last_read_memo = manager = None
1622
1341
                        bytes, sha1 = self._compressor.extract(key)
1623
1342
                        parents = self._unadded_refs[key]
1624
1343
                        yield FulltextContentFactory(key, parents, sha1, bytes)
1625
 
                        continue
1626
 
                    if batcher.add_key(key) > BATCH_SIZE:
1627
 
                        # Ok, this batch is big enough.  Yield some results.
1628
 
                        for factory in batcher.yield_factories():
1629
 
                            yield factory
 
1344
                    else:
 
1345
                        index_memo, _, parents, (method, _) = locations[key]
 
1346
                        read_memo = index_memo[0:3]
 
1347
                        if last_read_memo != read_memo:
 
1348
                            # We are starting a new block. If we have a
 
1349
                            # manager, we have found everything that fits for
 
1350
                            # now, so yield records
 
1351
                            if manager is not None:
 
1352
                                for factory in manager.get_record_stream():
 
1353
                                    yield factory
 
1354
                            # Now start a new manager
 
1355
                            block = self._get_block(index_memo)
 
1356
                            manager = _LazyGroupContentManager(block)
 
1357
                            last_read_memo = read_memo
 
1358
                        start, end = index_memo[3:5]
 
1359
                        manager.add_factory(key, parents, start, end)
1630
1360
            else:
1631
 
                for factory in batcher.yield_factories(full_flush=True):
1632
 
                    yield factory
 
1361
                if manager is not None:
 
1362
                    for factory in manager.get_record_stream():
 
1363
                        yield factory
 
1364
                    last_read_memo = manager = None
1633
1365
                for record in source.get_record_stream(keys, ordering,
1634
1366
                                                       include_delta_closure):
1635
1367
                    yield record
1636
 
        for factory in batcher.yield_factories(full_flush=True):
1637
 
            yield factory
 
1368
        if manager is not None:
 
1369
            for factory in manager.get_record_stream():
 
1370
                yield factory
1638
1371
 
1639
1372
    def get_sha1s(self, keys):
1640
1373
        """See VersionedFiles.get_sha1s()."""
1662
1395
        for _ in self._insert_record_stream(stream, random_id=False):
1663
1396
            pass
1664
1397
 
1665
 
    def _get_compressor_settings(self):
1666
 
        if self._max_bytes_to_index is None:
1667
 
            # TODO: VersionedFiles don't know about their containing
1668
 
            #       repository, so they don't have much of an idea about their
1669
 
            #       location. So for now, this is only a global option.
1670
 
            c = config.GlobalConfig()
1671
 
            val = c.get_user_option('bzr.groupcompress.max_bytes_to_index')
1672
 
            if val is not None:
1673
 
                try:
1674
 
                    val = int(val)
1675
 
                except ValueError, e:
1676
 
                    trace.warning('Value for '
1677
 
                                  '"bzr.groupcompress.max_bytes_to_index"'
1678
 
                                  ' %r is not an integer'
1679
 
                                  % (val,))
1680
 
                    val = None
1681
 
            if val is None:
1682
 
                val = self._DEFAULT_MAX_BYTES_TO_INDEX
1683
 
            self._max_bytes_to_index = val
1684
 
        return {'max_bytes_to_index': self._max_bytes_to_index}
1685
 
 
1686
 
    def _make_group_compressor(self):
1687
 
        return GroupCompressor(self._get_compressor_settings())
1688
 
 
1689
1398
    def _insert_record_stream(self, stream, random_id=False, nostore_sha=None,
1690
1399
                              reuse_blocks=True):
1691
1400
        """Internal core to insert a record stream into this container.
1714
1423
                return adapter
1715
1424
        # This will go up to fulltexts for gc to gc fetching, which isn't
1716
1425
        # ideal.
1717
 
        self._compressor = self._make_group_compressor()
 
1426
        self._compressor = GroupCompressor()
1718
1427
        self._unadded_refs = {}
1719
1428
        keys_to_add = []
1720
1429
        def flush():
1721
 
            bytes_len, chunks = self._compressor.flush().to_chunks()
1722
 
            self._compressor = self._make_group_compressor()
1723
 
            # Note: At this point we still have 1 copy of the fulltext (in
1724
 
            #       record and the var 'bytes'), and this generates 2 copies of
1725
 
            #       the compressed text (one for bytes, one in chunks)
1726
 
            # TODO: Push 'chunks' down into the _access api, so that we don't
1727
 
            #       have to double compressed memory here
1728
 
            # TODO: Figure out how to indicate that we would be happy to free
1729
 
            #       the fulltext content at this point. Note that sometimes we
1730
 
            #       will want it later (streaming CHK pages), but most of the
1731
 
            #       time we won't (everything else)
1732
 
            bytes = ''.join(chunks)
1733
 
            del chunks
 
1430
            bytes = self._compressor.flush().to_bytes()
1734
1431
            index, start, length = self._access.add_raw_records(
1735
1432
                [(None, len(bytes))], bytes)[0]
1736
1433
            nodes = []
1739
1436
            self._index.add_records(nodes, random_id=random_id)
1740
1437
            self._unadded_refs = {}
1741
1438
            del keys_to_add[:]
 
1439
            self._compressor = GroupCompressor()
1742
1440
 
1743
1441
        last_prefix = None
1744
1442
        max_fulltext_len = 0
1748
1446
        block_length = None
1749
1447
        # XXX: TODO: remove this, it is just for safety checking for now
1750
1448
        inserted_keys = set()
1751
 
        reuse_this_block = reuse_blocks
1752
1449
        for record in stream:
1753
1450
            # Raise an error when a record is missing.
1754
1451
            if record.storage_kind == 'absent':
1755
1452
                raise errors.RevisionNotPresent(record.key, self)
1756
1453
            if random_id:
1757
1454
                if record.key in inserted_keys:
1758
 
                    trace.note(gettext('Insert claimed random_id=True,'
1759
 
                               ' but then inserted %r two times'), record.key)
 
1455
                    trace.note('Insert claimed random_id=True,'
 
1456
                               ' but then inserted %r two times', record.key)
1760
1457
                    continue
1761
1458
                inserted_keys.add(record.key)
1762
1459
            if reuse_blocks:
1763
1460
                # If the reuse_blocks flag is set, check to see if we can just
1764
1461
                # copy a groupcompress block as-is.
1765
 
                # We only check on the first record (groupcompress-block) not
1766
 
                # on all of the (groupcompress-block-ref) entries.
1767
 
                # The reuse_this_block flag is then kept for as long as
1768
 
                if record.storage_kind == 'groupcompress-block':
1769
 
                    # Check to see if we really want to re-use this block
1770
 
                    insert_manager = record._manager
1771
 
                    reuse_this_block = insert_manager.check_is_well_utilized()
1772
 
            else:
1773
 
                reuse_this_block = False
1774
 
            if reuse_this_block:
1775
 
                # We still want to reuse this block
1776
1462
                if record.storage_kind == 'groupcompress-block':
1777
1463
                    # Insert the raw block into the target repo
1778
1464
                    insert_manager = record._manager
 
1465
                    insert_manager._check_rebuild_block()
1779
1466
                    bytes = record._manager._block.to_bytes()
1780
1467
                    _, start, length = self._access.add_raw_records(
1781
1468
                        [(None, len(bytes))], bytes)[0]
1786
1473
                                           'groupcompress-block-ref'):
1787
1474
                    if insert_manager is None:
1788
1475
                        raise AssertionError('No insert_manager set')
1789
 
                    if insert_manager is not record._manager:
1790
 
                        raise AssertionError('insert_manager does not match'
1791
 
                            ' the current record, we cannot be positive'
1792
 
                            ' that the appropriate content was inserted.'
1793
 
                            )
1794
1476
                    value = "%d %d %d %d" % (block_start, block_length,
1795
1477
                                             record._start, record._end)
1796
1478
                    nodes = [(record.key, value, (record.parents,))]
1846
1528
                key = record.key
1847
1529
            self._unadded_refs[key] = record.parents
1848
1530
            yield found_sha1
1849
 
            as_st = static_tuple.StaticTuple.from_sequence
1850
 
            if record.parents is not None:
1851
 
                parents = as_st([as_st(p) for p in record.parents])
1852
 
            else:
1853
 
                parents = None
1854
 
            refs = static_tuple.StaticTuple(parents)
1855
 
            keys_to_add.append((key, '%d %d' % (start_point, end_point), refs))
 
1531
            keys_to_add.append((key, '%d %d' % (start_point, end_point),
 
1532
                (record.parents,)))
1856
1533
        if len(keys_to_add):
1857
1534
            flush()
1858
1535
        self._compressor = None
1901
1578
        """See VersionedFiles.keys."""
1902
1579
        if 'evil' in debug.debug_flags:
1903
1580
            trace.mutter_callsite(2, "keys scales with size of history")
1904
 
        sources = [self._index] + self._immediate_fallback_vfs
 
1581
        sources = [self._index] + self._fallback_vfs
1905
1582
        result = set()
1906
1583
        for source in sources:
1907
1584
            result.update(source.keys())
1908
1585
        return result
1909
1586
 
1910
1587
 
1911
 
class _GCBuildDetails(object):
1912
 
    """A blob of data about the build details.
1913
 
 
1914
 
    This stores the minimal data, which then allows compatibility with the old
1915
 
    api, without taking as much memory.
1916
 
    """
1917
 
 
1918
 
    __slots__ = ('_index', '_group_start', '_group_end', '_basis_end',
1919
 
                 '_delta_end', '_parents')
1920
 
 
1921
 
    method = 'group'
1922
 
    compression_parent = None
1923
 
 
1924
 
    def __init__(self, parents, position_info):
1925
 
        self._parents = parents
1926
 
        (self._index, self._group_start, self._group_end, self._basis_end,
1927
 
         self._delta_end) = position_info
1928
 
 
1929
 
    def __repr__(self):
1930
 
        return '%s(%s, %s)' % (self.__class__.__name__,
1931
 
            self.index_memo, self._parents)
1932
 
 
1933
 
    @property
1934
 
    def index_memo(self):
1935
 
        return (self._index, self._group_start, self._group_end,
1936
 
                self._basis_end, self._delta_end)
1937
 
 
1938
 
    @property
1939
 
    def record_details(self):
1940
 
        return static_tuple.StaticTuple(self.method, None)
1941
 
 
1942
 
    def __getitem__(self, offset):
1943
 
        """Compatibility thunk to act like a tuple."""
1944
 
        if offset == 0:
1945
 
            return self.index_memo
1946
 
        elif offset == 1:
1947
 
            return self.compression_parent # Always None
1948
 
        elif offset == 2:
1949
 
            return self._parents
1950
 
        elif offset == 3:
1951
 
            return self.record_details
1952
 
        else:
1953
 
            raise IndexError('offset out of range')
1954
 
            
1955
 
    def __len__(self):
1956
 
        return 4
1957
 
 
1958
 
 
1959
1588
class _GCGraphIndex(object):
1960
1589
    """Mapper from GroupCompressVersionedFiles needs into GraphIndex storage."""
1961
1590
 
1962
1591
    def __init__(self, graph_index, is_locked, parents=True,
1963
1592
        add_callback=None, track_external_parent_refs=False,
1964
 
        inconsistency_fatal=True, track_new_keys=False):
 
1593
        inconsistency_fatal=True):
1965
1594
        """Construct a _GCGraphIndex on a graph_index.
1966
1595
 
1967
1596
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
1986
1615
        self.has_graph = parents
1987
1616
        self._is_locked = is_locked
1988
1617
        self._inconsistency_fatal = inconsistency_fatal
1989
 
        # GroupCompress records tend to have the same 'group' start + offset
1990
 
        # repeated over and over, this creates a surplus of ints
1991
 
        self._int_cache = {}
1992
1618
        if track_external_parent_refs:
1993
 
            self._key_dependencies = _KeyRefs(
1994
 
                track_new_keys=track_new_keys)
 
1619
            self._key_dependencies = knit._KeyRefs()
1995
1620
        else:
1996
1621
            self._key_dependencies = None
1997
1622
 
2030
1655
        if not random_id:
2031
1656
            present_nodes = self._get_entries(keys)
2032
1657
            for (index, key, value, node_refs) in present_nodes:
2033
 
                # Sometimes these are passed as a list rather than a tuple
2034
 
                node_refs = static_tuple.as_tuples(node_refs)
2035
 
                passed = static_tuple.as_tuples(keys[key])
2036
 
                if node_refs != passed[1]:
2037
 
                    details = '%s %s %s' % (key, (value, node_refs), passed)
 
1658
                if node_refs != keys[key][1]:
 
1659
                    details = '%s %s %s' % (key, (value, node_refs), keys[key])
2038
1660
                    if self._inconsistency_fatal:
2039
1661
                        raise errors.KnitCorrupt(self, "inconsistent details"
2040
1662
                                                 " in add_records: %s" %
2054
1676
                    result.append((key, value))
2055
1677
            records = result
2056
1678
        key_dependencies = self._key_dependencies
2057
 
        if key_dependencies is not None:
2058
 
            if self._parents:
2059
 
                for key, value, refs in records:
2060
 
                    parents = refs[0]
2061
 
                    key_dependencies.add_references(key, parents)
2062
 
            else:
2063
 
                for key, value, refs in records:
2064
 
                    new_keys.add_key(key)
 
1679
        if key_dependencies is not None and self._parents:
 
1680
            for key, value, refs in records:
 
1681
                parents = refs[0]
 
1682
                key_dependencies.add_references(key, parents)
2065
1683
        self._add_callback(records)
2066
1684
 
2067
1685
    def _check_read(self):
2098
1716
            if missing_keys:
2099
1717
                raise errors.RevisionNotPresent(missing_keys.pop(), self)
2100
1718
 
2101
 
    def find_ancestry(self, keys):
2102
 
        """See CombinedGraphIndex.find_ancestry"""
2103
 
        return self._graph_index.find_ancestry(keys, 0)
2104
 
 
2105
1719
    def get_parent_map(self, keys):
2106
1720
        """Get a map of the parents of keys.
2107
1721
 
2124
1738
        """Return the keys of missing parents."""
2125
1739
        # Copied from _KnitGraphIndex.get_missing_parents
2126
1740
        # We may have false positives, so filter those out.
2127
 
        self._key_dependencies.satisfy_refs_for_keys(
 
1741
        self._key_dependencies.add_keys(
2128
1742
            self.get_parent_map(self._key_dependencies.get_unsatisfied_refs()))
2129
1743
        return frozenset(self._key_dependencies.get_unsatisfied_refs())
2130
1744
 
2136
1750
        :param keys: An iterable of keys.
2137
1751
        :return: A dict of key:
2138
1752
            (index_memo, compression_parent, parents, record_details).
2139
 
 
2140
 
            * index_memo: opaque structure to pass to read_records to extract
2141
 
              the raw data
2142
 
            * compression_parent: Content that this record is built upon, may
2143
 
              be None
2144
 
            * parents: Logical parents of this node
2145
 
            * record_details: extra information about the content which needs
2146
 
              to be passed to Factory.parse_record
 
1753
            index_memo
 
1754
                opaque structure to pass to read_records to extract the raw
 
1755
                data
 
1756
            compression_parent
 
1757
                Content that this record is built upon, may be None
 
1758
            parents
 
1759
                Logical parents of this node
 
1760
            record_details
 
1761
                extra information about the content which needs to be passed to
 
1762
                Factory.parse_record
2147
1763
        """
2148
1764
        self._check_read()
2149
1765
        result = {}
2154
1770
                parents = None
2155
1771
            else:
2156
1772
                parents = entry[3][0]
2157
 
            details = _GCBuildDetails(parents, self._node_to_position(entry))
2158
 
            result[key] = details
 
1773
            method = 'group'
 
1774
            result[key] = (self._node_to_position(entry),
 
1775
                                  None, parents, (method, None))
2159
1776
        return result
2160
1777
 
2161
1778
    def keys(self):
2170
1787
        """Convert an index value to position details."""
2171
1788
        bits = node[2].split(' ')
2172
1789
        # It would be nice not to read the entire gzip.
2173
 
        # start and stop are put into _int_cache because they are very common.
2174
 
        # They define the 'group' that an entry is in, and many groups can have
2175
 
        # thousands of objects.
2176
 
        # Branching Launchpad, for example, saves ~600k integers, at 12 bytes
2177
 
        # each, or about 7MB. Note that it might be even more when you consider
2178
 
        # how PyInt is allocated in separate slabs. And you can't return a slab
2179
 
        # to the OS if even 1 int on it is in use. Note though that Python uses
2180
 
        # a LIFO when re-using PyInt slots, which might cause more
2181
 
        # fragmentation.
2182
1790
        start = int(bits[0])
2183
 
        start = self._int_cache.setdefault(start, start)
2184
1791
        stop = int(bits[1])
2185
 
        stop = self._int_cache.setdefault(stop, stop)
2186
1792
        basis_end = int(bits[2])
2187
1793
        delta_end = int(bits[3])
2188
 
        # We can't use StaticTuple here, because node[0] is a BTreeGraphIndex
2189
 
        # instance...
2190
 
        return (node[0], start, stop, basis_end, delta_end)
 
1794
        return node[0], start, stop, basis_end, delta_end
2191
1795
 
2192
1796
    def scan_unvalidated_index(self, graph_index):
2193
1797
        """Inform this _GCGraphIndex that there is an unvalidated index.
2194
1798
 
2195
1799
        This allows this _GCGraphIndex to keep track of any missing
2196
1800
        compression parents we may want to have filled in to make those
2197
 
        indices valid.  It also allows _GCGraphIndex to track any new keys.
 
1801
        indices valid.
2198
1802
 
2199
1803
        :param graph_index: A GraphIndex
2200
1804
        """
2201
 
        key_dependencies = self._key_dependencies
2202
 
        if key_dependencies is None:
2203
 
            return
2204
 
        for node in graph_index.iter_all_entries():
2205
 
            # Add parent refs from graph_index (and discard parent refs
2206
 
            # that the graph_index has).
2207
 
            key_dependencies.add_references(node[1], node[3][0])
 
1805
        if self._key_dependencies is not None:
 
1806
            # Add parent refs from graph_index (and discard parent refs that
 
1807
            # the graph_index has).
 
1808
            add_refs = self._key_dependencies.add_references
 
1809
            for node in graph_index.iter_all_entries():
 
1810
                add_refs(node[1], node[3][0])
 
1811
 
2208
1812
 
2209
1813
 
2210
1814
from bzrlib._groupcompress_py import (
2224
1828
        decode_base128_int,
2225
1829
        )
2226
1830
    GroupCompressor = PyrexGroupCompressor
2227
 
except ImportError, e:
2228
 
    osutils.failed_to_load_extension(e)
 
1831
except ImportError:
2229
1832
    GroupCompressor = PythonGroupCompressor
2230
1833