~bzr-pqm/bzr/bzr.dev

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