/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5050.70.1 by Martin Pool
Add failing test for bug 715000
1
# Copyright (C) 2008-2011 Canonical Ltd
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
2
#
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
3
# This program is free software; you can redistribute it and/or modify
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
12
#
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
3735.36.3 by John Arbash Meinel
Add the new address for FSF to the new files.
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
16
17
"""Core compression logic for compressing streams of related files."""
18
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
19
import time
0.17.5 by Robert Collins
nograph tests completely passing.
20
import zlib
0.17.44 by John Arbash Meinel
Use the bit field to allow both lzma groups and zlib groups.
21
try:
22
    import pylzma
23
except ImportError:
24
    pylzma = None
0.17.5 by Robert Collins
nograph tests completely passing.
25
0.17.4 by Robert Collins
Annotate.
26
from bzrlib import (
27
    annotate,
0.17.5 by Robert Collins
nograph tests completely passing.
28
    debug,
29
    errors,
0.17.4 by Robert Collins
Annotate.
30
    graph as _mod_graph,
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
31
    knit,
0.20.2 by John Arbash Meinel
Teach groupcompress about 'chunked' encoding
32
    osutils,
0.17.4 by Robert Collins
Annotate.
33
    pack,
4789.28.3 by John Arbash Meinel
Add a static_tuple.as_tuples() helper.
34
    static_tuple,
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
35
    trace,
0.17.4 by Robert Collins
Annotate.
36
    )
0.17.21 by Robert Collins
Update groupcompress to bzrlib 1.10.
37
from bzrlib.btree_index import BTreeBuilder
0.17.24 by Robert Collins
Add a group cache to decompression, 5 times faster than knit at decompression when accessing everything in a group.
38
from bzrlib.lru_cache import LRUSizeCache
5757.5.1 by Jelmer Vernooij
Move _DirectPackAccess to bzrlib.repofmt.pack_repo.
39
from bzrlib.repofmt import pack_repo
0.17.9 by Robert Collins
Initial stab at repository format support.
40
from bzrlib.tsort import topo_sort
0.17.2 by Robert Collins
Core proof of concept working.
41
from bzrlib.versionedfile import (
0.17.5 by Robert Collins
nograph tests completely passing.
42
    adapter_registry,
43
    AbsentContentFactory,
0.20.5 by John Arbash Meinel
Finish the Fulltext => Chunked conversions so that we work in the more-efficient Chunks.
44
    ChunkedContentFactory,
0.17.2 by Robert Collins
Core proof of concept working.
45
    FulltextContentFactory,
46
    VersionedFiles,
47
    )
48
4634.3.17 by Andrew Bennetts
Make BATCH_SIZE a global.
49
# Minimum number of uncompressed bytes to try fetch at once when retrieving
50
# groupcompress blocks.
51
BATCH_SIZE = 2**16
52
0.17.44 by John Arbash Meinel
Use the bit field to allow both lzma groups and zlib groups.
53
_USE_LZMA = False and (pylzma is not None)
0.17.2 by Robert Collins
Core proof of concept working.
54
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
55
# osutils.sha_string('')
56
_null_sha1 = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
57
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
58
def sort_gc_optimal(parent_map):
3735.31.14 by John Arbash Meinel
Change the gc-optimal to 'groupcompress'
59
    """Sort and group the keys in parent_map into groupcompress order.
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
60
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
61
    groupcompress is defined (currently) as reverse-topological order, grouped
62
    by the key prefix.
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
63
64
    :return: A sorted-list of keys
65
    """
3735.31.14 by John Arbash Meinel
Change the gc-optimal to 'groupcompress'
66
    # groupcompress ordering is approximately reverse topological,
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
67
    # properly grouped by file-id.
0.20.23 by John Arbash Meinel
Add a progress indicator for chk pages.
68
    per_prefix_map = {}
4593.5.43 by John Arbash Meinel
The api for topo_sort() was to allow a list of (key, value)
69
    for key, value in parent_map.iteritems():
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
70
        if isinstance(key, str) or len(key) == 1:
0.20.23 by John Arbash Meinel
Add a progress indicator for chk pages.
71
            prefix = ''
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
72
        else:
0.20.23 by John Arbash Meinel
Add a progress indicator for chk pages.
73
            prefix = key[0]
74
        try:
4593.5.43 by John Arbash Meinel
The api for topo_sort() was to allow a list of (key, value)
75
            per_prefix_map[prefix][key] = value
0.20.23 by John Arbash Meinel
Add a progress indicator for chk pages.
76
        except KeyError:
4593.5.43 by John Arbash Meinel
The api for topo_sort() was to allow a list of (key, value)
77
            per_prefix_map[prefix] = {key: value}
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
78
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
79
    present_keys = []
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
80
    for prefix in sorted(per_prefix_map):
81
        present_keys.extend(reversed(topo_sort(per_prefix_map[prefix])))
82
    return present_keys
83
84
3735.32.9 by John Arbash Meinel
Use a 32kB extension, since that is the max window size for zlib.
85
# The max zlib window size is 32kB, so if we set 'max_size' output of the
86
# decompressor to the requested bytes + 32kB, then we should guarantee
87
# num_bytes coming out.
88
_ZLIB_DECOMP_WINDOW = 32*1024
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
89
90
class GroupCompressBlock(object):
91
    """An object which maintains the internal structure of the compressed data.
92
93
    This tracks the meta info (start of text, length, type, etc.)
94
    """
95
0.25.5 by John Arbash Meinel
Now using a zlib compressed format.
96
    # Group Compress Block v1 Zlib
97
    GCB_HEADER = 'gcb1z\n'
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
98
    # Group Compress Block v1 Lzma
0.17.44 by John Arbash Meinel
Use the bit field to allow both lzma groups and zlib groups.
99
    GCB_LZ_HEADER = 'gcb1l\n'
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
100
    GCB_KNOWN_HEADERS = (GCB_HEADER, GCB_LZ_HEADER)
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
101
102
    def __init__(self):
103
        # map by key? or just order in file?
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
104
        self._compressor_name = None
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
105
        self._z_content_chunks = None
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
106
        self._z_content_decompressor = None
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
107
        self._z_content_length = None
108
        self._content_length = None
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
109
        self._content = None
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
110
        self._content_chunks = None
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
111
112
    def __len__(self):
3735.38.4 by John Arbash Meinel
Another disk format change.
113
        # This is the maximum number of bytes this object will reference if
114
        # everything is decompressed. However, if we decompress less than
115
        # everything... (this would cause some problems for LRUSizeCache)
116
        return self._content_length + self._z_content_length
0.17.48 by John Arbash Meinel
if _NO_LABELS is set, don't bother parsing the mini header.
117
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
118
    def _ensure_content(self, num_bytes=None):
119
        """Make sure that content has been expanded enough.
120
121
        :param num_bytes: Ensure that we have extracted at least num_bytes of
122
            content. If None, consume everything
123
        """
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
124
        if self._content_length is None:
125
            raise AssertionError('self._content_length should never be None')
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
126
        if num_bytes is None:
127
            num_bytes = self._content_length
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
128
        elif (self._content_length is not None
129
              and num_bytes > self._content_length):
130
            raise AssertionError(
131
                'requested num_bytes (%d) > content length (%d)'
132
                % (num_bytes, self._content_length))
133
        # Expand the content if required
3735.32.6 by John Arbash Meinel
A bit of reworking changes things so content is expanded at extract() time.
134
        if self._content is None:
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
135
            if self._content_chunks is not None:
136
                self._content = ''.join(self._content_chunks)
137
                self._content_chunks = None
138
        if self._content is None:
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
139
            # We join self._z_content_chunks here, because if we are
140
            # decompressing, then it is *very* likely that we have a single
141
            # chunk
142
            if self._z_content_chunks is None:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
143
                raise AssertionError('No content to decompress')
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
144
            z_content = ''.join(self._z_content_chunks)
145
            if z_content == '':
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
146
                self._content = ''
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
147
            elif self._compressor_name == 'lzma':
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
148
                # We don't do partial lzma decomp yet
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
149
                self._content = pylzma.decompress(z_content)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
150
            elif self._compressor_name == 'zlib':
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
151
                # Start a zlib decompressor
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
152
                if num_bytes * 4 > self._content_length * 3:
153
                    # If we are requesting more that 3/4ths of the content,
154
                    # just extract the whole thing in a single pass
155
                    num_bytes = self._content_length
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
156
                    self._content = zlib.decompress(z_content)
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
157
                else:
158
                    self._z_content_decompressor = zlib.decompressobj()
159
                    # Seed the decompressor with the uncompressed bytes, so
160
                    # that the rest of the code is simplified
161
                    self._content = self._z_content_decompressor.decompress(
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
162
                        z_content, num_bytes + _ZLIB_DECOMP_WINDOW)
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
163
                    if not self._z_content_decompressor.unconsumed_tail:
164
                        self._z_content_decompressor = None
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
165
            else:
3735.2.182 by Matt Nordhoff
Improve an assertion message slightly, and fix typos in 2 others
166
                raise AssertionError('Unknown compressor: %r'
3735.2.183 by John Arbash Meinel
Fix the compressor name.
167
                                     % self._compressor_name)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
168
        # Any bytes remaining to be decompressed will be in the decompressors
169
        # 'unconsumed_tail'
170
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
171
        # Do we have enough bytes already?
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
172
        if len(self._content) >= num_bytes:
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
173
            return
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
174
        # If we got this far, and don't have a decompressor, something is wrong
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
175
        if self._z_content_decompressor is None:
176
            raise AssertionError(
3735.2.182 by Matt Nordhoff
Improve an assertion message slightly, and fix typos in 2 others
177
                'No decompressor to decompress %d bytes' % num_bytes)
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
178
        remaining_decomp = self._z_content_decompressor.unconsumed_tail
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
179
        if not remaining_decomp:
180
            raise AssertionError('Nothing left to decompress')
181
        needed_bytes = num_bytes - len(self._content)
182
        # We always set max_size to 32kB over the minimum needed, so that
183
        # zlib will give us as much as we really want.
184
        # TODO: If this isn't good enough, we could make a loop here,
185
        #       that keeps expanding the request until we get enough
186
        self._content += self._z_content_decompressor.decompress(
187
            remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
188
        if len(self._content) < num_bytes:
189
            raise AssertionError('%d bytes wanted, only %d available'
190
                                 % (num_bytes, len(self._content)))
191
        if not self._z_content_decompressor.unconsumed_tail:
192
            # The stream is finished
193
            self._z_content_decompressor = None
3735.32.6 by John Arbash Meinel
A bit of reworking changes things so content is expanded at extract() time.
194
3735.38.4 by John Arbash Meinel
Another disk format change.
195
    def _parse_bytes(self, bytes, pos):
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
196
        """Read the various lengths from the header.
197
198
        This also populates the various 'compressed' buffers.
199
200
        :return: The position in bytes just after the last newline
201
        """
3735.38.4 by John Arbash Meinel
Another disk format change.
202
        # At present, we have 2 integers for the compressed and uncompressed
203
        # content. In base10 (ascii) 14 bytes can represent > 1TB, so to avoid
204
        # checking too far, cap the search to 14 bytes.
205
        pos2 = bytes.index('\n', pos, pos + 14)
206
        self._z_content_length = int(bytes[pos:pos2])
207
        pos = pos2 + 1
208
        pos2 = bytes.index('\n', pos, pos + 14)
209
        self._content_length = int(bytes[pos:pos2])
210
        pos = pos2 + 1
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
211
        if len(bytes) != (pos + self._z_content_length):
212
            # XXX: Define some GCCorrupt error ?
213
            raise AssertionError('Invalid bytes: (%d) != %d + %d' %
214
                                 (len(bytes), pos, self._z_content_length))
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
215
        self._z_content_chunks = (bytes[pos:],)
216
217
    @property
218
    def _z_content(self):
5439.2.2 by John Arbash Meinel
Smal tweaks from reviewer feedback.
219
        """Return z_content_chunks as a simple string.
220
221
        Meant only to be used by the test suite.
222
        """
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
223
        if self._z_content_chunks is not None:
224
            return ''.join(self._z_content_chunks)
225
        return None
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
226
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
227
    @classmethod
228
    def from_bytes(cls, bytes):
229
        out = cls()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
230
        if bytes[:6] not in cls.GCB_KNOWN_HEADERS:
231
            raise ValueError('bytes did not start with any of %r'
232
                             % (cls.GCB_KNOWN_HEADERS,))
233
        # XXX: why not testing the whole header ?
0.17.44 by John Arbash Meinel
Use the bit field to allow both lzma groups and zlib groups.
234
        if bytes[4] == 'z':
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
235
            out._compressor_name = 'zlib'
0.17.45 by John Arbash Meinel
Just make sure we have the right decompressor
236
        elif bytes[4] == 'l':
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
237
            out._compressor_name = 'lzma'
0.17.45 by John Arbash Meinel
Just make sure we have the right decompressor
238
        else:
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
239
            raise ValueError('unknown compressor: %r' % (bytes,))
3735.38.4 by John Arbash Meinel
Another disk format change.
240
        out._parse_bytes(bytes, 6)
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
241
        return out
242
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
243
    def extract(self, key, start, end, sha1=None):
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
244
        """Extract the text for a specific key.
245
246
        :param key: The label used for this content
247
        :param sha1: TODO (should we validate only when sha1 is supplied?)
248
        :return: The bytes for the content
249
        """
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
250
        if start == end == 0:
3735.2.158 by John Arbash Meinel
Remove support for passing None for end in GroupCompressBlock.extract.
251
            return ''
252
        self._ensure_content(end)
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
253
        # The bytes are 'f' or 'd' for the type, then a variable-length
254
        # base128 integer for the content size, then the actual content
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
255
        # We know that the variable-length integer won't be longer than 5
256
        # bytes (it takes 5 bytes to encode 2^32)
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
257
        c = self._content[start]
258
        if c == 'f':
259
            type = 'fulltext'
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
260
        else:
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
261
            if c != 'd':
262
                raise ValueError('Unknown content control code: %s'
263
                                 % (c,))
264
            type = 'delta'
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
265
        content_len, len_len = decode_base128_int(
266
                            self._content[start + 1:start + 6])
267
        content_start = start + 1 + len_len
3735.2.158 by John Arbash Meinel
Remove support for passing None for end in GroupCompressBlock.extract.
268
        if end != content_start + content_len:
269
            raise ValueError('end != len according to field header'
270
                ' %s != %s' % (end, content_start + content_len))
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
271
        if c == 'f':
3735.40.19 by John Arbash Meinel
Implement apply_delta_to_source which doesn't have to malloc another string.
272
            bytes = self._content[content_start:end]
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
273
        elif c == 'd':
3735.40.19 by John Arbash Meinel
Implement apply_delta_to_source which doesn't have to malloc another string.
274
            bytes = apply_delta_to_source(self._content, content_start, end)
3735.2.158 by John Arbash Meinel
Remove support for passing None for end in GroupCompressBlock.extract.
275
        return bytes
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
276
4469.1.2 by John Arbash Meinel
The only caller already knows the content length, so make the api such that
277
    def set_chunked_content(self, content_chunks, length):
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
278
        """Set the content of this block to the given chunks."""
4469.1.3 by John Arbash Meinel
Notes on why we do it the way we do.
279
        # If we have lots of short lines, it is may be more efficient to join
280
        # the content ahead of time. If the content is <10MiB, we don't really
281
        # care about the extra memory consumption, so we can just pack it and
282
        # be done. However, timing showed 18s => 17.9s for repacking 1k revs of
283
        # mysql, which is below the noise margin
4469.1.2 by John Arbash Meinel
The only caller already knows the content length, so make the api such that
284
        self._content_length = length
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
285
        self._content_chunks = content_chunks
4469.1.2 by John Arbash Meinel
The only caller already knows the content length, so make the api such that
286
        self._content = None
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
287
        self._z_content_chunks = None
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
288
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
289
    def set_content(self, content):
290
        """Set the content of this block."""
291
        self._content_length = len(content)
292
        self._content = content
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
293
        self._z_content_chunks = None
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
294
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
295
    def _create_z_content_using_lzma(self):
296
        if self._content_chunks is not None:
297
            self._content = ''.join(self._content_chunks)
298
            self._content_chunks = None
299
        if self._content is None:
300
            raise AssertionError('Nothing to compress')
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
301
        z_content = pylzma.compress(self._content)
302
        self._z_content_chunks = (z_content,)
303
        self._z_content_length = len(z_content)
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
304
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
305
    def _create_z_content_from_chunks(self, chunks):
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
306
        compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION)
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
307
        # Peak in this point is 1 fulltext, 1 compressed text, + zlib overhead
308
        # (measured peak is maybe 30MB over the above...)
309
        compressed_chunks = map(compressor.compress, chunks)
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
310
        compressed_chunks.append(compressor.flush())
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
311
        # Ignore empty chunks
312
        self._z_content_chunks = [c for c in compressed_chunks if c]
313
        self._z_content_length = sum(map(len, self._z_content_chunks))
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
314
315
    def _create_z_content(self):
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
316
        if self._z_content_chunks is not None:
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
317
            return
318
        if _USE_LZMA:
319
            self._create_z_content_using_lzma()
320
            return
321
        if self._content_chunks is not None:
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
322
            chunks = self._content_chunks
323
        else:
324
            chunks = (self._content,)
325
        self._create_z_content_from_chunks(chunks)
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
326
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
327
    def to_chunks(self):
328
        """Create the byte stream as a series of 'chunks'"""
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
329
        self._create_z_content()
0.17.46 by John Arbash Meinel
Set the proper header when using/not using lzma
330
        if _USE_LZMA:
331
            header = self.GCB_LZ_HEADER
332
        else:
333
            header = self.GCB_HEADER
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
334
        chunks = ['%s%d\n%d\n'
335
                  % (header, self._z_content_length, self._content_length),
0.25.7 by John Arbash Meinel
Have the GroupCompressBlock decide how to compress the header and content.
336
                 ]
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
337
        chunks.extend(self._z_content_chunks)
338
        total_len = sum(map(len, chunks))
339
        return total_len, chunks
340
341
    def to_bytes(self):
342
        """Encode the information into a byte stream."""
343
        total_len, chunks = self.to_chunks()
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
344
        return ''.join(chunks)
345
4300.1.1 by John Arbash Meinel
Add the ability to convert a gc block into 'human readable' form.
346
    def _dump(self, include_text=False):
347
        """Take this block, and spit out a human-readable structure.
348
349
        :param include_text: Inserts also include text bits, chose whether you
350
            want this displayed in the dump or not.
351
        :return: A dump of the given block. The layout is something like:
352
            [('f', length), ('d', delta_length, text_length, [delta_info])]
353
            delta_info := [('i', num_bytes, text), ('c', offset, num_bytes),
354
            ...]
355
        """
356
        self._ensure_content()
357
        result = []
358
        pos = 0
359
        while pos < self._content_length:
360
            kind = self._content[pos]
361
            pos += 1
362
            if kind not in ('f', 'd'):
363
                raise ValueError('invalid kind character: %r' % (kind,))
364
            content_len, len_len = decode_base128_int(
365
                                self._content[pos:pos + 5])
366
            pos += len_len
367
            if content_len + pos > self._content_length:
368
                raise ValueError('invalid content_len %d for record @ pos %d'
369
                                 % (content_len, pos - len_len - 1))
370
            if kind == 'f': # Fulltext
4398.5.6 by John Arbash Meinel
A bit more debugging information from gcblock._dump(True)
371
                if include_text:
372
                    text = self._content[pos:pos+content_len]
373
                    result.append(('f', content_len, text))
374
                else:
375
                    result.append(('f', content_len))
4300.1.1 by John Arbash Meinel
Add the ability to convert a gc block into 'human readable' form.
376
            elif kind == 'd': # Delta
377
                delta_content = self._content[pos:pos+content_len]
378
                delta_info = []
379
                # The first entry in a delta is the decompressed length
380
                decomp_len, delta_pos = decode_base128_int(delta_content)
381
                result.append(('d', content_len, decomp_len, delta_info))
382
                measured_len = 0
383
                while delta_pos < content_len:
384
                    c = ord(delta_content[delta_pos])
385
                    delta_pos += 1
386
                    if c & 0x80: # Copy
387
                        (offset, length,
388
                         delta_pos) = decode_copy_instruction(delta_content, c,
389
                                                              delta_pos)
4398.5.6 by John Arbash Meinel
A bit more debugging information from gcblock._dump(True)
390
                        if include_text:
391
                            text = self._content[offset:offset+length]
392
                            delta_info.append(('c', offset, length, text))
393
                        else:
394
                            delta_info.append(('c', offset, length))
4300.1.1 by John Arbash Meinel
Add the ability to convert a gc block into 'human readable' form.
395
                        measured_len += length
396
                    else: # Insert
397
                        if include_text:
398
                            txt = delta_content[delta_pos:delta_pos+c]
399
                        else:
400
                            txt = ''
401
                        delta_info.append(('i', c, txt))
402
                        measured_len += c
403
                        delta_pos += c
404
                if delta_pos != content_len:
405
                    raise ValueError('Delta consumed a bad number of bytes:'
406
                                     ' %d != %d' % (delta_pos, content_len))
407
                if measured_len != decomp_len:
408
                    raise ValueError('Delta claimed fulltext was %d bytes, but'
409
                                     ' extraction resulted in %d bytes'
410
                                     % (decomp_len, measured_len))
411
            pos += content_len
412
        return result
413
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
414
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
415
class _LazyGroupCompressFactory(object):
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
416
    """Yield content from a GroupCompressBlock on demand."""
417
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
418
    def __init__(self, key, parents, manager, start, end, first):
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
419
        """Create a _LazyGroupCompressFactory
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
420
421
        :param key: The key of just this record
422
        :param parents: The parents of this key (possibly None)
423
        :param gc_block: A GroupCompressBlock object
424
        :param start: Offset of the first byte for this record in the
425
            uncompressd content
426
        :param end: Offset of the byte just after the end of this record
427
            (ie, bytes = content[start:end])
428
        :param first: Is this the first Factory for the given block?
429
        """
430
        self.key = key
431
        self.parents = parents
432
        self.sha1 = None
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
433
        # Note: This attribute coupled with Manager._factories creates a
434
        #       reference cycle. Perhaps we would rather use a weakref(), or
435
        #       find an appropriate time to release the ref. After the first
436
        #       get_bytes_as call? After Manager.get_record_stream() returns
437
        #       the object?
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
438
        self._manager = manager
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
439
        self._bytes = None
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
440
        self.storage_kind = 'groupcompress-block'
441
        if not first:
442
            self.storage_kind = 'groupcompress-block-ref'
443
        self._first = first
444
        self._start = start
445
        self._end = end
446
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
447
    def __repr__(self):
448
        return '%s(%s, first=%s)' % (self.__class__.__name__,
449
            self.key, self._first)
450
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
451
    def get_bytes_as(self, storage_kind):
452
        if storage_kind == self.storage_kind:
453
            if self._first:
454
                # wire bytes, something...
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
455
                return self._manager._wire_bytes()
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
456
            else:
457
                return ''
458
        if storage_kind in ('fulltext', 'chunked'):
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
459
            if self._bytes is None:
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
460
                # Grab and cache the raw bytes for this entry
461
                # and break the ref-cycle with _manager since we don't need it
462
                # anymore
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
463
                self._manager._prepare_for_extract()
464
                block = self._manager._block
3735.34.2 by John Arbash Meinel
Merge brisbane-core tip, resolve differences.
465
                self._bytes = block.extract(self.key, self._start, self._end)
3735.37.5 by John Arbash Meinel
Restore the refcycle reduction code.
466
                # There are code paths that first extract as fulltext, and then
467
                # extract as storage_kind (smart fetch). So we don't break the
468
                # refcycle here, but instead in manager.get_record_stream()
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
469
            if storage_kind == 'fulltext':
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
470
                return self._bytes
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
471
            else:
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
472
                return [self._bytes]
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
473
        raise errors.UnavailableRepresentation(self.key, storage_kind,
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
474
                                               self.storage_kind)
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
475
476
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
477
class _LazyGroupContentManager(object):
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
478
    """This manages a group of _LazyGroupCompressFactory objects."""
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
479
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
480
    _max_cut_fraction = 0.75 # We allow a block to be trimmed to 75% of
481
                             # current size, and still be considered
482
                             # resuable
483
    _full_block_size = 4*1024*1024
484
    _full_mixed_block_size = 2*1024*1024
485
    _full_enough_block_size = 3*1024*1024 # size at which we won't repack
486
    _full_enough_mixed_block_size = 2*768*1024 # 1.5MB
487
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
488
    def __init__(self, block):
489
        self._block = block
490
        # We need to preserve the ordering
491
        self._factories = []
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
492
        self._last_byte = 0
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
493
494
    def add_factory(self, key, parents, start, end):
495
        if not self._factories:
496
            first = True
497
        else:
498
            first = False
499
        # Note that this creates a reference cycle....
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
500
        factory = _LazyGroupCompressFactory(key, parents, self,
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
501
            start, end, first=first)
3735.36.13 by John Arbash Meinel
max() shows up under lsprof as more expensive than creating an object.
502
        # max() works here, but as a function call, doing a compare seems to be
503
        # significantly faster, timeit says 250ms for max() and 100ms for the
504
        # comparison
505
        if end > self._last_byte:
506
            self._last_byte = end
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
507
        self._factories.append(factory)
508
509
    def get_record_stream(self):
510
        """Get a record for all keys added so far."""
511
        for factory in self._factories:
512
            yield factory
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
513
            # Break the ref-cycle
3735.34.2 by John Arbash Meinel
Merge brisbane-core tip, resolve differences.
514
            factory._bytes = None
3735.37.5 by John Arbash Meinel
Restore the refcycle reduction code.
515
            factory._manager = None
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
516
        # TODO: Consider setting self._factories = None after the above loop,
517
        #       as it will break the reference cycle
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
518
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
519
    def _trim_block(self, last_byte):
520
        """Create a new GroupCompressBlock, with just some of the content."""
521
        # None of the factories need to be adjusted, because the content is
522
        # located in an identical place. Just that some of the unreferenced
523
        # trailing bytes are stripped
524
        trace.mutter('stripping trailing bytes from groupcompress block'
525
                     ' %d => %d', self._block._content_length, last_byte)
526
        new_block = GroupCompressBlock()
527
        self._block._ensure_content(last_byte)
528
        new_block.set_content(self._block._content[:last_byte])
529
        self._block = new_block
530
531
    def _rebuild_block(self):
532
        """Create a new GroupCompressBlock with only the referenced texts."""
533
        compressor = GroupCompressor()
534
        tstart = time.time()
535
        old_length = self._block._content_length
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
536
        end_point = 0
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
537
        for factory in self._factories:
538
            bytes = factory.get_bytes_as('fulltext')
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
539
            (found_sha1, start_point, end_point,
540
             type) = compressor.compress(factory.key, bytes, factory.sha1)
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
541
            # Now update this factory with the new offsets, etc
542
            factory.sha1 = found_sha1
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
543
            factory._start = start_point
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
544
            factory._end = end_point
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
545
        self._last_byte = end_point
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
546
        new_block = compressor.flush()
547
        # TODO: Should we check that new_block really *is* smaller than the old
548
        #       block? It seems hard to come up with a method that it would
549
        #       expand, since we do full compression again. Perhaps based on a
550
        #       request that ends up poorly ordered?
551
        delta = time.time() - tstart
552
        self._block = new_block
4641.4.2 by John Arbash Meinel
Use unordered fetches to avoid fragmentation (bug #402645)
553
        trace.mutter('creating new compressed block on-the-fly in %.3fs'
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
554
                     ' %d bytes => %d bytes', delta, old_length,
555
                     self._block._content_length)
556
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
557
    def _prepare_for_extract(self):
558
        """A _LazyGroupCompressFactory is about to extract to fulltext."""
559
        # We expect that if one child is going to fulltext, all will be. This
560
        # helps prevent all of them from extracting a small amount at a time.
561
        # Which in itself isn't terribly expensive, but resizing 2MB 32kB at a
562
        # time (self._block._content) is a little expensive.
563
        self._block._ensure_content(self._last_byte)
564
4665.3.4 by John Arbash Meinel
Refactor the check_rebuild code a bit, so that we can potentially
565
    def _check_rebuild_action(self):
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
566
        """Check to see if our block should be repacked."""
567
        total_bytes_used = 0
568
        last_byte_used = 0
569
        for factory in self._factories:
570
            total_bytes_used += factory._end - factory._start
4665.3.4 by John Arbash Meinel
Refactor the check_rebuild code a bit, so that we can potentially
571
            if last_byte_used < factory._end:
572
                last_byte_used = factory._end
573
        # If we are using more than half of the bytes from the block, we have
574
        # nothing else to check
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
575
        if total_bytes_used * 2 >= self._block._content_length:
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
576
            return None, last_byte_used, total_bytes_used
4665.3.4 by John Arbash Meinel
Refactor the check_rebuild code a bit, so that we can potentially
577
        # We are using less than 50% of the content. Is the content we are
578
        # using at the beginning of the block? If so, we can just trim the
579
        # tail, rather than rebuilding from scratch.
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
580
        if total_bytes_used * 2 > last_byte_used:
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
581
            return 'trim', last_byte_used, total_bytes_used
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
582
583
        # We are using a small amount of the data, and it isn't just packed
584
        # nicely at the front, so rebuild the content.
585
        # Note: This would be *nicer* as a strip-data-from-group, rather than
586
        #       building it up again from scratch
587
        #       It might be reasonable to consider the fulltext sizes for
588
        #       different bits when deciding this, too. As you may have a small
589
        #       fulltext, and a trivial delta, and you are just trading around
590
        #       for another fulltext. If we do a simple 'prune' you may end up
591
        #       expanding many deltas into fulltexts, as well.
592
        #       If we build a cheap enough 'strip', then we could try a strip,
593
        #       if that expands the content, we then rebuild.
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
594
        return 'rebuild', last_byte_used, total_bytes_used
595
596
    def check_is_well_utilized(self):
597
        """Is the current block considered 'well utilized'?
598
4665.3.15 by Robert Collins
Review and tweak
599
        This heuristic asks if the current block considers itself to be a fully
600
        developed group, rather than just a loose collection of data.
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
601
        """
602
        if len(self._factories) == 1:
4665.3.15 by Robert Collins
Review and tweak
603
            # A block of length 1 could be improved by combining with other
604
            # groups - don't look deeper. Even larger than max size groups
605
            # could compress well with adjacent versions of the same thing.
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
606
            return False
607
        action, last_byte_used, total_bytes_used = self._check_rebuild_action()
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
608
        block_size = self._block._content_length
609
        if total_bytes_used < block_size * self._max_cut_fraction:
610
            # This block wants to trim itself small enough that we want to
611
            # consider it under-utilized.
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
612
            return False
613
        # TODO: This code is meant to be the twin of _insert_record_stream's
614
        #       'start_new_block' logic. It would probably be better to factor
615
        #       out that logic into a shared location, so that it stays
616
        #       together better
4665.3.6 by John Arbash Meinel
Add some comments, etc to discussing the 'is this block full enough'
617
        # We currently assume a block is properly utilized whenever it is >75%
618
        # of the size of a 'full' block. In normal operation, a block is
619
        # considered full when it hits 4MB of same-file content. So any block
620
        # >3MB is 'full enough'.
621
        # The only time this isn't true is when a given block has large-object
622
        # content. (a single file >4MB, etc.)
623
        # Under these circumstances, we allow a block to grow to
624
        # 2 x largest_content.  Which means that if a given block had a large
625
        # object, it may actually be under-utilized. However, given that this
626
        # is 'pack-on-the-fly' it is probably reasonable to not repack large
4665.3.15 by Robert Collins
Review and tweak
627
        # content blobs on-the-fly. Note that because we return False for all
628
        # 1-item blobs, we will repack them; we may wish to reevaluate our
629
        # treatment of large object blobs in the future.
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
630
        if block_size >= self._full_enough_block_size:
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
631
            return True
4665.3.6 by John Arbash Meinel
Add some comments, etc to discussing the 'is this block full enough'
632
        # If a block is <3MB, it still may be considered 'full' if it contains
633
        # mixed content. The current rule is 2MB of mixed content is considered
634
        # full. So check to see if this block contains mixed content, and
635
        # set the threshold appropriately.
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
636
        common_prefix = None
637
        for factory in self._factories:
638
            prefix = factory.key[:-1]
639
            if common_prefix is None:
640
                common_prefix = prefix
641
            elif prefix != common_prefix:
4665.3.6 by John Arbash Meinel
Add some comments, etc to discussing the 'is this block full enough'
642
                # Mixed content, check the size appropriately
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
643
                if block_size >= self._full_enough_mixed_block_size:
4665.3.6 by John Arbash Meinel
Add some comments, etc to discussing the 'is this block full enough'
644
                    return True
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
645
                break
4665.3.6 by John Arbash Meinel
Add some comments, etc to discussing the 'is this block full enough'
646
        # The content failed both the mixed check and the single-content check
647
        # so obviously it is not fully utilized
4665.3.9 by John Arbash Meinel
Start doing some work to make sure that we call _check_rebuild_block
648
        # TODO: there is one other constraint that isn't being checked
649
        #       namely, that the entries in the block are in the appropriate
650
        #       order. For example, you could insert the entries in exactly
651
        #       reverse groupcompress order, and we would think that is ok.
652
        #       (all the right objects are in one group, and it is fully
653
        #       utilized, etc.) For now, we assume that case is rare,
654
        #       especially since we should always fetch in 'groupcompress'
655
        #       order.
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
656
        return False
4665.3.4 by John Arbash Meinel
Refactor the check_rebuild code a bit, so that we can potentially
657
658
    def _check_rebuild_block(self):
4665.3.5 by John Arbash Meinel
Work out a heuristic about when a block is well utilized
659
        action, last_byte_used, total_bytes_used = self._check_rebuild_action()
4665.3.4 by John Arbash Meinel
Refactor the check_rebuild code a bit, so that we can potentially
660
        if action is None:
661
            return
662
        if action == 'trim':
663
            self._trim_block(last_byte_used)
664
        elif action == 'rebuild':
665
            self._rebuild_block()
666
        else:
667
            raise ValueError('unknown rebuild action: %r' % (action,))
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
668
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
669
    def _wire_bytes(self):
670
        """Return a byte stream suitable for transmitting over the wire."""
3735.32.24 by John Arbash Meinel
_wire_bytes() now strips groups as necessary, as does _insert_record_stream
671
        self._check_rebuild_block()
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
672
        # The outer block starts with:
673
        #   'groupcompress-block\n'
674
        #   <length of compressed key info>\n
675
        #   <length of uncompressed info>\n
676
        #   <length of gc block>\n
677
        #   <header bytes>
678
        #   <gc-block>
679
        lines = ['groupcompress-block\n']
680
        # The minimal info we need is the key, the start offset, and the
681
        # parents. The length and type are encoded in the record itself.
682
        # However, passing in the other bits makes it easier.  The list of
683
        # keys, and the start offset, the length
684
        # 1 line key
685
        # 1 line with parents, '' for ()
686
        # 1 line for start offset
687
        # 1 line for end byte
688
        header_lines = []
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
689
        for factory in self._factories:
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
690
            key_bytes = '\x00'.join(factory.key)
691
            parents = factory.parents
692
            if parents is None:
693
                parent_bytes = 'None:'
694
            else:
695
                parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
696
            record_header = '%s\n%s\n%d\n%d\n' % (
697
                key_bytes, parent_bytes, factory._start, factory._end)
698
            header_lines.append(record_header)
3735.37.5 by John Arbash Meinel
Restore the refcycle reduction code.
699
            # TODO: Can we break the refcycle at this point and set
700
            #       factory._manager = None?
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
701
        header_bytes = ''.join(header_lines)
702
        del header_lines
703
        header_bytes_len = len(header_bytes)
704
        z_header_bytes = zlib.compress(header_bytes)
705
        del header_bytes
706
        z_header_bytes_len = len(z_header_bytes)
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
707
        block_bytes_len, block_chunks = self._block.to_chunks()
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
708
        lines.append('%d\n%d\n%d\n' % (z_header_bytes_len, header_bytes_len,
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
709
                                       block_bytes_len))
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
710
        lines.append(z_header_bytes)
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
711
        lines.extend(block_chunks)
712
        del z_header_bytes, block_chunks
713
        # TODO: This is a point where we will double the memory consumption. To
714
        #       avoid this, we probably have to switch to a 'chunked' api
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
715
        return ''.join(lines)
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
716
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
717
    @classmethod
3735.32.18 by John Arbash Meinel
We now support generating a network stream.
718
    def from_bytes(cls, bytes):
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
719
        # TODO: This does extra string copying, probably better to do it a
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
720
        #       different way. At a minimum this creates 2 copies of the
721
        #       compressed content
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
722
        (storage_kind, z_header_len, header_len,
723
         block_len, rest) = bytes.split('\n', 4)
724
        del bytes
725
        if storage_kind != 'groupcompress-block':
726
            raise ValueError('Unknown storage kind: %s' % (storage_kind,))
727
        z_header_len = int(z_header_len)
728
        if len(rest) < z_header_len:
729
            raise ValueError('Compressed header len shorter than all bytes')
730
        z_header = rest[:z_header_len]
731
        header_len = int(header_len)
732
        header = zlib.decompress(z_header)
733
        if len(header) != header_len:
734
            raise ValueError('invalid length for decompressed bytes')
735
        del z_header
736
        block_len = int(block_len)
737
        if len(rest) != z_header_len + block_len:
738
            raise ValueError('Invalid length for block')
739
        block_bytes = rest[z_header_len:]
740
        del rest
741
        # So now we have a valid GCB, we just need to parse the factories that
742
        # were sent to us
743
        header_lines = header.split('\n')
744
        del header
745
        last = header_lines.pop()
746
        if last != '':
747
            raise ValueError('header lines did not end with a trailing'
748
                             ' newline')
749
        if len(header_lines) % 4 != 0:
750
            raise ValueError('The header was not an even multiple of 4 lines')
751
        block = GroupCompressBlock.from_bytes(block_bytes)
752
        del block_bytes
753
        result = cls(block)
754
        for start in xrange(0, len(header_lines), 4):
755
            # intern()?
756
            key = tuple(header_lines[start].split('\x00'))
757
            parents_line = header_lines[start+1]
758
            if parents_line == 'None:':
759
                parents = None
760
            else:
761
                parents = tuple([tuple(segment.split('\x00'))
762
                                 for segment in parents_line.split('\t')
763
                                  if segment])
764
            start_offset = int(header_lines[start+2])
765
            end_offset = int(header_lines[start+3])
766
            result.add_factory(key, parents, start_offset, end_offset)
767
        return result
768
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
769
3735.32.18 by John Arbash Meinel
We now support generating a network stream.
770
def network_block_to_records(storage_kind, bytes, line_end):
771
    if storage_kind != 'groupcompress-block':
772
        raise ValueError('Unknown storage kind: %s' % (storage_kind,))
773
    manager = _LazyGroupContentManager.from_bytes(bytes)
774
    return manager.get_record_stream()
775
776
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
777
class _CommonGroupCompressor(object):
778
779
    def __init__(self):
780
        """Create a GroupCompressor."""
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
781
        self.chunks = []
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
782
        self._last = None
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
783
        self.endpoint = 0
784
        self.input_bytes = 0
785
        self.labels_deltas = {}
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
786
        self._delta_index = None # Set by the children
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
787
        self._block = GroupCompressBlock()
788
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
789
    def compress(self, key, bytes, expected_sha, nostore_sha=None, soft=False):
790
        """Compress lines with label key.
791
792
        :param key: A key tuple. It is stored in the output
793
            for identification of the text during decompression. If the last
794
            element is 'None' it is replaced with the sha1 of the text -
795
            e.g. sha1:xxxxxxx.
796
        :param bytes: The bytes to be compressed
797
        :param expected_sha: If non-None, the sha the lines are believed to
798
            have. During compression the sha is calculated; a mismatch will
799
            cause an error.
800
        :param nostore_sha: If the computed sha1 sum matches, we will raise
801
            ExistingContent rather than adding the text.
802
        :param soft: Do a 'soft' compression. This means that we require larger
803
            ranges to match to be considered for a copy command.
804
805
        :return: The sha1 of lines, the start and end offsets in the delta, and
806
            the type ('fulltext' or 'delta').
807
808
        :seealso VersionedFiles.add_lines:
809
        """
810
        if not bytes: # empty, like a dir entry, etc
811
            if nostore_sha == _null_sha1:
812
                raise errors.ExistingContent()
813
            return _null_sha1, 0, 0, 'fulltext'
814
        # we assume someone knew what they were doing when they passed it in
815
        if expected_sha is not None:
816
            sha1 = expected_sha
817
        else:
818
            sha1 = osutils.sha_string(bytes)
819
        if nostore_sha is not None:
820
            if sha1 == nostore_sha:
821
                raise errors.ExistingContent()
822
        if key[-1] is None:
823
            key = key[:-1] + ('sha1:' + sha1,)
824
825
        start, end, type = self._compress(key, bytes, len(bytes) / 2, soft)
826
        return sha1, start, end, type
827
828
    def _compress(self, key, bytes, max_delta_size, soft=False):
829
        """Compress lines with label key.
830
831
        :param key: A key tuple. It is stored in the output for identification
832
            of the text during decompression.
833
834
        :param bytes: The bytes to be compressed
835
836
        :param max_delta_size: The size above which we issue a fulltext instead
837
            of a delta.
838
839
        :param soft: Do a 'soft' compression. This means that we require larger
840
            ranges to match to be considered for a copy command.
841
842
        :return: The sha1 of lines, the start and end offsets in the delta, and
843
            the type ('fulltext' or 'delta').
844
        """
845
        raise NotImplementedError(self._compress)
846
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
847
    def extract(self, key):
848
        """Extract a key previously added to the compressor.
849
850
        :param key: The key to extract.
851
        :return: An iterable over bytes and the sha1.
852
        """
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
853
        (start_byte, start_chunk, end_byte, end_chunk) = self.labels_deltas[key]
854
        delta_chunks = self.chunks[start_chunk:end_chunk]
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
855
        stored_bytes = ''.join(delta_chunks)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
856
        if stored_bytes[0] == 'f':
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
857
            fulltext_len, offset = decode_base128_int(stored_bytes[1:10])
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
858
            data_len = fulltext_len + 1 + offset
859
            if  data_len != len(stored_bytes):
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
860
                raise ValueError('Index claimed fulltext len, but stored bytes'
861
                                 ' claim %s != %s'
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
862
                                 % (len(stored_bytes), data_len))
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
863
            bytes = stored_bytes[offset + 1:]
864
        else:
865
            # XXX: This is inefficient at best
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
866
            source = ''.join(self.chunks[:start_chunk])
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
867
            if stored_bytes[0] != 'd':
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
868
                raise ValueError('Unknown content kind, bytes claim %s'
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
869
                                 % (stored_bytes[0],))
870
            delta_len, offset = decode_base128_int(stored_bytes[1:10])
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
871
            data_len = delta_len + 1 + offset
872
            if data_len != len(stored_bytes):
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
873
                raise ValueError('Index claimed delta len, but stored bytes'
874
                                 ' claim %s != %s'
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
875
                                 % (len(stored_bytes), data_len))
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
876
            bytes = apply_delta(source, stored_bytes[offset + 1:])
877
        bytes_sha1 = osutils.sha_string(bytes)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
878
        return bytes, bytes_sha1
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
879
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
880
    def flush(self):
881
        """Finish this group, creating a formatted stream.
882
883
        After calling this, the compressor should no longer be used
884
        """
4469.1.2 by John Arbash Meinel
The only caller already knows the content length, so make the api such that
885
        self._block.set_chunked_content(self.chunks, self.endpoint)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
886
        self.chunks = None
887
        self._delta_index = None
888
        return self._block
889
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
890
    def pop_last(self):
891
        """Call this if you want to 'revoke' the last compression.
892
893
        After this, the data structures will be rolled back, but you cannot do
894
        more compression.
895
        """
896
        self._delta_index = None
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
897
        del self.chunks[self._last[0]:]
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
898
        self.endpoint = self._last[1]
899
        self._last = None
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
900
901
    def ratio(self):
902
        """Return the overall compression ratio."""
903
        return float(self.input_bytes) / float(self.endpoint)
904
905
906
class PythonGroupCompressor(_CommonGroupCompressor):
907
3735.40.2 by John Arbash Meinel
Add a groupcompress.encode_copy_instruction function.
908
    def __init__(self):
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
909
        """Create a GroupCompressor.
910
911
        Used only if the pyrex version is not available.
912
        """
913
        super(PythonGroupCompressor, self).__init__()
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
914
        self._delta_index = LinesDeltaIndex([])
915
        # The actual content is managed by LinesDeltaIndex
916
        self.chunks = self._delta_index.lines
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
917
918
    def _compress(self, key, bytes, max_delta_size, soft=False):
919
        """see _CommonGroupCompressor._compress"""
920
        input_len = len(bytes)
3735.40.2 by John Arbash Meinel
Add a groupcompress.encode_copy_instruction function.
921
        new_lines = osutils.split_lines(bytes)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
922
        out_lines, index_lines = self._delta_index.make_delta(
923
            new_lines, bytes_length=input_len, soft=soft)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
924
        delta_length = sum(map(len, out_lines))
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
925
        if delta_length > max_delta_size:
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
926
            # The delta is longer than the fulltext, insert a fulltext
927
            type = 'fulltext'
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
928
            out_lines = ['f', encode_base128_int(input_len)]
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
929
            out_lines.extend(new_lines)
930
            index_lines = [False, False]
931
            index_lines.extend([True] * len(new_lines))
932
        else:
933
            # this is a worthy delta, output it
934
            type = 'delta'
935
            out_lines[0] = 'd'
936
            # Update the delta_length to include those two encoded integers
937
            out_lines[1] = encode_base128_int(delta_length)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
938
        # Before insertion
939
        start = self.endpoint
940
        chunk_start = len(self.chunks)
4241.17.2 by John Arbash Meinel
PythonGroupCompressor needs to support pop_last() properly.
941
        self._last = (chunk_start, self.endpoint)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
942
        self._delta_index.extend_lines(out_lines, index_lines)
943
        self.endpoint = self._delta_index.endpoint
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
944
        self.input_bytes += input_len
945
        chunk_end = len(self.chunks)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
946
        self.labels_deltas[key] = (start, chunk_start,
947
                                   self.endpoint, chunk_end)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
948
        return start, self.endpoint, type
949
950
951
class PyrexGroupCompressor(_CommonGroupCompressor):
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
952
    """Produce a serialised group of compressed texts.
0.23.6 by John Arbash Meinel
Start stripping out the actual GroupCompressor
953
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
954
    It contains code very similar to SequenceMatcher because of having a similar
955
    task. However some key differences apply:
956
     - there is no junk, we want a minimal edit not a human readable diff.
957
     - we don't filter very common lines (because we don't know where a good
958
       range will start, and after the first text we want to be emitting minmal
959
       edits only.
960
     - we chain the left side, not the right side
961
     - we incrementally update the adjacency matrix as new lines are provided.
962
     - we look for matches in all of the left side, so the routine which does
963
       the analagous task of find_longest_match does not need to filter on the
964
       left side.
965
    """
0.17.2 by Robert Collins
Core proof of concept working.
966
3735.32.19 by John Arbash Meinel
Get rid of the 'delta' flag to GroupCompressor. It didn't do anything anyway.
967
    def __init__(self):
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
968
        super(PyrexGroupCompressor, self).__init__()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
969
        self._delta_index = DeltaIndex()
0.23.6 by John Arbash Meinel
Start stripping out the actual GroupCompressor
970
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
971
    def _compress(self, key, bytes, max_delta_size, soft=False):
972
        """see _CommonGroupCompressor._compress"""
0.23.52 by John Arbash Meinel
Use the max_delta flag.
973
        input_len = len(bytes)
0.23.12 by John Arbash Meinel
Add a 'len:' field to the data.
974
        # By having action/label/sha1/len, we can parse the group if the index
975
        # was ever destroyed, we have the key in 'label', we know the final
976
        # bytes are valid from sha1, and we know where to find the end of this
977
        # record because of 'len'. (the delta record itself will store the
978
        # total length for the expanded record)
0.23.13 by John Arbash Meinel
Factor out the ability to have/not have labels.
979
        # 'len: %d\n' costs approximately 1% increase in total data
980
        # Having the labels at all costs us 9-10% increase, 38% increase for
981
        # inventory pages, and 5.8% increase for text pages
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
982
        # new_chunks = ['label:%s\nsha1:%s\n' % (label, sha1)]
0.23.33 by John Arbash Meinel
Fix a bug when handling multiple large-range copies.
983
        if self._delta_index._source_offset != self.endpoint:
984
            raise AssertionError('_source_offset != endpoint'
985
                ' somehow the DeltaIndex got out of sync with'
986
                ' the output lines')
0.23.52 by John Arbash Meinel
Use the max_delta flag.
987
        delta = self._delta_index.make_delta(bytes, max_delta_size)
988
        if (delta is None):
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
989
            type = 'fulltext'
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
990
            enc_length = encode_base128_int(len(bytes))
991
            len_mini_header = 1 + len(enc_length)
992
            self._delta_index.add_source(bytes, len_mini_header)
993
            new_chunks = ['f', enc_length, bytes]
0.23.9 by John Arbash Meinel
We now basically have full support for using diff-delta as the compressor.
994
        else:
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
995
            type = 'delta'
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
996
            enc_length = encode_base128_int(len(delta))
997
            len_mini_header = 1 + len(enc_length)
998
            new_chunks = ['d', enc_length, delta]
3735.38.5 by John Arbash Meinel
A bit of testing showed that _FAST=True was actually *slower*.
999
            self._delta_index.add_delta_source(delta, len_mini_header)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1000
        # Before insertion
1001
        start = self.endpoint
1002
        chunk_start = len(self.chunks)
1003
        # Now output these bytes
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
1004
        self._output_chunks(new_chunks)
0.23.6 by John Arbash Meinel
Start stripping out the actual GroupCompressor
1005
        self.input_bytes += input_len
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1006
        chunk_end = len(self.chunks)
1007
        self.labels_deltas[key] = (start, chunk_start,
1008
                                   self.endpoint, chunk_end)
0.23.29 by John Arbash Meinel
Forgot to add the delta bytes to the index objects.
1009
        if not self._delta_index._source_offset == self.endpoint:
1010
            raise AssertionError('the delta index is out of sync'
1011
                'with the output lines %s != %s'
1012
                % (self._delta_index._source_offset, self.endpoint))
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1013
        return start, self.endpoint, type
0.17.2 by Robert Collins
Core proof of concept working.
1014
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
1015
    def _output_chunks(self, new_chunks):
0.23.9 by John Arbash Meinel
We now basically have full support for using diff-delta as the compressor.
1016
        """Output some chunks.
1017
1018
        :param new_chunks: The chunks to output.
1019
        """
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
1020
        self._last = (len(self.chunks), self.endpoint)
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
1021
        endpoint = self.endpoint
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
1022
        self.chunks.extend(new_chunks)
0.23.9 by John Arbash Meinel
We now basically have full support for using diff-delta as the compressor.
1023
        endpoint += sum(map(len, new_chunks))
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
1024
        self.endpoint = endpoint
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
1025
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
1026
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1027
def make_pack_factory(graph, delta, keylength, inconsistency_fatal=True):
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1028
    """Create a factory for creating a pack based groupcompress.
1029
1030
    This is only functional enough to run interface tests, it doesn't try to
1031
    provide a full pack environment.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1032
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1033
    :param graph: Store a graph.
1034
    :param delta: Delta compress contents.
1035
    :param keylength: How long should keys be.
1036
    """
1037
    def factory(transport):
3735.32.2 by John Arbash Meinel
The 'delta' flag has no effect on the content (all GC is delta'd),
1038
        parents = graph
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1039
        ref_length = 0
1040
        if graph:
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1041
            ref_length = 1
0.17.7 by Robert Collins
Update for current index2 changes.
1042
        graph_index = BTreeBuilder(reference_lists=ref_length,
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1043
            key_elements=keylength)
1044
        stream = transport.open_write_stream('newpack')
1045
        writer = pack.ContainerWriter(stream.write)
1046
        writer.begin()
1047
        index = _GCGraphIndex(graph_index, lambda:True, parents=parents,
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1048
            add_callback=graph_index.add_nodes,
1049
            inconsistency_fatal=inconsistency_fatal)
5757.5.1 by Jelmer Vernooij
Move _DirectPackAccess to bzrlib.repofmt.pack_repo.
1050
        access = pack_repo._DirectPackAccess({})
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1051
        access.set_writer(writer, graph_index, (transport, 'newpack'))
0.17.2 by Robert Collins
Core proof of concept working.
1052
        result = GroupCompressVersionedFiles(index, access, delta)
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1053
        result.stream = stream
1054
        result.writer = writer
1055
        return result
1056
    return factory
1057
1058
1059
def cleanup_pack_group(versioned_files):
0.17.23 by Robert Collins
Only decompress as much of the zlib data as is needed to read the text recipe.
1060
    versioned_files.writer.end()
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1061
    versioned_files.stream.close()
1062
1063
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1064
class _BatchingBlockFetcher(object):
1065
    """Fetch group compress blocks in batches.
1066
    
1067
    :ivar total_bytes: int of expected number of bytes needed to fetch the
1068
        currently pending batch.
1069
    """
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1070
1071
    def __init__(self, gcvf, locations):
1072
        self.gcvf = gcvf
1073
        self.locations = locations
1074
        self.keys = []
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1075
        self.batch_memos = {}
1076
        self.memos_to_get = []
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1077
        self.total_bytes = 0
1078
        self.last_read_memo = None
1079
        self.manager = None
1080
1081
    def add_key(self, key):
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1082
        """Add another to key to fetch.
1083
        
1084
        :return: The estimated number of bytes needed to fetch the batch so
1085
            far.
1086
        """
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1087
        self.keys.append(key)
1088
        index_memo, _, _, _ = self.locations[key]
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1089
        read_memo = index_memo[0:3]
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1090
        # Three possibilities for this read_memo:
1091
        #  - it's already part of this batch; or
1092
        #  - it's not yet part of this batch, but is already cached; or
1093
        #  - it's not yet part of this batch and will need to be fetched.
1094
        if read_memo in self.batch_memos:
1095
            # This read memo is already in this batch.
4634.3.16 by Andrew Bennetts
Fix buglets.
1096
            return self.total_bytes
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1097
        try:
1098
            cached_block = self.gcvf._group_cache[read_memo]
1099
        except KeyError:
1100
            # This read memo is new to this batch, and the data isn't cached
1101
            # either.
1102
            self.batch_memos[read_memo] = None
1103
            self.memos_to_get.append(read_memo)
4634.3.12 by Andrew Bennetts
Bump up the batch size to 256k, and fix the batch size estimate to use the length of the raw bytes that will be fetched (not the uncompressed bytes).
1104
            byte_length = read_memo[2]
1105
            self.total_bytes += byte_length
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1106
        else:
1107
            # This read memo is new to this batch, but cached.
1108
            # Keep a reference to the cached block in batch_memos because it's
1109
            # certain that we'll use it when this batch is processed, but
1110
            # there's a risk that it would fall out of _group_cache between now
1111
            # and then.
1112
            self.batch_memos[read_memo] = cached_block
1113
        return self.total_bytes
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1114
        
4634.3.13 by Andrew Bennetts
Rename empty_manager to _flush_manager.
1115
    def _flush_manager(self):
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1116
        if self.manager is not None:
1117
            for factory in self.manager.get_record_stream():
1118
                yield factory
1119
            self.manager = None
4634.3.4 by Andrew Bennetts
Decruftify a little more.
1120
            self.last_read_memo = None
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1121
1122
    def yield_factories(self, full_flush=False):
4634.3.5 by Andrew Bennetts
More docstrings.
1123
        """Yield factories for keys added since the last yield.  They will be
1124
        returned in the order they were added via add_key.
1125
        
1126
        :param full_flush: by default, some results may not be returned in case
1127
            they can be part of the next batch.  If full_flush is True, then
1128
            all results are returned.
1129
        """
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1130
        if self.manager is None and not self.keys:
1131
            return
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1132
        # Fetch all memos in this batch.
1133
        blocks = self.gcvf._get_blocks(self.memos_to_get)
1134
        # Turn blocks into factories and yield them.
1135
        memos_to_get_stack = list(self.memos_to_get)
1136
        memos_to_get_stack.reverse()
4634.3.2 by Andrew Bennetts
Stop using (and remove) unnecessary key_batch var that was causing a bug.
1137
        for key in self.keys:
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1138
            index_memo, _, parents, _ = self.locations[key]
1139
            read_memo = index_memo[:3]
4634.3.4 by Andrew Bennetts
Decruftify a little more.
1140
            if self.last_read_memo != read_memo:
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1141
                # We are starting a new block. If we have a
1142
                # manager, we have found everything that fits for
1143
                # now, so yield records
4634.3.13 by Andrew Bennetts
Rename empty_manager to _flush_manager.
1144
                for factory in self._flush_manager():
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1145
                    yield factory
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1146
                # Now start a new manager.
1147
                if memos_to_get_stack and memos_to_get_stack[-1] == read_memo:
1148
                    # The next block from _get_blocks will be the block we
1149
                    # need.
1150
                    block_read_memo, block = blocks.next()
1151
                    if block_read_memo != read_memo:
1152
                        raise AssertionError(
4634.3.16 by Andrew Bennetts
Fix buglets.
1153
                            "block_read_memo out of sync with read_memo"
1154
                            "(%r != %r)" % (block_read_memo, read_memo))
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1155
                    self.batch_memos[read_memo] = block
1156
                    memos_to_get_stack.pop()
1157
                else:
1158
                    block = self.batch_memos[read_memo]
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1159
                self.manager = _LazyGroupContentManager(block)
4634.3.4 by Andrew Bennetts
Decruftify a little more.
1160
                self.last_read_memo = read_memo
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1161
            start, end = index_memo[3:5]
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1162
            self.manager.add_factory(key, parents, start, end)
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1163
        if full_flush:
4634.3.13 by Andrew Bennetts
Rename empty_manager to _flush_manager.
1164
            for factory in self._flush_manager():
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1165
                yield factory
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1166
        del self.keys[:]
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1167
        self.batch_memos.clear()
1168
        del self.memos_to_get[:]
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1169
        self.total_bytes = 0
1170
1171
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1172
class GroupCompressVersionedFiles(VersionedFiles):
1173
    """A group-compress based VersionedFiles implementation."""
1174
4634.35.10 by Andrew Bennetts
Move tests to per_repository_chk.
1175
    def __init__(self, index, access, delta=True, _unadded_refs=None):
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1176
        """Create a GroupCompressVersionedFiles object.
1177
1178
        :param index: The index object storing access and graph data.
1179
        :param access: The access object storing raw data.
0.17.2 by Robert Collins
Core proof of concept working.
1180
        :param delta: Whether to delta compress or just entropy compress.
4634.35.10 by Andrew Bennetts
Move tests to per_repository_chk.
1181
        :param _unadded_refs: private parameter, don't use.
0.17.2 by Robert Collins
Core proof of concept working.
1182
        """
1183
        self._index = index
1184
        self._access = access
1185
        self._delta = delta
4634.35.10 by Andrew Bennetts
Move tests to per_repository_chk.
1186
        if _unadded_refs is None:
1187
            _unadded_refs = {}
1188
        self._unadded_refs = _unadded_refs
0.17.24 by Robert Collins
Add a group cache to decompression, 5 times faster than knit at decompression when accessing everything in a group.
1189
        self._group_cache = LRUSizeCache(max_size=50*1024*1024)
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1190
        self._immediate_fallback_vfs = []
0.17.2 by Robert Collins
Core proof of concept working.
1191
4634.35.1 by Andrew Bennetts
Check for all necessary chk nodes, not just roots.
1192
    def without_fallbacks(self):
4634.35.10 by Andrew Bennetts
Move tests to per_repository_chk.
1193
        """Return a clone of this object without any fallbacks configured."""
1194
        return GroupCompressVersionedFiles(self._index, self._access,
1195
            self._delta, _unadded_refs=dict(self._unadded_refs))
4634.35.1 by Andrew Bennetts
Check for all necessary chk nodes, not just roots.
1196
0.17.2 by Robert Collins
Core proof of concept working.
1197
    def add_lines(self, key, parents, lines, parent_texts=None,
1198
        left_matching_blocks=None, nostore_sha=None, random_id=False,
1199
        check_content=True):
1200
        """Add a text to the store.
1201
1202
        :param key: The key tuple of the text to add.
1203
        :param parents: The parents key tuples of the text to add.
1204
        :param lines: A list of lines. Each line must be a bytestring. And all
1205
            of them except the last must be terminated with \n and contain no
1206
            other \n's. The last line may either contain no \n's or a single
1207
            terminating \n. If the lines list does meet this constraint the add
1208
            routine may error or may succeed - but you will be unable to read
1209
            the data back accurately. (Checking the lines have been split
1210
            correctly is expensive and extremely unlikely to catch bugs so it
1211
            is not done at runtime unless check_content is True.)
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1212
        :param parent_texts: An optional dictionary containing the opaque
0.17.2 by Robert Collins
Core proof of concept working.
1213
            representations of some or all of the parents of version_id to
1214
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
1215
            returned by add_lines or data corruption can be caused.
1216
        :param left_matching_blocks: a hint about which areas are common
1217
            between the text and its left-hand-parent.  The format is
1218
            the SequenceMatcher.get_matching_blocks format.
1219
        :param nostore_sha: Raise ExistingContent and do not add the lines to
1220
            the versioned file if the digest of the lines matches this.
1221
        :param random_id: If True a random id has been selected rather than
1222
            an id determined by some deterministic process such as a converter
1223
            from a foreign VCS. When True the backend may choose not to check
1224
            for uniqueness of the resulting key within the versioned file, so
1225
            this should only be done when the result is expected to be unique
1226
            anyway.
1227
        :param check_content: If True, the lines supplied are verified to be
1228
            bytestrings that are correctly formed lines.
1229
        :return: The text sha1, the number of bytes in the text, and an opaque
1230
                 representation of the inserted version which can be provided
1231
                 back to future add_lines calls in the parent_texts dictionary.
1232
        """
1233
        self._index._check_write_ok()
1234
        self._check_add(key, lines, random_id, check_content)
1235
        if parents is None:
1236
            # The caller might pass None if there is no graph data, but kndx
1237
            # indexes can't directly store that, so we give them
1238
            # an empty tuple instead.
1239
            parents = ()
1240
        # double handling for now. Make it work until then.
0.20.5 by John Arbash Meinel
Finish the Fulltext => Chunked conversions so that we work in the more-efficient Chunks.
1241
        length = sum(map(len, lines))
1242
        record = ChunkedContentFactory(key, parents, None, lines)
3735.31.12 by John Arbash Meinel
Push nostore_sha down through the stack.
1243
        sha1 = list(self._insert_record_stream([record], random_id=random_id,
1244
                                               nostore_sha=nostore_sha))[0]
0.20.5 by John Arbash Meinel
Finish the Fulltext => Chunked conversions so that we work in the more-efficient Chunks.
1245
        return sha1, length, None
0.17.2 by Robert Collins
Core proof of concept working.
1246
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
1247
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
4398.9.1 by Matt Nordhoff
Update _add_text docstrings that still referred to add_text.
1248
        """See VersionedFiles._add_text()."""
4398.8.4 by John Arbash Meinel
Implement add_text for GroupCompressVersionedFiles
1249
        self._index._check_write_ok()
1250
        self._check_add(key, None, random_id, check_content=False)
1251
        if text.__class__ is not str:
1252
            raise errors.BzrBadParameterUnicode("text")
1253
        if parents is None:
1254
            # The caller might pass None if there is no graph data, but kndx
1255
            # indexes can't directly store that, so we give them
1256
            # an empty tuple instead.
1257
            parents = ()
1258
        # double handling for now. Make it work until then.
1259
        length = len(text)
1260
        record = FulltextContentFactory(key, parents, None, text)
1261
        sha1 = list(self._insert_record_stream([record], random_id=random_id,
1262
                                               nostore_sha=nostore_sha))[0]
1263
        return sha1, length, None
1264
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1265
    def add_fallback_versioned_files(self, a_versioned_files):
1266
        """Add a source of texts for texts not present in this knit.
1267
1268
        :param a_versioned_files: A VersionedFiles object.
1269
        """
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1270
        self._immediate_fallback_vfs.append(a_versioned_files)
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1271
0.17.4 by Robert Collins
Annotate.
1272
    def annotate(self, key):
1273
        """See VersionedFiles.annotate."""
4454.3.58 by John Arbash Meinel
Enable the new annotator for gc format repos.
1274
        ann = annotate.Annotator(self)
1275
        return ann.annotate_flat(key)
0.17.4 by Robert Collins
Annotate.
1276
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
1277
    def get_annotator(self):
1278
        return annotate.Annotator(self)
1279
4332.3.28 by Robert Collins
Start checking file texts in a single pass.
1280
    def check(self, progress_bar=None, keys=None):
0.17.5 by Robert Collins
nograph tests completely passing.
1281
        """See VersionedFiles.check()."""
4332.3.28 by Robert Collins
Start checking file texts in a single pass.
1282
        if keys is None:
1283
            keys = self.keys()
1284
            for record in self.get_record_stream(keys, 'unordered', True):
1285
                record.get_bytes_as('fulltext')
1286
        else:
1287
            return self.get_record_stream(keys, 'unordered', True)
0.17.5 by Robert Collins
nograph tests completely passing.
1288
4744.2.5 by John Arbash Meinel
Change to a generic 'VersionedFiles.clear_cache()' api.
1289
    def clear_cache(self):
1290
        """See VersionedFiles.clear_cache()"""
1291
        self._group_cache.clear()
4744.2.7 by John Arbash Meinel
Add .clear_cache() members to GraphIndexBuilder and BTreeBuilder.
1292
        self._index._graph_index.clear_cache()
4679.9.19 by John Arbash Meinel
Interning the start and stop group positions saves another 7MB peak mem. \o/
1293
        self._index._int_cache.clear()
4744.2.5 by John Arbash Meinel
Change to a generic 'VersionedFiles.clear_cache()' api.
1294
0.17.2 by Robert Collins
Core proof of concept working.
1295
    def _check_add(self, key, lines, random_id, check_content):
1296
        """check that version_id and lines are safe to add."""
1297
        version_id = key[-1]
0.17.26 by Robert Collins
Working better --gc-plain-chk.
1298
        if version_id is not None:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1299
            if osutils.contains_whitespace(version_id):
3735.31.1 by John Arbash Meinel
Bring the groupcompress plugin into the brisbane-core branch.
1300
                raise errors.InvalidRevisionId(version_id, self)
0.17.2 by Robert Collins
Core proof of concept working.
1301
        self.check_not_reserved_id(version_id)
1302
        # TODO: If random_id==False and the key is already present, we should
1303
        # probably check that the existing content is identical to what is
1304
        # being inserted, and otherwise raise an exception.  This would make
1305
        # the bundle code simpler.
1306
        if check_content:
1307
            self._check_lines_not_unicode(lines)
1308
            self._check_lines_are_lines(lines)
1309
4593.5.20 by John Arbash Meinel
Expose KnownGraph off of VersionedFiles
1310
    def get_known_graph_ancestry(self, keys):
1311
        """Get a KnownGraph instance with the ancestry of keys."""
4634.11.2 by John Arbash Meinel
Teach VF.get_known_graph_ancestry to go to fallbacks (bug #419241)
1312
        # Note that this is identical to
1313
        # KnitVersionedFiles.get_known_graph_ancestry, but they don't share
1314
        # ancestry.
4634.11.3 by John Arbash Meinel
Implement _GCGraphIndex.find_ancestry()
1315
        parent_map, missing_keys = self._index.find_ancestry(keys)
5050.70.2 by Martin Pool
Search all fallbacks for get_known_graph_ancestry
1316
        for fallback in self._transitive_fallbacks():
4634.11.2 by John Arbash Meinel
Teach VF.get_known_graph_ancestry to go to fallbacks (bug #419241)
1317
            if not missing_keys:
1318
                break
4634.11.3 by John Arbash Meinel
Implement _GCGraphIndex.find_ancestry()
1319
            (f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
1320
                                                missing_keys)
4634.11.2 by John Arbash Meinel
Teach VF.get_known_graph_ancestry to go to fallbacks (bug #419241)
1321
            parent_map.update(f_parent_map)
1322
            missing_keys = f_missing_keys
4593.5.20 by John Arbash Meinel
Expose KnownGraph off of VersionedFiles
1323
        kg = _mod_graph.KnownGraph(parent_map)
1324
        return kg
1325
0.17.5 by Robert Collins
nograph tests completely passing.
1326
    def get_parent_map(self, keys):
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1327
        """Get a map of the graph parents of keys.
0.17.5 by Robert Collins
nograph tests completely passing.
1328
1329
        :param keys: The keys to look up parents for.
1330
        :return: A mapping from keys to parents. Absent keys are absent from
1331
            the mapping.
1332
        """
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1333
        return self._get_parent_map_with_sources(keys)[0]
1334
1335
    def _get_parent_map_with_sources(self, keys):
1336
        """Get a map of the parents of keys.
1337
1338
        :param keys: The keys to look up parents for.
1339
        :return: A tuple. The first element is a mapping from keys to parents.
1340
            Absent keys are absent from the mapping. The second element is a
1341
            list with the locations each key was found in. The first element
1342
            is the in-this-knit parents, the second the first fallback source,
1343
            and so on.
1344
        """
0.17.5 by Robert Collins
nograph tests completely passing.
1345
        result = {}
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1346
        sources = [self._index] + self._immediate_fallback_vfs
0.17.5 by Robert Collins
nograph tests completely passing.
1347
        source_results = []
1348
        missing = set(keys)
1349
        for source in sources:
1350
            if not missing:
1351
                break
1352
            new_result = source.get_parent_map(missing)
1353
            source_results.append(new_result)
1354
            result.update(new_result)
1355
            missing.difference_update(set(new_result))
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1356
        return result, source_results
0.17.5 by Robert Collins
nograph tests completely passing.
1357
4634.3.11 by Andrew Bennetts
Simplify further, comment more.
1358
    def _get_blocks(self, read_memos):
1359
        """Get GroupCompressBlocks for the given read_memos.
1360
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1361
        :returns: a series of (read_memo, block) pairs, in the order they were
1362
            originally passed.
4634.3.11 by Andrew Bennetts
Simplify further, comment more.
1363
        """
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1364
        cached = {}
1365
        for read_memo in read_memos:
1366
            try:
1367
                block = self._group_cache[read_memo]
1368
            except KeyError:
1369
                pass
1370
            else:
1371
                cached[read_memo] = block
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1372
        not_cached = []
1373
        not_cached_seen = set()
1374
        for read_memo in read_memos:
1375
            if read_memo in cached:
1376
                # Don't fetch what we already have
1377
                continue
1378
            if read_memo in not_cached_seen:
1379
                # Don't try to fetch the same data twice
1380
                continue
1381
            not_cached.append(read_memo)
1382
            not_cached_seen.add(read_memo)
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1383
        raw_records = self._access.get_raw_records(not_cached)
1384
        for read_memo in read_memos:
1385
            try:
4634.3.16 by Andrew Bennetts
Fix buglets.
1386
                yield read_memo, cached[read_memo]
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1387
            except KeyError:
4634.3.15 by Andrew Bennetts
Get rid of inaccurate comment.
1388
                # Read the block, and cache it.
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1389
                zdata = raw_records.next()
1390
                block = GroupCompressBlock.from_bytes(zdata)
1391
                self._group_cache[read_memo] = block
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1392
                cached[read_memo] = block
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1393
                yield read_memo, block
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1394
0.20.18 by John Arbash Meinel
Implement new handling of get_bytes_as(), and get_missing_compression_parent_keys()
1395
    def get_missing_compression_parent_keys(self):
1396
        """Return the keys of missing compression parents.
1397
1398
        Missing compression parents occur when a record stream was missing
1399
        basis texts, or a index was scanned that had missing basis texts.
1400
        """
1401
        # GroupCompress cannot currently reference texts that are not in the
1402
        # group, so this is valid for now
1403
        return frozenset()
1404
0.17.5 by Robert Collins
nograph tests completely passing.
1405
    def get_record_stream(self, keys, ordering, include_delta_closure):
1406
        """Get a stream of records for keys.
1407
1408
        :param keys: The keys to include.
1409
        :param ordering: Either 'unordered' or 'topological'. A topologically
1410
            sorted stream has compression parents strictly before their
1411
            children.
1412
        :param include_delta_closure: If True then the closure across any
1413
            compression parents will be included (in the opaque data).
1414
        :return: An iterator of ContentFactory objects, each of which is only
1415
            valid until the iterator is advanced.
1416
        """
1417
        # keys might be a generator
0.22.6 by John Arbash Meinel
Clustering chk pages properly makes a big difference.
1418
        orig_keys = list(keys)
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1419
        keys = set(keys)
0.17.5 by Robert Collins
nograph tests completely passing.
1420
        if not keys:
1421
            return
0.20.23 by John Arbash Meinel
Add a progress indicator for chk pages.
1422
        if (not self._index.has_graph
3735.31.14 by John Arbash Meinel
Change the gc-optimal to 'groupcompress'
1423
            and ordering in ('topological', 'groupcompress')):
0.17.5 by Robert Collins
nograph tests completely passing.
1424
            # Cannot topological order when no graph has been stored.
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1425
            # but we allow 'as-requested' or 'unordered'
0.17.5 by Robert Collins
nograph tests completely passing.
1426
            ordering = 'unordered'
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1427
1428
        remaining_keys = keys
1429
        while True:
1430
            try:
1431
                keys = set(remaining_keys)
1432
                for content_factory in self._get_remaining_record_stream(keys,
1433
                        orig_keys, ordering, include_delta_closure):
1434
                    remaining_keys.discard(content_factory.key)
1435
                    yield content_factory
1436
                return
1437
            except errors.RetryWithNewPacks, e:
1438
                self._access.reload_or_raise(e)
1439
1440
    def _find_from_fallback(self, missing):
1441
        """Find whatever keys you can from the fallbacks.
1442
1443
        :param missing: A set of missing keys. This set will be mutated as keys
1444
            are found from a fallback_vfs
1445
        :return: (parent_map, key_to_source_map, source_results)
1446
            parent_map  the overall key => parent_keys
1447
            key_to_source_map   a dict from {key: source}
1448
            source_results      a list of (source: keys)
1449
        """
1450
        parent_map = {}
1451
        key_to_source_map = {}
1452
        source_results = []
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1453
        for source in self._immediate_fallback_vfs:
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1454
            if not missing:
1455
                break
1456
            source_parents = source.get_parent_map(missing)
1457
            parent_map.update(source_parents)
1458
            source_parents = list(source_parents)
1459
            source_results.append((source, source_parents))
1460
            key_to_source_map.update((key, source) for key in source_parents)
1461
            missing.difference_update(source_parents)
1462
        return parent_map, key_to_source_map, source_results
1463
1464
    def _get_ordered_source_keys(self, ordering, parent_map, key_to_source_map):
1465
        """Get the (source, [keys]) list.
1466
1467
        The returned objects should be in the order defined by 'ordering',
1468
        which can weave between different sources.
1469
        :param ordering: Must be one of 'topological' or 'groupcompress'
1470
        :return: List of [(source, [keys])] tuples, such that all keys are in
1471
            the defined order, regardless of source.
1472
        """
1473
        if ordering == 'topological':
1474
            present_keys = topo_sort(parent_map)
1475
        else:
1476
            # ordering == 'groupcompress'
1477
            # XXX: This only optimizes for the target ordering. We may need
1478
            #      to balance that with the time it takes to extract
1479
            #      ordering, by somehow grouping based on
1480
            #      locations[key][0:3]
1481
            present_keys = sort_gc_optimal(parent_map)
1482
        # Now group by source:
1483
        source_keys = []
1484
        current_source = None
1485
        for key in present_keys:
1486
            source = key_to_source_map.get(key, self)
1487
            if source is not current_source:
1488
                source_keys.append((source, []))
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
1489
                current_source = source
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1490
            source_keys[-1][1].append(key)
1491
        return source_keys
1492
1493
    def _get_as_requested_source_keys(self, orig_keys, locations, unadded_keys,
1494
                                      key_to_source_map):
1495
        source_keys = []
1496
        current_source = None
1497
        for key in orig_keys:
1498
            if key in locations or key in unadded_keys:
1499
                source = self
1500
            elif key in key_to_source_map:
1501
                source = key_to_source_map[key]
1502
            else: # absent
1503
                continue
1504
            if source is not current_source:
1505
                source_keys.append((source, []))
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
1506
                current_source = source
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1507
            source_keys[-1][1].append(key)
1508
        return source_keys
1509
1510
    def _get_io_ordered_source_keys(self, locations, unadded_keys,
1511
                                    source_result):
1512
        def get_group(key):
1513
            # This is the group the bytes are stored in, followed by the
1514
            # location in the group
1515
            return locations[key][0]
1516
        present_keys = sorted(locations.iterkeys(), key=get_group)
1517
        # We don't have an ordering for keys in the in-memory object, but
1518
        # lets process the in-memory ones first.
1519
        present_keys = list(unadded_keys) + present_keys
1520
        # Now grab all of the ones from other sources
1521
        source_keys = [(self, present_keys)]
1522
        source_keys.extend(source_result)
1523
        return source_keys
1524
1525
    def _get_remaining_record_stream(self, keys, orig_keys, ordering,
1526
                                     include_delta_closure):
1527
        """Get a stream of records for keys.
1528
1529
        :param keys: The keys to include.
1530
        :param ordering: one of 'unordered', 'topological', 'groupcompress' or
1531
            'as-requested'
1532
        :param include_delta_closure: If True then the closure across any
1533
            compression parents will be included (in the opaque data).
1534
        :return: An iterator of ContentFactory objects, each of which is only
1535
            valid until the iterator is advanced.
1536
        """
0.17.5 by Robert Collins
nograph tests completely passing.
1537
        # Cheap: iterate
1538
        locations = self._index.get_build_details(keys)
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1539
        unadded_keys = set(self._unadded_refs).intersection(keys)
1540
        missing = keys.difference(locations)
1541
        missing.difference_update(unadded_keys)
1542
        (fallback_parent_map, key_to_source_map,
1543
         source_result) = self._find_from_fallback(missing)
1544
        if ordering in ('topological', 'groupcompress'):
0.17.5 by Robert Collins
nograph tests completely passing.
1545
            # would be better to not globally sort initially but instead
1546
            # start with one key, recurse to its oldest parent, then grab
1547
            # everything in the same group, etc.
1548
            parent_map = dict((key, details[2]) for key, details in
1549
                locations.iteritems())
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1550
            for key in unadded_keys:
1551
                parent_map[key] = self._unadded_refs[key]
1552
            parent_map.update(fallback_parent_map)
1553
            source_keys = self._get_ordered_source_keys(ordering, parent_map,
1554
                                                        key_to_source_map)
0.22.6 by John Arbash Meinel
Clustering chk pages properly makes a big difference.
1555
        elif ordering == 'as-requested':
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1556
            source_keys = self._get_as_requested_source_keys(orig_keys,
1557
                locations, unadded_keys, key_to_source_map)
0.17.5 by Robert Collins
nograph tests completely passing.
1558
        else:
0.20.10 by John Arbash Meinel
Change the extraction ordering for 'unordered'.
1559
            # We want to yield the keys in a semi-optimal (read-wise) ordering.
1560
            # Otherwise we thrash the _group_cache and destroy performance
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1561
            source_keys = self._get_io_ordered_source_keys(locations,
1562
                unadded_keys, source_result)
1563
        for key in missing:
0.17.5 by Robert Collins
nograph tests completely passing.
1564
            yield AbsentContentFactory(key)
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1565
        # Batch up as many keys as we can until either:
1566
        #  - we encounter an unadded ref, or
1567
        #  - we run out of keys, or
4634.3.17 by Andrew Bennetts
Make BATCH_SIZE a global.
1568
        #  - the total bytes to retrieve for this batch > BATCH_SIZE
4634.3.3 by Andrew Bennetts
Fix bug, add docstrings, improve clarity.
1569
        batcher = _BatchingBlockFetcher(self, locations)
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1570
        for source, keys in source_keys:
1571
            if source is self:
1572
                for key in keys:
1573
                    if key in self._unadded_refs:
4634.3.8 by Andrew Bennetts
Tweak some comments.
1574
                        # Flush batch, then yield unadded ref from
1575
                        # self._compressor.
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1576
                        for factory in batcher.yield_factories(full_flush=True):
1577
                            yield factory
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1578
                        bytes, sha1 = self._compressor.extract(key)
1579
                        parents = self._unadded_refs[key]
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
1580
                        yield FulltextContentFactory(key, parents, sha1, bytes)
4634.3.1 by Andrew Bennetts
Add some batching to _get_remaining_record_stream.
1581
                        continue
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1582
                    if batcher.add_key(key) > BATCH_SIZE:
4634.3.8 by Andrew Bennetts
Tweak some comments.
1583
                        # Ok, this batch is big enough.  Yield some results.
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1584
                        for factory in batcher.yield_factories():
1585
                            yield factory
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
1586
            else:
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1587
                for factory in batcher.yield_factories(full_flush=True):
1588
                    yield factory
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1589
                for record in source.get_record_stream(keys, ordering,
1590
                                                       include_delta_closure):
1591
                    yield record
4634.3.14 by Andrew Bennetts
Some changes prompted by John's review.
1592
        for factory in batcher.yield_factories(full_flush=True):
1593
            yield factory
0.20.5 by John Arbash Meinel
Finish the Fulltext => Chunked conversions so that we work in the more-efficient Chunks.
1594
0.17.5 by Robert Collins
nograph tests completely passing.
1595
    def get_sha1s(self, keys):
1596
        """See VersionedFiles.get_sha1s()."""
1597
        result = {}
1598
        for record in self.get_record_stream(keys, 'unordered', True):
1599
            if record.sha1 != None:
1600
                result[record.key] = record.sha1
1601
            else:
1602
                if record.storage_kind != 'absent':
3735.40.2 by John Arbash Meinel
Add a groupcompress.encode_copy_instruction function.
1603
                    result[record.key] = osutils.sha_string(
1604
                        record.get_bytes_as('fulltext'))
0.17.5 by Robert Collins
nograph tests completely passing.
1605
        return result
1606
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
1607
    def insert_record_stream(self, stream):
0.17.2 by Robert Collins
Core proof of concept working.
1608
        """Insert a record stream into this container.
1609
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1610
        :param stream: A stream of records to insert.
0.17.2 by Robert Collins
Core proof of concept working.
1611
        :return: None
1612
        :seealso VersionedFiles.get_record_stream:
1613
        """
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1614
        # XXX: Setting random_id=True makes
1615
        # test_insert_record_stream_existing_keys fail for groupcompress and
1616
        # groupcompress-nograph, this needs to be revisited while addressing
1617
        # 'bzr branch' performance issues.
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
1618
        for _ in self._insert_record_stream(stream, random_id=False):
0.17.5 by Robert Collins
nograph tests completely passing.
1619
            pass
0.17.2 by Robert Collins
Core proof of concept working.
1620
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1621
    def _insert_record_stream(self, stream, random_id=False, nostore_sha=None,
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
1622
                              reuse_blocks=True):
0.17.2 by Robert Collins
Core proof of concept working.
1623
        """Internal core to insert a record stream into this container.
1624
1625
        This helper function has a different interface than insert_record_stream
1626
        to allow add_lines to be minimal, but still return the needed data.
1627
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1628
        :param stream: A stream of records to insert.
3735.31.12 by John Arbash Meinel
Push nostore_sha down through the stack.
1629
        :param nostore_sha: If the sha1 of a given text matches nostore_sha,
1630
            raise ExistingContent, rather than committing the new text.
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1631
        :param reuse_blocks: If the source is streaming from
1632
            groupcompress-blocks, just insert the blocks as-is, rather than
1633
            expanding the texts and inserting again.
0.17.2 by Robert Collins
Core proof of concept working.
1634
        :return: An iterator over the sha1 of the inserted records.
1635
        :seealso insert_record_stream:
1636
        :seealso add_lines:
1637
        """
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1638
        adapters = {}
0.17.5 by Robert Collins
nograph tests completely passing.
1639
        def get_adapter(adapter_key):
1640
            try:
1641
                return adapters[adapter_key]
1642
            except KeyError:
1643
                adapter_factory = adapter_registry.get(adapter_key)
1644
                adapter = adapter_factory(self)
1645
                adapters[adapter_key] = adapter
1646
                return adapter
0.17.2 by Robert Collins
Core proof of concept working.
1647
        # This will go up to fulltexts for gc to gc fetching, which isn't
1648
        # ideal.
3735.32.19 by John Arbash Meinel
Get rid of the 'delta' flag to GroupCompressor. It didn't do anything anyway.
1649
        self._compressor = GroupCompressor()
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
1650
        self._unadded_refs = {}
0.17.5 by Robert Collins
nograph tests completely passing.
1651
        keys_to_add = []
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
1652
        def flush():
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
1653
            bytes_len, chunks = self._compressor.flush().to_chunks()
4634.139.9 by John Arbash Meinel
Partial fix for bug #566940.
1654
            self._compressor = GroupCompressor()
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
1655
            # Note: At this point we still have 1 copy of the fulltext (in
1656
            #       record and the var 'bytes'), and this generates 2 copies of
1657
            #       the compressed text (one for bytes, one in chunks)
1658
            # TODO: Push 'chunks' down into the _access api, so that we don't
1659
            #       have to double compressed memory here
1660
            # TODO: Figure out how to indicate that we would be happy to free
1661
            #       the fulltext content at this point. Note that sometimes we
1662
            #       will want it later (streaming CHK pages), but most of the
1663
            #       time we won't (everything else)
1664
            bytes = ''.join(chunks)
1665
            del chunks
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
1666
            index, start, length = self._access.add_raw_records(
0.25.7 by John Arbash Meinel
Have the GroupCompressBlock decide how to compress the header and content.
1667
                [(None, len(bytes))], bytes)[0]
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
1668
            nodes = []
1669
            for key, reads, refs in keys_to_add:
1670
                nodes.append((key, "%d %d %s" % (start, length, reads), refs))
1671
            self._index.add_records(nodes, random_id=random_id)
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1672
            self._unadded_refs = {}
1673
            del keys_to_add[:]
1674
0.20.15 by John Arbash Meinel
Change so that regions that have lots of copies get converted back
1675
        last_prefix = None
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1676
        max_fulltext_len = 0
0.25.11 by John Arbash Meinel
Slightly different handling of large texts.
1677
        max_fulltext_prefix = None
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
1678
        insert_manager = None
1679
        block_start = None
1680
        block_length = None
3735.36.15 by John Arbash Meinel
Set 'combine_backing_indices=False' as the default for text and chk indices.
1681
        # XXX: TODO: remove this, it is just for safety checking for now
1682
        inserted_keys = set()
4665.3.9 by John Arbash Meinel
Start doing some work to make sure that we call _check_rebuild_block
1683
        reuse_this_block = reuse_blocks
0.17.2 by Robert Collins
Core proof of concept working.
1684
        for record in stream:
0.17.5 by Robert Collins
nograph tests completely passing.
1685
            # Raise an error when a record is missing.
1686
            if record.storage_kind == 'absent':
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1687
                raise errors.RevisionNotPresent(record.key, self)
3735.36.15 by John Arbash Meinel
Set 'combine_backing_indices=False' as the default for text and chk indices.
1688
            if random_id:
1689
                if record.key in inserted_keys:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1690
                    trace.note('Insert claimed random_id=True,'
1691
                               ' but then inserted %r two times', record.key)
3735.36.15 by John Arbash Meinel
Set 'combine_backing_indices=False' as the default for text and chk indices.
1692
                    continue
1693
                inserted_keys.add(record.key)
4665.3.9 by John Arbash Meinel
Start doing some work to make sure that we call _check_rebuild_block
1694
            if reuse_blocks:
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1695
                # If the reuse_blocks flag is set, check to see if we can just
1696
                # copy a groupcompress block as-is.
4665.3.10 by John Arbash Meinel
Get a test written which exercises the 'trim' code path.
1697
                # We only check on the first record (groupcompress-block) not
1698
                # on all of the (groupcompress-block-ref) entries.
1699
                # The reuse_this_block flag is then kept for as long as
4634.23.1 by Robert Collins
Cherrypick from bzr.dev: Fix bug 402652: recompress badly packed groups during fetch. (John Arbash Meinel, Robert Collins)
1700
                if record.storage_kind == 'groupcompress-block':
4665.3.2 by John Arbash Meinel
An alternative implementation that passes both tests.
1701
                    # Check to see if we really want to re-use this block
1702
                    insert_manager = record._manager
4665.3.9 by John Arbash Meinel
Start doing some work to make sure that we call _check_rebuild_block
1703
                    reuse_this_block = insert_manager.check_is_well_utilized()
4665.3.10 by John Arbash Meinel
Get a test written which exercises the 'trim' code path.
1704
            else:
1705
                reuse_this_block = False
4665.3.2 by John Arbash Meinel
An alternative implementation that passes both tests.
1706
            if reuse_this_block:
1707
                # We still want to reuse this block
1708
                if record.storage_kind == 'groupcompress-block':
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1709
                    # Insert the raw block into the target repo
1710
                    insert_manager = record._manager
1711
                    bytes = record._manager._block.to_bytes()
1712
                    _, start, length = self._access.add_raw_records(
1713
                        [(None, len(bytes))], bytes)[0]
1714
                    del bytes
1715
                    block_start = start
1716
                    block_length = length
1717
                if record.storage_kind in ('groupcompress-block',
1718
                                           'groupcompress-block-ref'):
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1719
                    if insert_manager is None:
1720
                        raise AssertionError('No insert_manager set')
4665.3.4 by John Arbash Meinel
Refactor the check_rebuild code a bit, so that we can potentially
1721
                    if insert_manager is not record._manager:
1722
                        raise AssertionError('insert_manager does not match'
1723
                            ' the current record, we cannot be positive'
1724
                            ' that the appropriate content was inserted.'
1725
                            )
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1726
                    value = "%d %d %d %d" % (block_start, block_length,
1727
                                             record._start, record._end)
1728
                    nodes = [(record.key, value, (record.parents,))]
3735.38.1 by John Arbash Meinel
Change the delta byte stream to remove the 'source length' entry.
1729
                    # TODO: Consider buffering up many nodes to be added, not
1730
                    #       sure how much overhead this has, but we're seeing
1731
                    #       ~23s / 120s in add_records calls
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1732
                    self._index.add_records(nodes, random_id=random_id)
1733
                    continue
0.20.18 by John Arbash Meinel
Implement new handling of get_bytes_as(), and get_missing_compression_parent_keys()
1734
            try:
0.23.52 by John Arbash Meinel
Use the max_delta flag.
1735
                bytes = record.get_bytes_as('fulltext')
0.20.18 by John Arbash Meinel
Implement new handling of get_bytes_as(), and get_missing_compression_parent_keys()
1736
            except errors.UnavailableRepresentation:
0.17.5 by Robert Collins
nograph tests completely passing.
1737
                adapter_key = record.storage_kind, 'fulltext'
1738
                adapter = get_adapter(adapter_key)
0.20.21 by John Arbash Meinel
Merge the chk sorting code.
1739
                bytes = adapter.get_bytes(record)
0.20.13 by John Arbash Meinel
Play around a bit.
1740
            if len(record.key) > 1:
1741
                prefix = record.key[0]
0.25.11 by John Arbash Meinel
Slightly different handling of large texts.
1742
                soft = (prefix == last_prefix)
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1743
            else:
1744
                prefix = None
0.25.11 by John Arbash Meinel
Slightly different handling of large texts.
1745
                soft = False
1746
            if max_fulltext_len < len(bytes):
1747
                max_fulltext_len = len(bytes)
1748
                max_fulltext_prefix = prefix
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1749
            (found_sha1, start_point, end_point,
1750
             type) = self._compressor.compress(record.key,
1751
                                               bytes, record.sha1, soft=soft,
1752
                                               nostore_sha=nostore_sha)
1753
            # delta_ratio = float(len(bytes)) / (end_point - start_point)
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1754
            # Check if we want to continue to include that text
0.25.11 by John Arbash Meinel
Slightly different handling of large texts.
1755
            if (prefix == max_fulltext_prefix
1756
                and end_point < 2 * max_fulltext_len):
1757
                # As long as we are on the same file_id, we will fill at least
1758
                # 2 * max_fulltext_len
1759
                start_new_block = False
1760
            elif end_point > 4*1024*1024:
1761
                start_new_block = True
1762
            elif (prefix is not None and prefix != last_prefix
1763
                  and end_point > 2*1024*1024):
1764
                start_new_block = True
1765
            else:
1766
                start_new_block = False
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1767
            last_prefix = prefix
1768
            if start_new_block:
1769
                self._compressor.pop_last()
1770
                flush()
1771
                max_fulltext_len = len(bytes)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1772
                (found_sha1, start_point, end_point,
1773
                 type) = self._compressor.compress(record.key, bytes,
1774
                                                   record.sha1)
0.17.26 by Robert Collins
Working better --gc-plain-chk.
1775
            if record.key[-1] is None:
1776
                key = record.key[:-1] + ('sha1:' + found_sha1,)
1777
            else:
1778
                key = record.key
1779
            self._unadded_refs[key] = record.parents
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
1780
            yield found_sha1
4842.1.1 by Andrew Bennetts
Fix crash involving static_tuple when C extensions are not built.
1781
            as_st = static_tuple.StaticTuple.from_sequence
1782
            if record.parents is not None:
1783
                parents = as_st([as_st(p) for p in record.parents])
1784
            else:
1785
                parents = None
1786
            refs = static_tuple.StaticTuple(parents)
1787
            keys_to_add.append((key, '%d %d' % (start_point, end_point), refs))
0.17.8 by Robert Collins
Flush pending updates at the end of _insert_record_stream
1788
        if len(keys_to_add):
1789
            flush()
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
1790
        self._compressor = None
5195.3.12 by Parth Malwankar
initial approximation of progress.
1791
0.17.5 by Robert Collins
nograph tests completely passing.
1792
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1793
        """Iterate over the lines in the versioned files from keys.
1794
1795
        This may return lines from other keys. Each item the returned
1796
        iterator yields is a tuple of a line and a text version that that line
1797
        is present in (not introduced in).
1798
1799
        Ordering of results is in whatever order is most suitable for the
1800
        underlying storage format.
1801
1802
        If a progress bar is supplied, it may be used to indicate progress.
1803
        The caller is responsible for cleaning up progress bars (because this
1804
        is an iterator).
1805
1806
        NOTES:
1807
         * Lines are normalised by the underlying store: they will all have \n
1808
           terminators.
1809
         * Lines are returned in arbitrary order.
1810
1811
        :return: An iterator over (line, key).
1812
        """
1813
        keys = set(keys)
1814
        total = len(keys)
1815
        # we don't care about inclusions, the caller cares.
1816
        # but we need to setup a list of records to visit.
1817
        # we need key, position, length
1818
        for key_idx, record in enumerate(self.get_record_stream(keys,
1819
            'unordered', True)):
1820
            # XXX: todo - optimise to use less than full texts.
1821
            key = record.key
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
1822
            if pb is not None:
1823
                pb.update('Walking content', key_idx, total)
0.17.5 by Robert Collins
nograph tests completely passing.
1824
            if record.storage_kind == 'absent':
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1825
                raise errors.RevisionNotPresent(key, self)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1826
            lines = osutils.split_lines(record.get_bytes_as('fulltext'))
0.17.5 by Robert Collins
nograph tests completely passing.
1827
            for line in lines:
1828
                yield line, key
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
1829
        if pb is not None:
1830
            pb.update('Walking content', total, total)
0.17.5 by Robert Collins
nograph tests completely passing.
1831
1832
    def keys(self):
1833
        """See VersionedFiles.keys."""
1834
        if 'evil' in debug.debug_flags:
1835
            trace.mutter_callsite(2, "keys scales with size of history")
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1836
        sources = [self._index] + self._immediate_fallback_vfs
0.17.5 by Robert Collins
nograph tests completely passing.
1837
        result = set()
1838
        for source in sources:
1839
            result.update(source.keys())
1840
        return result
1841
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1842
5365.4.1 by John Arbash Meinel
Find a case where we are wasting a bit of memory.
1843
class _GCBuildDetails(object):
1844
    """A blob of data about the build details.
1845
1846
    This stores the minimal data, which then allows compatibility with the old
1847
    api, without taking as much memory.
1848
    """
1849
1850
    __slots__ = ('_index', '_group_start', '_group_end', '_basis_end',
1851
                 '_delta_end', '_parents')
1852
1853
    method = 'group'
1854
    compression_parent = None
1855
1856
    def __init__(self, parents, position_info):
1857
        self._parents = parents
5365.4.2 by John Arbash Meinel
As suggested by Martin <gz>, switch to tuple unpacking for attribute assignment
1858
        (self._index, self._group_start, self._group_end, self._basis_end,
1859
         self._delta_end) = position_info
5365.4.1 by John Arbash Meinel
Find a case where we are wasting a bit of memory.
1860
1861
    def __repr__(self):
1862
        return '%s(%s, %s)' % (self.__class__.__name__,
1863
            self.index_memo, self._parents)
1864
1865
    @property
1866
    def index_memo(self):
1867
        return (self._index, self._group_start, self._group_end,
1868
                self._basis_end, self._delta_end)
1869
1870
    @property
1871
    def record_details(self):
1872
        return static_tuple.StaticTuple(self.method, None)
1873
1874
    def __getitem__(self, offset):
1875
        """Compatibility thunk to act like a tuple."""
1876
        if offset == 0:
1877
            return self.index_memo
1878
        elif offset == 1:
1879
            return self.compression_parent # Always None
1880
        elif offset == 2:
1881
            return self._parents
1882
        elif offset == 3:
1883
            return self.record_details
1884
        else:
1885
            raise IndexError('offset out of range')
1886
            
1887
    def __len__(self):
1888
        return 4
1889
1890
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1891
class _GCGraphIndex(object):
1892
    """Mapper from GroupCompressVersionedFiles needs into GraphIndex storage."""
1893
0.17.9 by Robert Collins
Initial stab at repository format support.
1894
    def __init__(self, graph_index, is_locked, parents=True,
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1895
        add_callback=None, track_external_parent_refs=False,
4634.29.1 by Andrew Bennetts
Rough code to reject commit_write_group if any inventory's CHK root is absent.
1896
        inconsistency_fatal=True, track_new_keys=False):
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1897
        """Construct a _GCGraphIndex on a graph_index.
1898
1899
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1900
        :param is_locked: A callback, returns True if the index is locked and
1901
            thus usable.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1902
        :param parents: If True, record knits parents, if not do not record
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1903
            parents.
1904
        :param add_callback: If not None, allow additions to the index and call
1905
            this callback with a list of added GraphIndex nodes:
1906
            [(node, value, node_refs), ...]
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
1907
        :param track_external_parent_refs: As keys are added, keep track of the
1908
            keys they reference, so that we can query get_missing_parents(),
1909
            etc.
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1910
        :param inconsistency_fatal: When asked to add records that are already
1911
            present, and the details are inconsistent with the existing
1912
            record, raise an exception instead of warning (and skipping the
1913
            record).
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1914
        """
1915
        self._add_callback = add_callback
1916
        self._graph_index = graph_index
1917
        self._parents = parents
1918
        self.has_graph = parents
1919
        self._is_locked = is_locked
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1920
        self._inconsistency_fatal = inconsistency_fatal
4679.9.19 by John Arbash Meinel
Interning the start and stop group positions saves another 7MB peak mem. \o/
1921
        # GroupCompress records tend to have the same 'group' start + offset
1922
        # repeated over and over, this creates a surplus of ints
1923
        self._int_cache = {}
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
1924
        if track_external_parent_refs:
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
1925
            self._key_dependencies = knit._KeyRefs(
1926
                track_new_keys=track_new_keys)
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
1927
        else:
1928
            self._key_dependencies = None
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1929
0.17.5 by Robert Collins
nograph tests completely passing.
1930
    def add_records(self, records, random_id=False):
1931
        """Add multiple records to the index.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1932
0.17.5 by Robert Collins
nograph tests completely passing.
1933
        This function does not insert data into the Immutable GraphIndex
1934
        backing the KnitGraphIndex, instead it prepares data for insertion by
1935
        the caller and checks that it is safe to insert then calls
1936
        self._add_callback with the prepared GraphIndex nodes.
1937
1938
        :param records: a list of tuples:
1939
                         (key, options, access_memo, parents).
1940
        :param random_id: If True the ids being added were randomly generated
1941
            and no check for existence will be performed.
1942
        """
1943
        if not self._add_callback:
1944
            raise errors.ReadOnlyError(self)
1945
        # we hope there are no repositories with inconsistent parentage
1946
        # anymore.
1947
1948
        changed = False
1949
        keys = {}
1950
        for (key, value, refs) in records:
1951
            if not self._parents:
1952
                if refs:
1953
                    for ref in refs:
1954
                        if ref:
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1955
                            raise errors.KnitCorrupt(self,
0.17.5 by Robert Collins
nograph tests completely passing.
1956
                                "attempt to add node with parents "
1957
                                "in parentless index.")
1958
                    refs = ()
1959
                    changed = True
1960
            keys[key] = (value, refs)
1961
        # check for dups
1962
        if not random_id:
1963
            present_nodes = self._get_entries(keys)
1964
            for (index, key, value, node_refs) in present_nodes:
4789.28.3 by John Arbash Meinel
Add a static_tuple.as_tuples() helper.
1965
                # Sometimes these are passed as a list rather than a tuple
1966
                node_refs = static_tuple.as_tuples(node_refs)
1967
                passed = static_tuple.as_tuples(keys[key])
1968
                if node_refs != passed[1]:
1969
                    details = '%s %s %s' % (key, (value, node_refs), passed)
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1970
                    if self._inconsistency_fatal:
1971
                        raise errors.KnitCorrupt(self, "inconsistent details"
1972
                                                 " in add_records: %s" %
1973
                                                 details)
1974
                    else:
1975
                        trace.warning("inconsistent details in skipped"
1976
                                      " record: %s", details)
0.17.5 by Robert Collins
nograph tests completely passing.
1977
                del keys[key]
1978
                changed = True
1979
        if changed:
1980
            result = []
1981
            if self._parents:
1982
                for key, (value, node_refs) in keys.iteritems():
1983
                    result.append((key, value, node_refs))
1984
            else:
1985
                for key, (value, node_refs) in keys.iteritems():
1986
                    result.append((key, value))
1987
            records = result
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
1988
        key_dependencies = self._key_dependencies
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
1989
        if key_dependencies is not None:
1990
            if self._parents:
1991
                for key, value, refs in records:
1992
                    parents = refs[0]
1993
                    key_dependencies.add_references(key, parents)
1994
            else:
1995
                for key, value, refs in records:
1996
                    new_keys.add_key(key)
0.17.5 by Robert Collins
nograph tests completely passing.
1997
        self._add_callback(records)
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1998
0.17.5 by Robert Collins
nograph tests completely passing.
1999
    def _check_read(self):
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
2000
        """Raise an exception if reads are not permitted."""
0.17.5 by Robert Collins
nograph tests completely passing.
2001
        if not self._is_locked():
2002
            raise errors.ObjectNotLocked(self)
2003
0.17.2 by Robert Collins
Core proof of concept working.
2004
    def _check_write_ok(self):
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
2005
        """Raise an exception if writes are not permitted."""
0.17.2 by Robert Collins
Core proof of concept working.
2006
        if not self._is_locked():
2007
            raise errors.ObjectNotLocked(self)
2008
0.17.5 by Robert Collins
nograph tests completely passing.
2009
    def _get_entries(self, keys, check_present=False):
2010
        """Get the entries for keys.
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
2011
2012
        Note: Callers are responsible for checking that the index is locked
2013
        before calling this method.
2014
0.17.5 by Robert Collins
nograph tests completely passing.
2015
        :param keys: An iterable of index key tuples.
2016
        """
2017
        keys = set(keys)
2018
        found_keys = set()
2019
        if self._parents:
2020
            for node in self._graph_index.iter_entries(keys):
2021
                yield node
2022
                found_keys.add(node[1])
2023
        else:
2024
            # adapt parentless index to the rest of the code.
2025
            for node in self._graph_index.iter_entries(keys):
2026
                yield node[0], node[1], node[2], ()
2027
                found_keys.add(node[1])
2028
        if check_present:
2029
            missing_keys = keys.difference(found_keys)
2030
            if missing_keys:
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
2031
                raise errors.RevisionNotPresent(missing_keys.pop(), self)
0.17.5 by Robert Collins
nograph tests completely passing.
2032
4634.11.3 by John Arbash Meinel
Implement _GCGraphIndex.find_ancestry()
2033
    def find_ancestry(self, keys):
2034
        """See CombinedGraphIndex.find_ancestry"""
2035
        return self._graph_index.find_ancestry(keys, 0)
2036
0.17.5 by Robert Collins
nograph tests completely passing.
2037
    def get_parent_map(self, keys):
2038
        """Get a map of the parents of keys.
2039
2040
        :param keys: The keys to look up parents for.
2041
        :return: A mapping from keys to parents. Absent keys are absent from
2042
            the mapping.
2043
        """
2044
        self._check_read()
2045
        nodes = self._get_entries(keys)
2046
        result = {}
2047
        if self._parents:
2048
            for node in nodes:
2049
                result[node[1]] = node[3][0]
2050
        else:
2051
            for node in nodes:
2052
                result[node[1]] = None
2053
        return result
2054
4343.3.1 by John Arbash Meinel
Set 'supports_external_lookups=True' for dev6 repositories.
2055
    def get_missing_parents(self):
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
2056
        """Return the keys of missing parents."""
2057
        # Copied from _KnitGraphIndex.get_missing_parents
2058
        # We may have false positives, so filter those out.
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2059
        self._key_dependencies.satisfy_refs_for_keys(
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
2060
            self.get_parent_map(self._key_dependencies.get_unsatisfied_refs()))
2061
        return frozenset(self._key_dependencies.get_unsatisfied_refs())
4343.3.1 by John Arbash Meinel
Set 'supports_external_lookups=True' for dev6 repositories.
2062
0.17.5 by Robert Collins
nograph tests completely passing.
2063
    def get_build_details(self, keys):
2064
        """Get the various build details for keys.
2065
2066
        Ghosts are omitted from the result.
2067
2068
        :param keys: An iterable of keys.
2069
        :return: A dict of key:
2070
            (index_memo, compression_parent, parents, record_details).
2071
            index_memo
2072
                opaque structure to pass to read_records to extract the raw
2073
                data
2074
            compression_parent
2075
                Content that this record is built upon, may be None
2076
            parents
2077
                Logical parents of this node
2078
            record_details
2079
                extra information about the content which needs to be passed to
2080
                Factory.parse_record
2081
        """
2082
        self._check_read()
2083
        result = {}
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
2084
        entries = self._get_entries(keys)
0.17.5 by Robert Collins
nograph tests completely passing.
2085
        for entry in entries:
2086
            key = entry[1]
2087
            if not self._parents:
2088
                parents = None
2089
            else:
2090
                parents = entry[3][0]
5365.4.1 by John Arbash Meinel
Find a case where we are wasting a bit of memory.
2091
            details = _GCBuildDetails(parents, self._node_to_position(entry))
2092
            result[key] = details
0.17.5 by Robert Collins
nograph tests completely passing.
2093
        return result
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
2094
0.17.5 by Robert Collins
nograph tests completely passing.
2095
    def keys(self):
2096
        """Get all the keys in the collection.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
2097
0.17.5 by Robert Collins
nograph tests completely passing.
2098
        The keys are not ordered.
2099
        """
2100
        self._check_read()
2101
        return [node[1] for node in self._graph_index.iter_all_entries()]
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
2102
0.17.5 by Robert Collins
nograph tests completely passing.
2103
    def _node_to_position(self, node):
2104
        """Convert an index value to position details."""
2105
        bits = node[2].split(' ')
2106
        # It would be nice not to read the entire gzip.
4679.9.19 by John Arbash Meinel
Interning the start and stop group positions saves another 7MB peak mem. \o/
2107
        # start and stop are put into _int_cache because they are very common.
2108
        # They define the 'group' that an entry is in, and many groups can have
2109
        # thousands of objects.
2110
        # Branching Launchpad, for example, saves ~600k integers, at 12 bytes
2111
        # each, or about 7MB. Note that it might be even more when you consider
2112
        # how PyInt is allocated in separate slabs. And you can't return a slab
2113
        # to the OS if even 1 int on it is in use. Note though that Python uses
5365.4.1 by John Arbash Meinel
Find a case where we are wasting a bit of memory.
2114
        # a LIFO when re-using PyInt slots, which might cause more
4679.9.19 by John Arbash Meinel
Interning the start and stop group positions saves another 7MB peak mem. \o/
2115
        # fragmentation.
0.17.5 by Robert Collins
nograph tests completely passing.
2116
        start = int(bits[0])
4679.9.19 by John Arbash Meinel
Interning the start and stop group positions saves another 7MB peak mem. \o/
2117
        start = self._int_cache.setdefault(start, start)
0.17.5 by Robert Collins
nograph tests completely passing.
2118
        stop = int(bits[1])
4679.9.19 by John Arbash Meinel
Interning the start and stop group positions saves another 7MB peak mem. \o/
2119
        stop = self._int_cache.setdefault(stop, stop)
0.17.5 by Robert Collins
nograph tests completely passing.
2120
        basis_end = int(bits[2])
2121
        delta_end = int(bits[3])
4679.9.19 by John Arbash Meinel
Interning the start and stop group positions saves another 7MB peak mem. \o/
2122
        # We can't use StaticTuple here, because node[0] is a BTreeGraphIndex
2123
        # instance...
2124
        return (node[0], start, stop, basis_end, delta_end)
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
2125
4343.3.2 by John Arbash Meinel
All stacking tests seem to be passing for dev6 repos
2126
    def scan_unvalidated_index(self, graph_index):
2127
        """Inform this _GCGraphIndex that there is an unvalidated index.
2128
2129
        This allows this _GCGraphIndex to keep track of any missing
2130
        compression parents we may want to have filled in to make those
4634.29.3 by Andrew Bennetts
Simplify further.
2131
        indices valid.  It also allows _GCGraphIndex to track any new keys.
4343.3.2 by John Arbash Meinel
All stacking tests seem to be passing for dev6 repos
2132
2133
        :param graph_index: A GraphIndex
2134
        """
4634.29.3 by Andrew Bennetts
Simplify further.
2135
        key_dependencies = self._key_dependencies
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2136
        if key_dependencies is None:
4634.29.1 by Andrew Bennetts
Rough code to reject commit_write_group if any inventory's CHK root is absent.
2137
            return
2138
        for node in graph_index.iter_all_entries():
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2139
            # Add parent refs from graph_index (and discard parent refs
2140
            # that the graph_index has).
2141
            key_dependencies.add_references(node[1], node[3][0])
4343.3.2 by John Arbash Meinel
All stacking tests seem to be passing for dev6 repos
2142
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
2143
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
2144
from bzrlib._groupcompress_py import (
2145
    apply_delta,
3735.40.19 by John Arbash Meinel
Implement apply_delta_to_source which doesn't have to malloc another string.
2146
    apply_delta_to_source,
3735.40.11 by John Arbash Meinel
Implement make_delta and apply_delta.
2147
    encode_base128_int,
2148
    decode_base128_int,
4300.1.1 by John Arbash Meinel
Add the ability to convert a gc block into 'human readable' form.
2149
    decode_copy_instruction,
3735.40.13 by John Arbash Meinel
Rename EquivalenceTable to LinesDeltaIndex.
2150
    LinesDeltaIndex,
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
2151
    )
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
2152
try:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
2153
    from bzrlib._groupcompress_pyx import (
2154
        apply_delta,
3735.40.19 by John Arbash Meinel
Implement apply_delta_to_source which doesn't have to malloc another string.
2155
        apply_delta_to_source,
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
2156
        DeltaIndex,
3735.40.16 by John Arbash Meinel
Implement (de|en)code_base128_int in pyrex.
2157
        encode_base128_int,
2158
        decode_base128_int,
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
2159
        )
3735.40.2 by John Arbash Meinel
Add a groupcompress.encode_copy_instruction function.
2160
    GroupCompressor = PyrexGroupCompressor
4574.3.6 by Martin Pool
More warnings when failing to load extensions
2161
except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
2162
    osutils.failed_to_load_extension(e)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
2163
    GroupCompressor = PythonGroupCompressor
2164