~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/groupcompress.py

  • Committer: Ian Clatworthy
  • Date: 2010-05-26 04:26:59 UTC
  • mto: (5255.2.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5256.
  • Revision ID: ian.clatworthy@canonical.com-20100526042659-2e3p4qdjr0sby0bt
Fix PDF generation of User Reference

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2008, 2009, 2010 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
21
19
import time
22
20
import zlib
23
21
try:
28
26
from bzrlib import (
29
27
    annotate,
30
28
    debug,
31
 
    diff,
32
29
    errors,
33
30
    graph as _mod_graph,
 
31
    knit,
34
32
    osutils,
35
33
    pack,
36
 
    patiencediff,
 
34
    static_tuple,
37
35
    trace,
38
36
    )
39
 
from bzrlib.graph import Graph
40
 
from bzrlib.knit import _DirectPackAccess
41
37
from bzrlib.btree_index import BTreeBuilder
42
38
from bzrlib.lru_cache import LRUSizeCache
43
39
from bzrlib.tsort import topo_sort
49
45
    VersionedFiles,
50
46
    )
51
47
 
 
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
 
 
58
57
def sort_gc_optimal(parent_map):
59
58
    """Sort and group the keys in parent_map into groupcompress order.
60
59
 
66
65
    # groupcompress ordering is approximately reverse topological,
67
66
    # properly grouped by file-id.
68
67
    per_prefix_map = {}
69
 
    for item in parent_map.iteritems():
70
 
        key = item[0]
 
68
    for key, value in parent_map.iteritems():
71
69
        if isinstance(key, str) or len(key) == 1:
72
70
            prefix = ''
73
71
        else:
74
72
            prefix = key[0]
75
73
        try:
76
 
            per_prefix_map[prefix].append(item)
 
74
            per_prefix_map[prefix][key] = value
77
75
        except KeyError:
78
 
            per_prefix_map[prefix] = [item]
 
76
            per_prefix_map[prefix] = {key: value}
79
77
 
80
78
    present_keys = []
81
79
    for prefix in sorted(per_prefix_map):
96
94
 
97
95
    # Group Compress Block v1 Zlib
98
96
    GCB_HEADER = 'gcb1z\n'
 
97
    # Group Compress Block v1 Lzma
99
98
    GCB_LZ_HEADER = 'gcb1l\n'
 
99
    GCB_KNOWN_HEADERS = (GCB_HEADER, GCB_LZ_HEADER)
100
100
 
101
101
    def __init__(self):
102
102
        # map by key? or just order in file?
106
106
        self._z_content_length = None
107
107
        self._content_length = None
108
108
        self._content = None
 
109
        self._content_chunks = None
109
110
 
110
111
    def __len__(self):
111
112
        # This is the maximum number of bytes this object will reference if
119
120
        :param num_bytes: Ensure that we have extracted at least num_bytes of
120
121
            content. If None, consume everything
121
122
        """
122
 
        # TODO: If we re-use the same content block at different times during
123
 
        #       get_record_stream(), it is possible that the first pass will
124
 
        #       get inserted, triggering an extract/_ensure_content() which
125
 
        #       will get rid of _z_content. And then the next use of the block
126
 
        #       will try to access _z_content (to send it over the wire), and
127
 
        #       fail because it is already extracted. Consider never releasing
128
 
        #       _z_content because of this.
 
123
        if self._content_length is None:
 
124
            raise AssertionError('self._content_length should never be None')
129
125
        if num_bytes is None:
130
126
            num_bytes = self._content_length
131
 
        if self._content_length is not None:
132
 
            assert num_bytes <= self._content_length
133
 
        if self._content is None:
134
 
            assert self._z_content is not None
 
127
        elif (self._content_length is not None
 
128
              and num_bytes > self._content_length):
 
129
            raise AssertionError(
 
130
                'requested num_bytes (%d) > content length (%d)'
 
131
                % (num_bytes, self._content_length))
 
132
        # Expand the content if required
 
133
        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
            if self._z_content is None:
 
139
                raise AssertionError('No content to decompress')
135
140
            if self._z_content == '':
136
141
                self._content = ''
137
142
            elif self._compressor_name == 'lzma':
138
143
                # We don't do partial lzma decomp yet
139
144
                self._content = pylzma.decompress(self._z_content)
140
 
            else:
 
145
            elif self._compressor_name == 'zlib':
141
146
                # Start a zlib decompressor
142
 
                assert self._compressor_name == 'zlib'
143
 
                if num_bytes is None:
 
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
144
151
                    self._content = zlib.decompress(self._z_content)
145
152
                else:
146
153
                    self._z_content_decompressor = zlib.decompressobj()
148
155
                    # that the rest of the code is simplified
149
156
                    self._content = self._z_content_decompressor.decompress(
150
157
                        self._z_content, num_bytes + _ZLIB_DECOMP_WINDOW)
151
 
                # Any bytes remaining to be decompressed will be in the
152
 
                # decompressors 'unconsumed_tail'
 
158
                    if not self._z_content_decompressor.unconsumed_tail:
 
159
                        self._z_content_decompressor = None
 
160
            else:
 
161
                raise AssertionError('Unknown compressor: %r'
 
162
                                     % self._compressor_name)
 
163
        # Any bytes remaining to be decompressed will be in the decompressors
 
164
        # 'unconsumed_tail'
 
165
 
153
166
        # Do we have enough bytes already?
154
 
        if num_bytes is not None and len(self._content) >= num_bytes:
155
 
            return
156
 
        if num_bytes is None and self._z_content_decompressor is None:
157
 
            # We must have already decompressed everything
 
167
        if len(self._content) >= num_bytes:
158
168
            return
159
169
        # If we got this far, and don't have a decompressor, something is wrong
160
 
        assert self._z_content_decompressor is not None
 
170
        if self._z_content_decompressor is None:
 
171
            raise AssertionError(
 
172
                'No decompressor to decompress %d bytes' % num_bytes)
161
173
        remaining_decomp = self._z_content_decompressor.unconsumed_tail
162
 
        if num_bytes is None:
163
 
            if remaining_decomp:
164
 
                # We don't know how much is left, but we'll decompress it all
165
 
                self._content += self._z_content_decompressor.decompress(
166
 
                    remaining_decomp)
167
 
                # Note: There what I consider a bug in zlib.decompressobj
168
 
                #       If you pass back in the entire unconsumed_tail, only
169
 
                #       this time you don't pass a max-size, it doesn't
170
 
                #       change the unconsumed_tail back to None/''.
171
 
                #       However, we know we are done with the whole stream
172
 
                self._z_content_decompressor = None
173
 
            self._content_length = len(self._content)
174
 
        else:
175
 
            # If we have nothing left to decomp, we ran out of decomp bytes
176
 
            assert remaining_decomp
177
 
            needed_bytes = num_bytes - len(self._content)
178
 
            # We always set max_size to 32kB over the minimum needed, so that
179
 
            # zlib will give us as much as we really want.
180
 
            # TODO: If this isn't good enough, we could make a loop here,
181
 
            #       that keeps expanding the request until we get enough
182
 
            self._content += self._z_content_decompressor.decompress(
183
 
                remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
184
 
            assert len(self._content) >= num_bytes
185
 
            if not self._z_content_decompressor.unconsumed_tail:
186
 
                # The stream is finished
187
 
                self._z_content_decompressor = None
 
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
188
189
 
189
190
    def _parse_bytes(self, bytes, pos):
190
191
        """Read the various lengths from the header.
202
203
        pos2 = bytes.index('\n', pos, pos + 14)
203
204
        self._content_length = int(bytes[pos:pos2])
204
205
        pos = pos2 + 1
205
 
        assert len(bytes) == (pos + self._z_content_length)
 
206
        if len(bytes) != (pos + self._z_content_length):
 
207
            # XXX: Define some GCCorrupt error ?
 
208
            raise AssertionError('Invalid bytes: (%d) != %d + %d' %
 
209
                                 (len(bytes), pos, self._z_content_length))
206
210
        self._z_content = bytes[pos:]
207
 
        assert len(self._z_content) == self._z_content_length
208
211
 
209
212
    @classmethod
210
213
    def from_bytes(cls, bytes):
211
214
        out = cls()
212
 
        if bytes[:6] not in (cls.GCB_HEADER, cls.GCB_LZ_HEADER):
213
 
            raise ValueError('bytes did not start with %r' % (cls.GCB_HEADER,))
 
215
        if bytes[:6] not in cls.GCB_KNOWN_HEADERS:
 
216
            raise ValueError('bytes did not start with any of %r'
 
217
                             % (cls.GCB_KNOWN_HEADERS,))
 
218
        # XXX: why not testing the whole header ?
214
219
        if bytes[4] == 'z':
215
220
            out._compressor_name = 'zlib'
216
221
        elif bytes[4] == 'l':
254
259
            bytes = apply_delta_to_source(self._content, content_start, end)
255
260
        return bytes
256
261
 
 
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
 
257
274
    def set_content(self, content):
258
275
        """Set the content of this block."""
259
276
        self._content_length = len(content)
260
277
        self._content = content
261
278
        self._z_content = None
262
279
 
 
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
 
263
308
    def to_bytes(self):
264
309
        """Encode the information into a byte stream."""
265
 
        compress = zlib.compress
266
 
        if _USE_LZMA:
267
 
            compress = pylzma.compress
268
 
        if self._z_content is None:
269
 
            assert self._content is not None
270
 
            self._z_content = compress(self._content)
271
 
            self._z_content_length = len(self._z_content)
 
310
        self._create_z_content()
272
311
        if _USE_LZMA:
273
312
            header = self.GCB_LZ_HEADER
274
313
        else:
279
318
                 ]
280
319
        return ''.join(chunks)
281
320
 
 
321
    def _dump(self, include_text=False):
 
322
        """Take this block, and spit out a human-readable structure.
 
323
 
 
324
        :param include_text: Inserts also include text bits, chose whether you
 
325
            want this displayed in the dump or not.
 
326
        :return: A dump of the given block. The layout is something like:
 
327
            [('f', length), ('d', delta_length, text_length, [delta_info])]
 
328
            delta_info := [('i', num_bytes, text), ('c', offset, num_bytes),
 
329
            ...]
 
330
        """
 
331
        self._ensure_content()
 
332
        result = []
 
333
        pos = 0
 
334
        while pos < self._content_length:
 
335
            kind = self._content[pos]
 
336
            pos += 1
 
337
            if kind not in ('f', 'd'):
 
338
                raise ValueError('invalid kind character: %r' % (kind,))
 
339
            content_len, len_len = decode_base128_int(
 
340
                                self._content[pos:pos + 5])
 
341
            pos += len_len
 
342
            if content_len + pos > self._content_length:
 
343
                raise ValueError('invalid content_len %d for record @ pos %d'
 
344
                                 % (content_len, pos - len_len - 1))
 
345
            if kind == 'f': # Fulltext
 
346
                if include_text:
 
347
                    text = self._content[pos:pos+content_len]
 
348
                    result.append(('f', content_len, text))
 
349
                else:
 
350
                    result.append(('f', content_len))
 
351
            elif kind == 'd': # Delta
 
352
                delta_content = self._content[pos:pos+content_len]
 
353
                delta_info = []
 
354
                # The first entry in a delta is the decompressed length
 
355
                decomp_len, delta_pos = decode_base128_int(delta_content)
 
356
                result.append(('d', content_len, decomp_len, delta_info))
 
357
                measured_len = 0
 
358
                while delta_pos < content_len:
 
359
                    c = ord(delta_content[delta_pos])
 
360
                    delta_pos += 1
 
361
                    if c & 0x80: # Copy
 
362
                        (offset, length,
 
363
                         delta_pos) = decode_copy_instruction(delta_content, c,
 
364
                                                              delta_pos)
 
365
                        if include_text:
 
366
                            text = self._content[offset:offset+length]
 
367
                            delta_info.append(('c', offset, length, text))
 
368
                        else:
 
369
                            delta_info.append(('c', offset, length))
 
370
                        measured_len += length
 
371
                    else: # Insert
 
372
                        if include_text:
 
373
                            txt = delta_content[delta_pos:delta_pos+c]
 
374
                        else:
 
375
                            txt = ''
 
376
                        delta_info.append(('i', c, txt))
 
377
                        measured_len += c
 
378
                        delta_pos += c
 
379
                if delta_pos != content_len:
 
380
                    raise ValueError('Delta consumed a bad number of bytes:'
 
381
                                     ' %d != %d' % (delta_pos, content_len))
 
382
                if measured_len != decomp_len:
 
383
                    raise ValueError('Delta claimed fulltext was %d bytes, but'
 
384
                                     ' extraction resulted in %d bytes'
 
385
                                     % (decomp_len, measured_len))
 
386
            pos += content_len
 
387
        return result
 
388
 
282
389
 
283
390
class _LazyGroupCompressFactory(object):
284
391
    """Yield content from a GroupCompressBlock on demand."""
331
438
                self._manager._prepare_for_extract()
332
439
                block = self._manager._block
333
440
                self._bytes = block.extract(self.key, self._start, self._end)
334
 
                # XXX: It seems the smart fetch extracts inventories and chk
335
 
                #      pages as fulltexts to find the next chk pages, but then
336
 
                #      passes them down to be inserted as a
337
 
                #      groupcompress-block, so this is not safe to do. Perhaps
338
 
                #      we could just change the storage kind to "fulltext" at
339
 
                #      that point?
340
 
                # self._manager = None
 
441
                # There are code paths that first extract as fulltext, and then
 
442
                # extract as storage_kind (smart fetch). So we don't break the
 
443
                # refcycle here, but instead in manager.get_record_stream()
341
444
            if storage_kind == 'fulltext':
342
445
                return self._bytes
343
446
            else:
349
452
class _LazyGroupContentManager(object):
350
453
    """This manages a group of _LazyGroupCompressFactory objects."""
351
454
 
 
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
 
352
463
    def __init__(self, block):
353
464
        self._block = block
354
465
        # We need to preserve the ordering
376
487
            yield factory
377
488
            # Break the ref-cycle
378
489
            factory._bytes = None
379
 
            # XXX: this is not safe, the smart fetch code requests the content
380
 
            #      as both a 'fulltext', and then later on as a
381
 
            #      groupcompress-block. The iter_interesting_nodes code also is
382
 
            #      still buffering multiple records and returning them later.
383
 
            #      So that code would need to be updated to either re-fetch the
384
 
            #      original object, or buffer it somehow.
385
 
            # factory._manager = None
 
490
            factory._manager = None
386
491
        # TODO: Consider setting self._factories = None after the above loop,
387
492
        #       as it will break the reference cycle
388
493
 
406
511
        end_point = 0
407
512
        for factory in self._factories:
408
513
            bytes = factory.get_bytes_as('fulltext')
409
 
            (found_sha1, start_point, end_point, type,
410
 
             length) = compressor.compress(factory.key, bytes, factory.sha1)
 
514
            (found_sha1, start_point, end_point,
 
515
             type) = compressor.compress(factory.key, bytes, factory.sha1)
411
516
            # Now update this factory with the new offsets, etc
412
517
            factory.sha1 = found_sha1
413
518
            factory._start = start_point
432
537
        # time (self._block._content) is a little expensive.
433
538
        self._block._ensure_content(self._last_byte)
434
539
 
435
 
    def _check_rebuild_block(self):
 
540
    def _check_rebuild_action(self):
436
541
        """Check to see if our block should be repacked."""
437
542
        total_bytes_used = 0
438
543
        last_byte_used = 0
439
544
        for factory in self._factories:
440
545
            total_bytes_used += factory._end - factory._start
441
 
            last_byte_used = max(last_byte_used, factory._end)
442
 
        # If we are using most of the bytes from the block, we have nothing
443
 
        # else to check (currently more that 1/2)
 
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
444
550
        if total_bytes_used * 2 >= self._block._content_length:
445
 
            return
446
 
        # Can we just strip off the trailing bytes? If we are going to be
447
 
        # transmitting more than 50% of the front of the content, go ahead
 
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.
448
555
        if total_bytes_used * 2 > last_byte_used:
449
 
            self._trim_block(last_byte_used)
450
 
            return
 
556
            return 'trim', last_byte_used, total_bytes_used
451
557
 
452
558
        # We are using a small amount of the data, and it isn't just packed
453
559
        # nicely at the front, so rebuild the content.
460
566
        #       expanding many deltas into fulltexts, as well.
461
567
        #       If we build a cheap enough 'strip', then we could try a strip,
462
568
        #       if that expands the content, we then rebuild.
463
 
        self._rebuild_block()
 
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,))
464
643
 
465
644
    def _wire_bytes(self):
466
645
        """Return a byte stream suitable for transmitting over the wire."""
492
671
            record_header = '%s\n%s\n%d\n%d\n' % (
493
672
                key_bytes, parent_bytes, factory._start, factory._end)
494
673
            header_lines.append(record_header)
 
674
            # TODO: Can we break the refcycle at this point and set
 
675
            #       factory._manager = None?
495
676
        header_bytes = ''.join(header_lines)
496
677
        del header_lines
497
678
        header_bytes_len = len(header_bytes)
593
774
        :param soft: Do a 'soft' compression. This means that we require larger
594
775
            ranges to match to be considered for a copy command.
595
776
 
596
 
        :return: The sha1 of lines, the start and end offsets in the delta, the
597
 
            type ('fulltext' or 'delta') and the number of bytes accumulated in
598
 
            the group output so far.
 
777
        :return: The sha1 of lines, the start and end offsets in the delta, and
 
778
            the type ('fulltext' or 'delta').
599
779
 
600
780
        :seealso VersionedFiles.add_lines:
601
781
        """
602
782
        if not bytes: # empty, like a dir entry, etc
603
783
            if nostore_sha == _null_sha1:
604
784
                raise errors.ExistingContent()
605
 
            return _null_sha1, 0, 0, 'fulltext', 0
 
785
            return _null_sha1, 0, 0, 'fulltext'
606
786
        # we assume someone knew what they were doing when they passed it in
607
787
        if expected_sha is not None:
608
788
            sha1 = expected_sha
614
794
        if key[-1] is None:
615
795
            key = key[:-1] + ('sha1:' + sha1,)
616
796
 
617
 
        return self._compress(key, bytes, sha1, len(bytes) / 2, soft)
 
797
        start, end, type = self._compress(key, bytes, len(bytes) / 2, soft)
 
798
        return sha1, start, end, type
618
799
 
619
 
    def _compress(self, key, bytes, sha1, max_delta_size, soft=False):
 
800
    def _compress(self, key, bytes, max_delta_size, soft=False):
620
801
        """Compress lines with label key.
621
802
 
622
803
        :param key: A key tuple. It is stored in the output for identification
624
805
 
625
806
        :param bytes: The bytes to be compressed
626
807
 
627
 
        :param sha1: The sha1 for 'bytes'.
628
 
 
629
808
        :param max_delta_size: The size above which we issue a fulltext instead
630
809
            of a delta.
631
810
 
632
811
        :param soft: Do a 'soft' compression. This means that we require larger
633
812
            ranges to match to be considered for a copy command.
634
813
 
635
 
        :return: The sha1 of lines, the start and end offsets in the delta, the
636
 
            type ('fulltext' or 'delta') and the number of bytes accumulated in
637
 
            the group output so far.
 
814
        :return: The sha1 of lines, the start and end offsets in the delta, and
 
815
            the type ('fulltext' or 'delta').
638
816
        """
639
817
        raise NotImplementedError(self._compress)
640
818
 
676
854
 
677
855
        After calling this, the compressor should no longer be used
678
856
        """
679
 
        content = ''.join(self.chunks)
 
857
        # TODO: this causes us to 'bloat' to 2x the size of content in the
 
858
        #       group. This has an impact for 'commit' of large objects.
 
859
        #       One possibility is to use self._content_chunks, and be lazy and
 
860
        #       only fill out self._content as a full string when we actually
 
861
        #       need it. That would at least drop the peak memory consumption
 
862
        #       for 'commit' down to ~1x the size of the largest file, at a
 
863
        #       cost of increased complexity within this code. 2x is still <<
 
864
        #       3x the size of the largest file, so we are doing ok.
 
865
        self._block.set_chunked_content(self.chunks, self.endpoint)
680
866
        self.chunks = None
681
867
        self._delta_index = None
682
 
        self._block.set_content(content)
683
868
        return self._block
684
869
 
685
870
    def pop_last(self):
703
888
    def __init__(self):
704
889
        """Create a GroupCompressor.
705
890
 
706
 
        :param delta: If False, do not compress records.
 
891
        Used only if the pyrex version is not available.
707
892
        """
708
893
        super(PythonGroupCompressor, self).__init__()
709
894
        self._delta_index = LinesDeltaIndex([])
710
895
        # The actual content is managed by LinesDeltaIndex
711
896
        self.chunks = self._delta_index.lines
712
897
 
713
 
    def _compress(self, key, bytes, sha1, max_delta_size, soft=False):
 
898
    def _compress(self, key, bytes, max_delta_size, soft=False):
714
899
        """see _CommonGroupCompressor._compress"""
715
 
        bytes_length = len(bytes)
 
900
        input_len = len(bytes)
716
901
        new_lines = osutils.split_lines(bytes)
717
 
        out_lines, index_lines = self._delta_index.make_delta(new_lines,
718
 
            bytes_length=bytes_length, soft=soft)
 
902
        out_lines, index_lines = self._delta_index.make_delta(
 
903
            new_lines, bytes_length=input_len, soft=soft)
719
904
        delta_length = sum(map(len, out_lines))
720
905
        if delta_length > max_delta_size:
721
906
            # The delta is longer than the fulltext, insert a fulltext
722
907
            type = 'fulltext'
723
 
            out_lines = ['f', encode_base128_int(bytes_length)]
 
908
            out_lines = ['f', encode_base128_int(input_len)]
724
909
            out_lines.extend(new_lines)
725
910
            index_lines = [False, False]
726
911
            index_lines.extend([True] * len(new_lines))
727
 
            out_length = len(out_lines[1]) + bytes_length + 1
728
912
        else:
729
913
            # this is a worthy delta, output it
730
914
            type = 'delta'
731
915
            out_lines[0] = 'd'
732
916
            # Update the delta_length to include those two encoded integers
733
917
            out_lines[1] = encode_base128_int(delta_length)
734
 
            out_length = len(out_lines[3]) + 1 + delta_length
735
 
        start = self.endpoint # Before insertion
736
 
        chunk_start = len(self._delta_index.lines)
 
918
        # Before insertion
 
919
        start = self.endpoint
 
920
        chunk_start = len(self.chunks)
 
921
        self._last = (chunk_start, self.endpoint)
737
922
        self._delta_index.extend_lines(out_lines, index_lines)
738
923
        self.endpoint = self._delta_index.endpoint
739
 
        self.input_bytes += bytes_length
740
 
        chunk_end = len(self._delta_index.lines)
 
924
        self.input_bytes += input_len
 
925
        chunk_end = len(self.chunks)
741
926
        self.labels_deltas[key] = (start, chunk_start,
742
927
                                   self.endpoint, chunk_end)
743
 
        return sha1, start, self.endpoint, type, out_length
 
928
        return start, self.endpoint, type
744
929
 
745
930
 
746
931
class PyrexGroupCompressor(_CommonGroupCompressor):
763
948
        super(PyrexGroupCompressor, self).__init__()
764
949
        self._delta_index = DeltaIndex()
765
950
 
766
 
    def _compress(self, key, bytes, sha1, max_delta_size, soft=False):
 
951
    def _compress(self, key, bytes, max_delta_size, soft=False):
767
952
        """see _CommonGroupCompressor._compress"""
768
953
        input_len = len(bytes)
769
954
        # By having action/label/sha1/len, we can parse the group if the index
784
969
            type = 'fulltext'
785
970
            enc_length = encode_base128_int(len(bytes))
786
971
            len_mini_header = 1 + len(enc_length)
787
 
            length = len(bytes) + len_mini_header
788
972
            self._delta_index.add_source(bytes, len_mini_header)
789
973
            new_chunks = ['f', enc_length, bytes]
790
974
        else:
791
975
            type = 'delta'
792
976
            enc_length = encode_base128_int(len(delta))
793
977
            len_mini_header = 1 + len(enc_length)
794
 
            length = len(delta) + len_mini_header
795
978
            new_chunks = ['d', enc_length, delta]
796
979
            self._delta_index.add_delta_source(delta, len_mini_header)
797
980
        # Before insertion
807
990
            raise AssertionError('the delta index is out of sync'
808
991
                'with the output lines %s != %s'
809
992
                % (self._delta_index._source_offset, self.endpoint))
810
 
        return sha1, start, self.endpoint, type, length
 
993
        return start, self.endpoint, type
811
994
 
812
995
    def _output_chunks(self, new_chunks):
813
996
        """Output some chunks.
821
1004
        self.endpoint = endpoint
822
1005
 
823
1006
 
824
 
def make_pack_factory(graph, delta, keylength):
 
1007
def make_pack_factory(graph, delta, keylength, inconsistency_fatal=True):
825
1008
    """Create a factory for creating a pack based groupcompress.
826
1009
 
827
1010
    This is only functional enough to run interface tests, it doesn't try to
842
1025
        writer = pack.ContainerWriter(stream.write)
843
1026
        writer.begin()
844
1027
        index = _GCGraphIndex(graph_index, lambda:True, parents=parents,
845
 
            add_callback=graph_index.add_nodes)
846
 
        access = _DirectPackAccess({})
 
1028
            add_callback=graph_index.add_nodes,
 
1029
            inconsistency_fatal=inconsistency_fatal)
 
1030
        access = knit._DirectPackAccess({})
847
1031
        access.set_writer(writer, graph_index, (transport, 'newpack'))
848
1032
        result = GroupCompressVersionedFiles(index, access, delta)
849
1033
        result.stream = stream
857
1041
    versioned_files.stream.close()
858
1042
 
859
1043
 
 
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
 
860
1152
class GroupCompressVersionedFiles(VersionedFiles):
861
1153
    """A group-compress based VersionedFiles implementation."""
862
1154
 
863
 
    def __init__(self, index, access, delta=True):
 
1155
    def __init__(self, index, access, delta=True, _unadded_refs=None):
864
1156
        """Create a GroupCompressVersionedFiles object.
865
1157
 
866
1158
        :param index: The index object storing access and graph data.
867
1159
        :param access: The access object storing raw data.
868
1160
        :param delta: Whether to delta compress or just entropy compress.
 
1161
        :param _unadded_refs: private parameter, don't use.
869
1162
        """
870
1163
        self._index = index
871
1164
        self._access = access
872
1165
        self._delta = delta
873
 
        self._unadded_refs = {}
 
1166
        if _unadded_refs is None:
 
1167
            _unadded_refs = {}
 
1168
        self._unadded_refs = _unadded_refs
874
1169
        self._group_cache = LRUSizeCache(max_size=50*1024*1024)
875
1170
        self._fallback_vfs = []
876
1171
 
 
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
 
877
1177
    def add_lines(self, key, parents, lines, parent_texts=None,
878
1178
        left_matching_blocks=None, nostore_sha=None, random_id=False,
879
1179
        check_content=True):
924
1224
                                               nostore_sha=nostore_sha))[0]
925
1225
        return sha1, length, None
926
1226
 
 
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
 
927
1245
    def add_fallback_versioned_files(self, a_versioned_files):
928
1246
        """Add a source of texts for texts not present in this knit.
929
1247
 
933
1251
 
934
1252
    def annotate(self, key):
935
1253
        """See VersionedFiles.annotate."""
936
 
        graph = Graph(self)
937
 
        parent_map = self.get_parent_map([key])
938
 
        if not parent_map:
939
 
            raise errors.RevisionNotPresent(key, self)
940
 
        if parent_map[key] is not None:
941
 
            search = graph._make_breadth_first_searcher([key])
942
 
            keys = set()
943
 
            while True:
944
 
                try:
945
 
                    present, ghosts = search.next_with_ghosts()
946
 
                except StopIteration:
947
 
                    break
948
 
                keys.update(present)
949
 
            parent_map = self.get_parent_map(keys)
950
 
        else:
951
 
            keys = [key]
952
 
            parent_map = {key:()}
953
 
        head_cache = _mod_graph.FrozenHeadsCache(graph)
954
 
        parent_cache = {}
955
 
        reannotate = annotate.reannotate
956
 
        for record in self.get_record_stream(keys, 'topological', True):
957
 
            key = record.key
958
 
            chunks = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
959
 
            parent_lines = [parent_cache[parent] for parent in parent_map[key]]
960
 
            parent_cache[key] = list(
961
 
                reannotate(parent_lines, chunks, key, None, head_cache))
962
 
        return parent_cache[key]
963
 
 
964
 
    def check(self, progress_bar=None):
 
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):
965
1261
        """See VersionedFiles.check()."""
966
 
        keys = self.keys()
967
 
        for record in self.get_record_stream(keys, 'unordered', True):
968
 
            record.get_bytes_as('fulltext')
 
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()
969
1274
 
970
1275
    def _check_add(self, key, lines, random_id, check_content):
971
1276
        """check that version_id and lines are safe to add."""
982
1287
            self._check_lines_not_unicode(lines)
983
1288
            self._check_lines_are_lines(lines)
984
1289
 
 
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
 
985
1306
    def get_parent_map(self, keys):
986
1307
        """Get a map of the graph parents of keys.
987
1308
 
1014
1335
            missing.difference_update(set(new_result))
1015
1336
        return result, source_results
1016
1337
 
1017
 
    def _get_block(self, index_memo):
1018
 
        read_memo = index_memo[0:3]
1019
 
        # get the group:
1020
 
        try:
1021
 
            block = self._group_cache[read_memo]
1022
 
        except KeyError:
1023
 
            # read the group
1024
 
            zdata = self._access.get_raw_records([read_memo]).next()
1025
 
            # decompress - whole thing - this is not a bug, as it
1026
 
            # permits caching. We might want to store the partially
1027
 
            # decompresed group and decompress object, so that recent
1028
 
            # texts are not penalised by big groups.
1029
 
            block = GroupCompressBlock.from_bytes(zdata)
1030
 
            self._group_cache[read_memo] = block
1031
 
        # cheapo debugging:
1032
 
        # print len(zdata), len(plain)
1033
 
        # parse - requires split_lines, better to have byte offsets
1034
 
        # here (but not by much - we only split the region for the
1035
 
        # recipe, and we often want to end up with lines anyway.
1036
 
        return block
 
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
1037
1374
 
1038
1375
    def get_missing_compression_parent_keys(self):
1039
1376
        """Return the keys of missing compression parents.
1205
1542
                unadded_keys, source_result)
1206
1543
        for key in missing:
1207
1544
            yield AbsentContentFactory(key)
1208
 
        manager = None
1209
 
        last_read_memo = None
1210
 
        # TODO: This works fairly well at batching up existing groups into a
1211
 
        #       streamable format, and possibly allowing for taking one big
1212
 
        #       group and splitting it when it isn't fully utilized.
1213
 
        #       However, it doesn't allow us to find under-utilized groups and
1214
 
        #       combine them into a bigger group on the fly.
1215
 
        #       (Consider the issue with how chk_map inserts texts
1216
 
        #       one-at-a-time.) This could be done at insert_record_stream()
1217
 
        #       time, but it probably would decrease the number of
1218
 
        #       bytes-on-the-wire for fetch.
 
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)
1219
1550
        for source, keys in source_keys:
1220
1551
            if source is self:
1221
1552
                for key in keys:
1222
1553
                    if key in self._unadded_refs:
1223
 
                        if manager is not None:
1224
 
                            for factory in manager.get_record_stream():
1225
 
                                yield factory
1226
 
                            last_read_memo = manager = None
 
1554
                        # Flush batch, then yield unadded ref from
 
1555
                        # self._compressor.
 
1556
                        for factory in batcher.yield_factories(full_flush=True):
 
1557
                            yield factory
1227
1558
                        bytes, sha1 = self._compressor.extract(key)
1228
1559
                        parents = self._unadded_refs[key]
1229
1560
                        yield FulltextContentFactory(key, parents, sha1, bytes)
1230
 
                    else:
1231
 
                        index_memo, _, parents, (method, _) = locations[key]
1232
 
                        read_memo = index_memo[0:3]
1233
 
                        if last_read_memo != read_memo:
1234
 
                            # We are starting a new block. If we have a
1235
 
                            # manager, we have found everything that fits for
1236
 
                            # now, so yield records
1237
 
                            if manager is not None:
1238
 
                                for factory in manager.get_record_stream():
1239
 
                                    yield factory
1240
 
                            # Now start a new manager
1241
 
                            block = self._get_block(index_memo)
1242
 
                            manager = _LazyGroupContentManager(block)
1243
 
                            last_read_memo = read_memo
1244
 
                        start, end = index_memo[3:5]
1245
 
                        manager.add_factory(key, parents, start, end)
 
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
1246
1566
            else:
1247
 
                if manager is not None:
1248
 
                    for factory in manager.get_record_stream():
1249
 
                        yield factory
1250
 
                    last_read_memo = manager = None
 
1567
                for factory in batcher.yield_factories(full_flush=True):
 
1568
                    yield factory
1251
1569
                for record in source.get_record_stream(keys, ordering,
1252
1570
                                                       include_delta_closure):
1253
1571
                    yield record
1254
 
        if manager is not None:
1255
 
            for factory in manager.get_record_stream():
1256
 
                yield factory
 
1572
        for factory in batcher.yield_factories(full_flush=True):
 
1573
            yield factory
1257
1574
 
1258
1575
    def get_sha1s(self, keys):
1259
1576
        """See VersionedFiles.get_sha1s()."""
1274
1591
        :return: None
1275
1592
        :seealso VersionedFiles.get_record_stream:
1276
1593
        """
1277
 
        for _ in self._insert_record_stream(stream):
 
1594
        # XXX: Setting random_id=True makes
 
1595
        # test_insert_record_stream_existing_keys fail for groupcompress and
 
1596
        # groupcompress-nograph, this needs to be revisited while addressing
 
1597
        # 'bzr branch' performance issues.
 
1598
        for _ in self._insert_record_stream(stream, random_id=False):
1278
1599
            pass
1279
1600
 
1280
1601
    def _insert_record_stream(self, stream, random_id=False, nostore_sha=None,
1310
1631
        keys_to_add = []
1311
1632
        def flush():
1312
1633
            bytes = self._compressor.flush().to_bytes()
 
1634
            self._compressor = GroupCompressor()
1313
1635
            index, start, length = self._access.add_raw_records(
1314
1636
                [(None, len(bytes))], bytes)[0]
1315
1637
            nodes = []
1318
1640
            self._index.add_records(nodes, random_id=random_id)
1319
1641
            self._unadded_refs = {}
1320
1642
            del keys_to_add[:]
1321
 
            self._compressor = GroupCompressor()
1322
1643
 
1323
1644
        last_prefix = None
1324
 
        last_fulltext_len = None
1325
1645
        max_fulltext_len = 0
1326
1646
        max_fulltext_prefix = None
1327
1647
        insert_manager = None
1328
1648
        block_start = None
1329
1649
        block_length = None
 
1650
        # XXX: TODO: remove this, it is just for safety checking for now
 
1651
        inserted_keys = set()
 
1652
        reuse_this_block = reuse_blocks
1330
1653
        for record in stream:
1331
1654
            # Raise an error when a record is missing.
1332
1655
            if record.storage_kind == 'absent':
1333
1656
                raise errors.RevisionNotPresent(record.key, self)
 
1657
            if random_id:
 
1658
                if record.key in inserted_keys:
 
1659
                    trace.note('Insert claimed random_id=True,'
 
1660
                               ' but then inserted %r two times', record.key)
 
1661
                    continue
 
1662
                inserted_keys.add(record.key)
1334
1663
            if reuse_blocks:
1335
1664
                # If the reuse_blocks flag is set, check to see if we can just
1336
1665
                # 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
1337
1677
                if record.storage_kind == 'groupcompress-block':
1338
1678
                    # Insert the raw block into the target repo
1339
1679
                    insert_manager = record._manager
1340
 
                    insert_manager._check_rebuild_block()
1341
1680
                    bytes = record._manager._block.to_bytes()
1342
1681
                    _, start, length = self._access.add_raw_records(
1343
1682
                        [(None, len(bytes))], bytes)[0]
1346
1685
                    block_length = length
1347
1686
                if record.storage_kind in ('groupcompress-block',
1348
1687
                                           'groupcompress-block-ref'):
1349
 
                    assert insert_manager is not None
1350
 
                    assert record._manager is insert_manager
 
1688
                    if insert_manager is None:
 
1689
                        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
                            )
1351
1695
                    value = "%d %d %d %d" % (block_start, block_length,
1352
1696
                                             record._start, record._end)
1353
1697
                    nodes = [(record.key, value, (record.parents,))]
1371
1715
            if max_fulltext_len < len(bytes):
1372
1716
                max_fulltext_len = len(bytes)
1373
1717
                max_fulltext_prefix = prefix
1374
 
            (found_sha1, start_point, end_point, type,
1375
 
             length) = self._compressor.compress(record.key,
1376
 
                bytes, record.sha1, soft=soft,
1377
 
                nostore_sha=nostore_sha)
1378
 
            # delta_ratio = float(len(bytes)) / length
 
1718
            (found_sha1, start_point, end_point,
 
1719
             type) = self._compressor.compress(record.key,
 
1720
                                               bytes, record.sha1, soft=soft,
 
1721
                                               nostore_sha=nostore_sha)
 
1722
            # delta_ratio = float(len(bytes)) / (end_point - start_point)
1379
1723
            # Check if we want to continue to include that text
1380
1724
            if (prefix == max_fulltext_prefix
1381
1725
                and end_point < 2 * max_fulltext_len):
1394
1738
                self._compressor.pop_last()
1395
1739
                flush()
1396
1740
                max_fulltext_len = len(bytes)
1397
 
                (found_sha1, start_point, end_point, type,
1398
 
                 length) = self._compressor.compress(record.key,
1399
 
                    bytes, record.sha1)
1400
 
                last_fulltext_len = length
 
1741
                (found_sha1, start_point, end_point,
 
1742
                 type) = self._compressor.compress(record.key, bytes,
 
1743
                                                   record.sha1)
1401
1744
            if record.key[-1] is None:
1402
1745
                key = record.key[:-1] + ('sha1:' + found_sha1,)
1403
1746
            else:
1404
1747
                key = record.key
1405
1748
            self._unadded_refs[key] = record.parents
1406
1749
            yield found_sha1
1407
 
            keys_to_add.append((key, '%d %d' % (start_point, end_point),
1408
 
                (record.parents,)))
 
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))
1409
1757
        if len(keys_to_add):
1410
1758
            flush()
1411
1759
        self._compressor = None
1431
1779
 
1432
1780
        :return: An iterator over (line, key).
1433
1781
        """
1434
 
        if pb is None:
1435
 
            pb = progress.DummyProgress()
1436
1782
        keys = set(keys)
1437
1783
        total = len(keys)
1438
1784
        # we don't care about inclusions, the caller cares.
1442
1788
            'unordered', True)):
1443
1789
            # XXX: todo - optimise to use less than full texts.
1444
1790
            key = record.key
1445
 
            pb.update('Walking content', key_idx, total)
 
1791
            if pb is not None:
 
1792
                pb.update('Walking content', key_idx, total)
1446
1793
            if record.storage_kind == 'absent':
1447
1794
                raise errors.RevisionNotPresent(key, self)
1448
1795
            lines = osutils.split_lines(record.get_bytes_as('fulltext'))
1449
1796
            for line in lines:
1450
1797
                yield line, key
1451
 
        pb.update('Walking content', total, total)
 
1798
        if pb is not None:
 
1799
            pb.update('Walking content', total, total)
1452
1800
 
1453
1801
    def keys(self):
1454
1802
        """See VersionedFiles.keys."""
1465
1813
    """Mapper from GroupCompressVersionedFiles needs into GraphIndex storage."""
1466
1814
 
1467
1815
    def __init__(self, graph_index, is_locked, parents=True,
1468
 
        add_callback=None):
 
1816
        add_callback=None, track_external_parent_refs=False,
 
1817
        inconsistency_fatal=True, track_new_keys=False):
1469
1818
        """Construct a _GCGraphIndex on a graph_index.
1470
1819
 
1471
1820
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
1476
1825
        :param add_callback: If not None, allow additions to the index and call
1477
1826
            this callback with a list of added GraphIndex nodes:
1478
1827
            [(node, value, node_refs), ...]
 
1828
        :param track_external_parent_refs: As keys are added, keep track of the
 
1829
            keys they reference, so that we can query get_missing_parents(),
 
1830
            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).
1479
1835
        """
1480
1836
        self._add_callback = add_callback
1481
1837
        self._graph_index = graph_index
1482
1838
        self._parents = parents
1483
1839
        self.has_graph = parents
1484
1840
        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
        if track_external_parent_refs:
 
1846
            self._key_dependencies = knit._KeyRefs(
 
1847
                track_new_keys=track_new_keys)
 
1848
        else:
 
1849
            self._key_dependencies = None
1485
1850
 
1486
1851
    def add_records(self, records, random_id=False):
1487
1852
        """Add multiple records to the index.
1508
1873
                if refs:
1509
1874
                    for ref in refs:
1510
1875
                        if ref:
1511
 
                            raise KnitCorrupt(self,
 
1876
                            raise errors.KnitCorrupt(self,
1512
1877
                                "attempt to add node with parents "
1513
1878
                                "in parentless index.")
1514
1879
                    refs = ()
1518
1883
        if not random_id:
1519
1884
            present_nodes = self._get_entries(keys)
1520
1885
            for (index, key, value, node_refs) in present_nodes:
1521
 
                if node_refs != keys[key][1]:
1522
 
                    raise errors.KnitCorrupt(self, "inconsistent details in add_records"
1523
 
                        ": %s %s" % ((value, node_refs), keys[key]))
 
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)
1524
1898
                del keys[key]
1525
1899
                changed = True
1526
1900
        if changed:
1532
1906
                for key, (value, node_refs) in keys.iteritems():
1533
1907
                    result.append((key, value))
1534
1908
            records = result
 
1909
        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)
1535
1918
        self._add_callback(records)
1536
1919
 
1537
1920
    def _check_read(self):
1566
1949
        if check_present:
1567
1950
            missing_keys = keys.difference(found_keys)
1568
1951
            if missing_keys:
1569
 
                raise RevisionNotPresent(missing_keys.pop(), self)
 
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)
1570
1957
 
1571
1958
    def get_parent_map(self, keys):
1572
1959
        """Get a map of the parents of keys.
1586
1973
                result[node[1]] = None
1587
1974
        return result
1588
1975
 
 
1976
    def get_missing_parents(self):
 
1977
        """Return the keys of missing parents."""
 
1978
        # Copied from _KnitGraphIndex.get_missing_parents
 
1979
        # We may have false positives, so filter those out.
 
1980
        self._key_dependencies.satisfy_refs_for_keys(
 
1981
            self.get_parent_map(self._key_dependencies.get_unsatisfied_refs()))
 
1982
        return frozenset(self._key_dependencies.get_unsatisfied_refs())
 
1983
 
1589
1984
    def get_build_details(self, keys):
1590
1985
        """Get the various build details for keys.
1591
1986
 
1631
2026
        """Convert an index value to position details."""
1632
2027
        bits = node[2].split(' ')
1633
2028
        # 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.
1634
2038
        start = int(bits[0])
 
2039
        start = self._int_cache.setdefault(start, start)
1635
2040
        stop = int(bits[1])
 
2041
        stop = self._int_cache.setdefault(stop, stop)
1636
2042
        basis_end = int(bits[2])
1637
2043
        delta_end = int(bits[3])
1638
 
        return node[0], start, stop, basis_end, delta_end
 
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)
 
2047
 
 
2048
    def scan_unvalidated_index(self, graph_index):
 
2049
        """Inform this _GCGraphIndex that there is an unvalidated index.
 
2050
 
 
2051
        This allows this _GCGraphIndex to keep track of any missing
 
2052
        compression parents we may want to have filled in to make those
 
2053
        indices valid.  It also allows _GCGraphIndex to track any new keys.
 
2054
 
 
2055
        :param graph_index: A GraphIndex
 
2056
        """
 
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])
1639
2064
 
1640
2065
 
1641
2066
from bzrlib._groupcompress_py import (
1643
2068
    apply_delta_to_source,
1644
2069
    encode_base128_int,
1645
2070
    decode_base128_int,
 
2071
    decode_copy_instruction,
1646
2072
    LinesDeltaIndex,
1647
2073
    )
1648
2074
try:
1654
2080
        decode_base128_int,
1655
2081
        )
1656
2082
    GroupCompressor = PyrexGroupCompressor
1657
 
except ImportError:
 
2083
except ImportError, e:
 
2084
    osutils.failed_to_load_extension(e)
1658
2085
    GroupCompressor = PythonGroupCompressor
1659
2086