/brz/remove-bazaar

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