~bzr-pqm/bzr/bzr.dev

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