/brz/remove-bazaar

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