Debian Codegraph @

tests/test-revlog-raw.py

raw
1 # test revlog interaction about raw data (flagprocessor)
2
3
4 import hashlib
5 import sys
6
7 from mercurial import (
8 encoding,
9 revlog,
10 revlogutils,
11 transaction,
12 vfs,
13 )
14
15 from mercurial.revlogutils import (
16 config,
17 constants,
18 deltas,
19 flagutil,
20 )
21
22
23 class _NoTransaction:
24 """transaction like object to update the nodemap outside a transaction"""
25
26 def __init__(self):
27 self._postclose = {}
28
29 def addpostclose(self, callback_id, callback_func):
30 self._postclose[callback_id] = callback_func
31
32 def registertmp(self, *args, **kwargs):
33 pass
34
35 def addbackup(self, *args, **kwargs):
36 pass
37
38 def add(self, *args, **kwargs):
39 pass
40
41 def addabort(self, *args, **kwargs):
42 pass
43
44 def _report(self, *args):
45 pass
46
47
48 # TESTTMP is optional. This makes it convenient to run without run-tests.py
49 tvfs = vfs.vfs(encoding.environ.get(b'TESTTMP', b'/tmp'))
50
51 # Enable generaldelta otherwise revlog won't use delta as expected by the test
52 tvfs.options = {
53 b'generaldelta': True,
54 b'revlogv1': True,
55 b'delta-config': config.DeltaConfig(sparse_revlog=True),
56 }
57
58
59 def abort(msg):
60 print('abort: %s' % msg)
61 # Return 0 so run-tests.py could compare the output.
62 sys.exit()
63
64
65 # Register a revlog processor for flag EXTSTORED.
66 #
67 # It simply prepends a fixed header, and replaces '1' to 'i'. So it has
68 # insertion and replacement, and may be interesting to test revlog's line-based
69 # deltas.
70 _extheader = b'E\n'
71
72
73 def readprocessor(self, rawtext):
74 # True: the returned text could be used to verify hash
75 text = rawtext[len(_extheader) :].replace(b'i', b'1')
76 return text, True
77
78
79 def writeprocessor(self, text):
80 # False: the returned rawtext shouldn't be used to verify hash
81 rawtext = _extheader + text.replace(b'1', b'i')
82 return rawtext, False
83
84
85 def rawprocessor(self, rawtext):
86 # False: do not verify hash. Only the content returned by "readprocessor"
87 # can be used to verify hash.
88 return False
89
90
91 flagutil.addflagprocessor(
92 revlog.REVIDX_EXTSTORED, (readprocessor, writeprocessor, rawprocessor)
93 )
94
95 # Utilities about reading and appending revlog
96
97
98 def newtransaction():
99 # A transaction is required to write revlogs
100 report = lambda msg: None
101 return transaction.transaction(report, tvfs, {'plain': tvfs}, b'journal')
102
103
104 def newrevlog(name=b'_testrevlog', recreate=False):
105 if recreate:
106 tvfs.tryunlink(name + b'.i')
107 target = (constants.KIND_OTHER, b'test')
108 rlog = revlog.revlog(tvfs, target=target, radix=name, may_inline=False)
109 return rlog
110
111
112 def appendrev(rlog, text, tr, isext=False, isdelta=True):
113 """Append a revision. If isext is True, set the EXTSTORED flag so flag
114 processor will be used (and rawtext is different from text). If isdelta is
115 True, force the revision to be a delta, otherwise it's full text.
116 """
117 nextrev = len(rlog)
118 p1 = rlog.node(nextrev - 1)
119 p2 = rlog.nullid
120 if isext:
121 flags = revlog.REVIDX_EXTSTORED
122 else:
123 flags = revlog.REVIDX_DEFAULT_FLAGS
124 # Change storedeltachains temporarily, to override revlog's delta decision
125 rlog._storedeltachains = isdelta
126 try:
127 rlog.addrevision(text, tr, nextrev, p1, p2, flags=flags)
128 return nextrev
129 except Exception as ex:
130 abort('rev %d: failed to append: %s' % (nextrev, ex))
131 finally:
132 # Restore storedeltachains. It is always True, see revlog.__init__
133 rlog._storedeltachains = True
134
135
136 def addgroupcopy(rlog, tr, destname=b'_destrevlog', optimaldelta=True):
137 """Copy revlog to destname using revlog.addgroup. Return the copied revlog.
138
139 This emulates push or pull. They use changegroup. Changegroup requires
140 repo to work. We don't have a repo, so a dummy changegroup is used.
141
142 If optimaldelta is True, use optimized delta parent, so the destination
143 revlog could probably reuse it. Otherwise it builds sub-optimal delta, and
144 the destination revlog needs more work to use it.
145
146 This exercises some revlog.addgroup (and revlog._addrevision(text=None))
147 code path, which is not covered by "appendrev" alone.
148 """
149
150 class dummychangegroup:
151 @staticmethod
152 def deltachunk(pnode):
153 pnode = pnode or rlog.nullid
154 parentrev = rlog.rev(pnode)
155 r = parentrev + 1
156 if r >= len(rlog):
157 return {}
158 if optimaldelta:
159 deltaparent = parentrev
160 else:
161 # suboptimal deltaparent
162 deltaparent = min(0, parentrev)
163 if not rlog._candelta(deltaparent, r):
164 deltaparent = -1
165 return revlogutils.InboundRevision(
166 node=rlog.node(r),
167 p1=pnode,
168 p2=rlog.nullid,
169 link_node=rlog.node(rlog.linkrev(r)),
170 flags=rlog.flags(r),
171 delta_base=rlog.node(deltaparent),
172 delta=rlog.revdiff(deltaparent, r),
173 sidedata=rlog.sidedata(r),
174 )
175
176 def deltaiter(self):
177 chain = None
178 for chunkdata in iter(lambda: self.deltachunk(chain), {}):
179 chain = chunkdata.node
180 yield chunkdata
181
182 def linkmap(lnode):
183 return rlog.rev(lnode)
184
185 dlog = newrevlog(destname, recreate=True)
186 dummydeltas = dummychangegroup().deltaiter()
187 dlog.addgroup(dummydeltas, linkmap, tr)
188 return dlog
189
190
191 def lowlevelcopy(rlog, tr, destname=b'_destrevlog'):
192 """Like addgroupcopy, but use the low level revlog._addrevision directly.
193
194 It exercises some code paths that are hard to reach easily otherwise.
195 """
196 dlog = newrevlog(destname, recreate=True)
197 for r in rlog:
198 p1 = rlog.node(r - 1)
199 p2 = rlog.nullid
200 if r == 0 or (rlog.flags(r) & revlog.REVIDX_EXTSTORED):
201 text = rlog.rawdata(r)
202 cachedelta = None
203 else:
204 # deltaparent cannot have EXTSTORED flag.
205 deltaparent = max(
206 [-1]
207 + [
208 p
209 for p in range(r)
210 if rlog.flags(p) & revlog.REVIDX_EXTSTORED == 0
211 ]
212 )
213 text = None
214 cachedelta = revlogutils.CachedDelta(
215 deltaparent,
216 rlog.revdiff(deltaparent, r),
217 )
218 flags = rlog.flags(r)
219 with dlog._writing(_NoTransaction()):
220 dlog._addrevision(
221 rlog.node(r),
222 text,
223 tr,
224 r,
225 p1,
226 p2,
227 flags,
228 cachedelta,
229 )
230 return dlog
231
232
233 # Utilities to generate revisions for testing
234
235
236 def genbits(n):
237 """Given a number n, generate (2 ** (n * 2) + 1) numbers in range(2 ** n).
238 i.e. the generated numbers have a width of n bits.
239
240 The combination of two adjacent numbers will cover all possible cases.
241 That is to say, given any x, y where both x, and y are in range(2 ** n),
242 there is an x followed immediately by y in the generated sequence.
243 """
244 m = 2**n
245
246 # Gray Code. See https://en.wikipedia.org/wiki/Gray_code
247 gray = lambda x: x ^ (x >> 1)
248 reversegray = {gray(i): i for i in range(m)}
249
250 # Generate (n * 2) bit gray code, yield lower n bits as X, and look for
251 # the next unused gray code where higher n bits equal to X.
252
253 # For gray codes whose higher bits are X, a[X] of them have been used.
254 a = [0] * m
255
256 # Iterate from 0.
257 x = 0
258 yield x
259 for i in range(m * m):
260 x = reversegray[x]
261 y = gray(a[x] + x * m) & (m - 1)
262 assert a[x] < m
263 a[x] += 1
264 x = y
265 yield x
266
267
268 def gentext(rev):
269 '''Given a revision number, generate dummy text'''
270 return b''.join(b'%d\n' % j for j in range(-1, rev % 5))
271
272
273 def writecases(rlog, tr):
274 """Write some revisions interested to the test.
275
276 The test is interested in 3 properties of a revision:
277
278 - Is it a delta or a full text? (isdelta)
279 This is to catch some delta application issues.
280 - Does it have a flag of EXTSTORED? (isext)
281 This is to catch some flag processor issues. Especially when
282 interacted with revlog deltas.
283 - Is its text empty? (isempty)
284 This is less important. It is intended to try to catch some careless
285 checks like "if text" instead of "if text is None". Note: if flag
286 processor is involved, raw text may be not empty.
287
288 Write 65 revisions. So that all combinations of the above flags for
289 adjacent revisions are covered. That is to say,
290
291 len(set(
292 (r.delta, r.ext, r.empty, (r+1).delta, (r+1).ext, (r+1).empty)
293 for r in range(len(rlog) - 1)
294 )) is 64.
295
296 Where "r.delta", "r.ext", and "r.empty" are booleans matching properties
297 mentioned above.
298
299 Return expected [(text, rawtext)].
300 """
301 result = []
302 for i, x in enumerate(genbits(3)):
303 isdelta, isext, isempty = bool(x & 1), bool(x & 2), bool(x & 4)
304 if isempty:
305 text = b''
306 else:
307 text = gentext(i)
308 rev = appendrev(rlog, text, tr, isext=isext, isdelta=isdelta)
309
310 # Verify text, rawtext, and rawsize
311 if isext:
312 rawtext = writeprocessor(None, text)[0]
313 else:
314 rawtext = text
315 if rlog.rawsize(rev) != len(rawtext):
316 abort('rev %d: wrong rawsize' % rev)
317 if rlog.revision(rev) != text:
318 abort('rev %d: wrong text' % rev)
319 if rlog.rawdata(rev) != rawtext:
320 abort('rev %d: wrong rawtext' % rev)
321 result.append((text, rawtext))
322
323 # Verify flags like isdelta, isext work as expected
324 # isdelta can be overridden to False if this or p1 has isext set
325 if bool(rlog.deltaparent(rev) > -1) and not isdelta:
326 abort('rev %d: isdelta is unexpected' % rev)
327 if bool(rlog.flags(rev)) != isext:
328 abort('rev %d: isext is ineffective' % rev)
329 return result
330
331
332 # Main test and checking
333
334
335 def checkrevlog(rlog, expected):
336 '''Check if revlog has expected contents. expected is [(text, rawtext)]'''
337 # Test using different access orders. This could expose some issues
338 # depending on revlog caching (see revlog._cache).
339 for r0 in range(len(rlog) - 1):
340 r1 = r0 + 1
341 for revorder in [[r0, r1], [r1, r0]]:
342 for raworder in [[True], [False], [True, False], [False, True]]:
343 nlog = newrevlog()
344 for rev in revorder:
345 for raw in raworder:
346 if raw:
347 t = nlog.rawdata(rev)
348 else:
349 t = nlog.revision(rev)
350 if t != expected[rev][int(raw)]:
351 abort(
352 'rev %d: corrupted %stext'
353 % (rev, raw and 'raw' or '')
354 )
355
356
357 slicingdata = [
358 ([0, 1, 2, 3, 55, 56, 58, 59, 60], [[0, 1], [2], [58], [59, 60]], 10),
359 ([0, 1, 2, 3, 55, 56, 58, 59, 60], [[0, 1], [2], [58], [59, 60]], 10),
360 (
361 [-1, 0, 1, 2, 3, 55, 56, 58, 59, 60],
362 [[-1, 0, 1], [2], [58], [59, 60]],
363 10,
364 ),
365 ]
366
367
368 def slicingtest(rlog):
369 old_delta_config = rlog.delta_config
370 old_data_config = rlog.data_config
371 rlog.delta_config = rlog.delta_config.copy()
372 rlog.data_config = rlog.data_config.copy()
373 try:
374 # the test revlog is small, we remove the floor under which we
375 # slicing is diregarded.
376 rlog.data_config.sr_min_gap_size = 0
377 rlog.delta_config.sr_min_gap_size = 0
378 for item in slicingdata:
379 chain, expected, target = item
380 result = deltas.slicechunk(rlog, chain, targetsize=target)
381 result = list(result)
382 if result != expected:
383 print('slicing differ:')
384 print(' chain: %s' % chain)
385 print(' size: %s' % [rlog.length(r) for r in chain])
386 print(' parents: %s' % [rlog.deltaparent(r) for r in chain])
387 print(' snapshot: %s' % [rlog.issnapshot(r) for r in chain])
388 print(' target: %s' % target)
389 print(' expected: %s' % expected)
390 print(' result: %s' % result)
391 finally:
392 rlog.delta_config = old_delta_config
393 rlog.data_config = old_data_config
394
395
396 def md5sum(s):
397 return hashlib.md5(s).digest()
398
399
400 def _maketext(*coord):
401 """create piece of text according to range of integers
402
403 The test returned use a md5sum of the integer to make it less
404 compressible"""
405 pieces = []
406 for start, size in coord:
407 num = range(start, start + size)
408 p = [md5sum(b'%d' % r) for r in num]
409 pieces.append(b'\n'.join(p))
410 return b'\n'.join(pieces) + b'\n'
411
412
413 data = [
414 _maketext((0, 120), (456, 60)),
415 _maketext((0, 120), (345, 60)),
416 _maketext((0, 120), (734, 60)),
417 _maketext((0, 120), (734, 60), (923, 45)),
418 _maketext((0, 120), (734, 60), (234, 45)),
419 _maketext((0, 120), (734, 60), (564, 45)),
420 _maketext((0, 120), (734, 60), (361, 45)),
421 _maketext((0, 120), (734, 60), (489, 45)),
422 _maketext((0, 120), (123, 60)),
423 _maketext((0, 120), (145, 60)),
424 _maketext((0, 120), (104, 60)),
425 _maketext((0, 120), (430, 60)),
426 _maketext((0, 120), (430, 60), (923, 45)),
427 _maketext((0, 120), (430, 60), (234, 45)),
428 _maketext((0, 120), (430, 60), (564, 45)),
429 _maketext((0, 120), (430, 60), (361, 45)),
430 _maketext((0, 120), (430, 60), (489, 45)),
431 _maketext((0, 120), (249, 60)),
432 _maketext((0, 120), (832, 60)),
433 _maketext((0, 120), (891, 60)),
434 _maketext((0, 120), (543, 60)),
435 _maketext((0, 120), (120, 60)),
436 _maketext((0, 120), (60, 60), (768, 30)),
437 _maketext((0, 120), (60, 60), (260, 30)),
438 _maketext((0, 120), (60, 60), (450, 30)),
439 _maketext((0, 120), (60, 60), (361, 30)),
440 _maketext((0, 120), (60, 60), (886, 30)),
441 _maketext((0, 120), (60, 60), (116, 30)),
442 _maketext((0, 120), (60, 60), (567, 30), (629, 40)),
443 _maketext((0, 120), (60, 60), (569, 30), (745, 40)),
444 _maketext((0, 120), (60, 60), (777, 30), (700, 40)),
445 _maketext((0, 120), (60, 60), (618, 30), (398, 40), (158, 10)),
446 ]
447
448
449 def makesnapshot(tr):
450 rl = newrevlog(name=b'_snaprevlog3', recreate=True)
451 for i in data:
452 appendrev(rl, i, tr)
453 return rl
454
455
456 snapshots = [-1, 0, 6, 8, 11, 17, 19, 21, 25, 30]
457
458
459 def issnapshottest(rlog):
460 result = []
461 if rlog.issnapshot(-1):
462 result.append(-1)
463 for rev in rlog:
464 if rlog.issnapshot(rev):
465 result.append(rev)
466 if snapshots != result:
467 print('snapshot differ:')
468 print(' expected: %s' % snapshots)
469 print(' got: %s' % result)
470
471
472 snapshotmapall = {0: {6, 8, 11, 17, 19, 25}, 8: {21}, -1: {0, 30}}
473 snapshotmap15 = {0: {17, 19, 25}, 8: {21}, -1: {30}}
474
475
476 def findsnapshottest(rlog):
477 cache = deltas.SnapshotCache()
478 cache.update(rlog)
479 resultall = dict(cache.snapshots)
480 if resultall != snapshotmapall:
481 print('snapshot map differ:')
482 print(' expected: %s' % snapshotmapall)
483 print(' got: %s' % resultall)
484 cache15 = deltas.SnapshotCache()
485 cache15.update(rlog, 15)
486 result15 = dict(cache15.snapshots)
487 if result15 != snapshotmap15:
488 print('snapshot map differ:')
489 print(' expected: %s' % snapshotmap15)
490 print(' got: %s' % result15)
491
492
493 def maintest():
494 with newtransaction() as tr:
495 rl = newrevlog(recreate=True)
496 expected = writecases(rl, tr)
497 checkrevlog(rl, expected)
498 print('local test passed')
499 # Copy via revlog.addgroup
500 rl1 = addgroupcopy(rl, tr)
501 checkrevlog(rl1, expected)
502 rl2 = addgroupcopy(rl, tr, optimaldelta=False)
503 checkrevlog(rl2, expected)
504 print('addgroupcopy test passed')
505 # Copy via revlog.clone
506 rl3 = newrevlog(name=b'_destrevlog3', recreate=True)
507 rl.clone(tr, rl3)
508 checkrevlog(rl3, expected)
509 print('clone test passed')
510 # Copy via low-level revlog._addrevision
511 rl4 = lowlevelcopy(rl, tr)
512 checkrevlog(rl4, expected)
513 print('lowlevelcopy test passed')
514 slicingtest(rl)
515 print('slicing test passed')
516 rl5 = makesnapshot(tr)
517 issnapshottest(rl5)
518 print('issnapshot test passed')
519 findsnapshottest(rl5)
520 print('findsnapshot test passed')
521
522
523 try:
524 maintest()
525 except Exception as ex:
526 abort('crashed: %s' % ex)