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