~bzr-pqm/bzr/bzr.dev

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