Debian Codegraph @

tests/test-ancestor.py

raw
1 import binascii
2 import getopt
3 import math
4 import os
5 import random
6 import sys
7 import time
8
9 from mercurial.node import nullrev
10 from mercurial import (
11 ancestor,
12 debugcommands,
13 ui as uimod,
14 )
15 from mercurial.repo import (
16 factory as repo_factory,
17 )
18
19
20 def buildgraph(rng, nodes=100, rootprob=0.05, mergeprob=0.2, prevprob=0.7):
21 """nodes: total number of nodes in the graph
22 rootprob: probability that a new node (not 0) will be a root
23 mergeprob: probability that, excluding a root a node will be a merge
24 prevprob: probability that p1 will be the previous node
25
26 return value is a graph represented as an adjacency list.
27 """
28 graph = [None] * nodes
29 for i in range(nodes):
30 if i == 0 or rng.random() < rootprob:
31 graph[i] = [nullrev]
32 elif i == 1:
33 graph[i] = [0]
34 elif rng.random() < mergeprob:
35 if i == 2 or rng.random() < prevprob:
36 # p1 is prev
37 p1 = i - 1
38 else:
39 p1 = rng.randrange(i - 1)
40 p2 = rng.choice(list(range(0, p1)) + list(range(p1 + 1, i)))
41 graph[i] = [p1, p2]
42 elif rng.random() < prevprob:
43 graph[i] = [i - 1]
44 else:
45 graph[i] = [rng.randrange(i - 1)]
46
47 return graph
48
49
50 def buildancestorsets(graph):
51 ancs = [None] * len(graph)
52 for i in range(len(graph)):
53 ancs[i] = {i}
54 if graph[i] == [nullrev]:
55 continue
56 for p in graph[i]:
57 ancs[i].update(ancs[p])
58 return ancs
59
60
61 class naiveincrementalmissingancestors:
62 def __init__(self, ancs, bases):
63 self.ancs = ancs
64 self.bases = set(bases)
65
66 def addbases(self, newbases):
67 self.bases.update(newbases)
68
69 def removeancestorsfrom(self, revs):
70 for base in self.bases:
71 if base != nullrev:
72 revs.difference_update(self.ancs[base])
73 revs.discard(nullrev)
74
75 def missingancestors(self, revs):
76 res = set()
77 for rev in revs:
78 if rev != nullrev:
79 res.update(self.ancs[rev])
80 for base in self.bases:
81 if base != nullrev:
82 res.difference_update(self.ancs[base])
83 return sorted(res)
84
85
86 def test_missingancestors(seed, rng):
87 # empirically observed to take around 1 second
88 graphcount = 100
89 testcount = 10
90 inccount = 10
91 nerrs = [0]
92
93 # the default mu and sigma give us a nice distribution of mostly
94 # single-digit counts (including 0) with some higher ones
95 def lognormrandom(mu, sigma):
96 return int(math.floor(rng.lognormvariate(mu, sigma)))
97
98 def samplerevs(nodes, mu=1.1, sigma=0.8):
99 count = min(lognormrandom(mu, sigma), len(nodes))
100 return rng.sample(nodes, count)
101
102 def err(seed, graph, bases, seq, output, expected):
103 if nerrs[0] == 0:
104 print('seed:', hex(seed)[:-1], file=sys.stderr)
105 if gerrs[0] == 0:
106 print('graph:', graph, file=sys.stderr)
107 print('* bases:', bases, file=sys.stderr)
108 print('* seq: ', seq, file=sys.stderr)
109 print('* output: ', output, file=sys.stderr)
110 print('* expected:', expected, file=sys.stderr)
111 nerrs[0] += 1
112 gerrs[0] += 1
113
114 for g in range(graphcount):
115 graph = buildgraph(rng)
116 ancs = buildancestorsets(graph)
117 gerrs = [0]
118 for _ in range(testcount):
119 # start from nullrev to include it as a possibility
120 graphnodes = range(nullrev, len(graph))
121 bases = samplerevs(graphnodes)
122
123 # fast algorithm
124 inc = ancestor.incrementalmissingancestors(graph.__getitem__, bases)
125 # reference slow algorithm
126 naiveinc = naiveincrementalmissingancestors(ancs, bases)
127 seq = []
128 for _ in range(inccount):
129 if rng.random() < 0.2:
130 newbases = samplerevs(graphnodes)
131 seq.append(('addbases', newbases))
132 inc.addbases(newbases)
133 naiveinc.addbases(newbases)
134 if rng.random() < 0.4:
135 # larger set so that there are more revs to remove from
136 revs = samplerevs(graphnodes, mu=1.5)
137 seq.append(('removeancestorsfrom', revs))
138 hrevs = set(revs)
139 rrevs = set(revs)
140 inc.removeancestorsfrom(hrevs)
141 naiveinc.removeancestorsfrom(rrevs)
142 if hrevs != rrevs:
143 err(
144 seed,
145 graph,
146 bases,
147 seq,
148 sorted(hrevs),
149 sorted(rrevs),
150 )
151 else:
152 revs = samplerevs(graphnodes)
153 seq.append(('missingancestors', revs))
154 h = inc.missingancestors(revs)
155 r = naiveinc.missingancestors(revs)
156 if h != r:
157 err(seed, graph, bases, seq, h, r)
158
159
160 # graph is a dict of child->parent adjacency lists for this graph:
161 # o 13
162 # |
163 # | o 12
164 # | |
165 # | | o 11
166 # | | |\
167 # | | | | o 10
168 # | | | | |
169 # | o---+ | 9
170 # | | | | |
171 # o | | | | 8
172 # / / / /
173 # | | o | 7
174 # | | | |
175 # o---+ | 6
176 # / / /
177 # | | o 5
178 # | |/
179 # | o 4
180 # | |
181 # o | 3
182 # | |
183 # | o 2
184 # |/
185 # o 1
186 # |
187 # o 0
188
189 graph = {
190 0: [-1, -1],
191 1: [0, -1],
192 2: [1, -1],
193 3: [1, -1],
194 4: [2, -1],
195 5: [4, -1],
196 6: [4, -1],
197 7: [4, -1],
198 8: [-1, -1],
199 9: [6, 7],
200 10: [5, -1],
201 11: [3, 7],
202 12: [9, -1],
203 13: [8, -1],
204 }
205
206
207 def test_missingancestors_explicit():
208 """A few explicit cases, easier to check for catching errors in refactors.
209
210 The bigger graph at the end has been produced by the random generator
211 above, and we have some evidence that the other tests don't cover it.
212 """
213 for i, (bases, revs) in enumerate(
214 (
215 ({1, 2, 3, 4, 7}, set(range(10))),
216 ({10}, set({11, 12, 13, 14})),
217 ({7}, set({1, 2, 3, 4, 5})),
218 )
219 ):
220 print("%% removeancestorsfrom(), example %d" % (i + 1))
221 missanc = ancestor.incrementalmissingancestors(graph.get, bases)
222 missanc.removeancestorsfrom(revs)
223 print("remaining (sorted): %s" % sorted(list(revs)))
224
225 for i, (bases, revs) in enumerate(
226 (
227 ({10}, {11}),
228 ({11}, {10}),
229 ({7}, {9, 11}),
230 )
231 ):
232 print("%% missingancestors(), example %d" % (i + 1))
233 missanc = ancestor.incrementalmissingancestors(graph.get, bases)
234 print("return %s" % missanc.missingancestors(revs))
235
236 print("% removeancestorsfrom(), bigger graph")
237 vecgraph = [
238 [-1, -1],
239 [0, -1],
240 [1, 0],
241 [2, 1],
242 [3, -1],
243 [4, -1],
244 [5, 1],
245 [2, -1],
246 [7, -1],
247 [8, -1],
248 [9, -1],
249 [10, 1],
250 [3, -1],
251 [12, -1],
252 [13, -1],
253 [14, -1],
254 [4, -1],
255 [16, -1],
256 [17, -1],
257 [18, -1],
258 [19, 11],
259 [20, -1],
260 [21, -1],
261 [22, -1],
262 [23, -1],
263 [2, -1],
264 [3, -1],
265 [26, 24],
266 [27, -1],
267 [28, -1],
268 [12, -1],
269 [1, -1],
270 [1, 9],
271 [32, -1],
272 [33, -1],
273 [34, 31],
274 [35, -1],
275 [36, 26],
276 [37, -1],
277 [38, -1],
278 [39, -1],
279 [40, -1],
280 [41, -1],
281 [42, 26],
282 [0, -1],
283 [44, -1],
284 [45, 4],
285 [40, -1],
286 [47, -1],
287 [36, 0],
288 [49, -1],
289 [-1, -1],
290 [51, -1],
291 [52, -1],
292 [53, -1],
293 [14, -1],
294 [55, -1],
295 [15, -1],
296 [23, -1],
297 [58, -1],
298 [59, -1],
299 [2, -1],
300 [61, 59],
301 [62, -1],
302 [63, -1],
303 [-1, -1],
304 [65, -1],
305 [66, -1],
306 [67, -1],
307 [68, -1],
308 [37, 28],
309 [69, 25],
310 [71, -1],
311 [72, -1],
312 [50, 2],
313 [74, -1],
314 [12, -1],
315 [18, -1],
316 [77, -1],
317 [78, -1],
318 [79, -1],
319 [43, 33],
320 [81, -1],
321 [82, -1],
322 [83, -1],
323 [84, 45],
324 [85, -1],
325 [86, -1],
326 [-1, -1],
327 [88, -1],
328 [-1, -1],
329 [76, 83],
330 [44, -1],
331 [92, -1],
332 [93, -1],
333 [9, -1],
334 [95, 67],
335 [96, -1],
336 [97, -1],
337 [-1, -1],
338 ]
339 problem_rev = 28
340 problem_base = 70
341 # problem_rev is a parent of problem_base, but a faulty implementation
342 # could forget to remove it.
343 bases = {60, 26, 70, 3, 96, 19, 98, 49, 97, 47, 1, 6}
344 if problem_rev not in vecgraph[problem_base] or problem_base not in bases:
345 print("Conditions have changed")
346 missanc = ancestor.incrementalmissingancestors(vecgraph.__getitem__, bases)
347 revs = {4, 12, 41, 28, 68, 38, 1, 30, 56, 44}
348 missanc.removeancestorsfrom(revs)
349 if 28 in revs:
350 print("Failed!")
351 else:
352 print("Ok")
353
354
355 def genlazyancestors(revs, stoprev=0, inclusive=False):
356 print(
357 "%% lazy ancestor set for %s, stoprev = %s, inclusive = %s"
358 % (revs, stoprev, inclusive)
359 )
360 return ancestor.lazyancestors(
361 graph.get, revs, stoprev=stoprev, inclusive=inclusive
362 )
363
364
365 def printlazyancestors(s, l):
366 print('membership: %r' % [n for n in l if n in s])
367 print('iteration: %r' % list(s))
368
369
370 def test_lazyancestors():
371 # Empty revs
372 s = genlazyancestors([])
373 printlazyancestors(s, [3, 0, -1])
374
375 # Standard example
376 s = genlazyancestors([11, 13])
377 printlazyancestors(s, [11, 13, 7, 9, 8, 3, 6, 4, 1, -1, 0])
378
379 # Standard with ancestry in the initial set (1 is ancestor of 3)
380 s = genlazyancestors([1, 3])
381 printlazyancestors(s, [1, -1, 0])
382
383 # Including revs
384 s = genlazyancestors([11, 13], inclusive=True)
385 printlazyancestors(s, [11, 13, 7, 9, 8, 3, 6, 4, 1, -1, 0])
386
387 # Test with stoprev
388 s = genlazyancestors([11, 13], stoprev=6)
389 printlazyancestors(s, [11, 13, 7, 9, 8, 3, 6, 4, 1, -1, 0])
390 s = genlazyancestors([11, 13], stoprev=6, inclusive=True)
391 printlazyancestors(s, [11, 13, 7, 9, 8, 3, 6, 4, 1, -1, 0])
392
393 # Test with stoprev >= min(initrevs)
394 s = genlazyancestors([11, 13], stoprev=11, inclusive=True)
395 printlazyancestors(s, [11, 13, 7, 9, 8, 3, 6, 4, 1, -1, 0])
396 s = genlazyancestors([11, 13], stoprev=12, inclusive=True)
397 printlazyancestors(s, [11, 13, 7, 9, 8, 3, 6, 4, 1, -1, 0])
398
399 # Contiguous chains: 5->4, 2->1 (where 1 is in seen set), 1->0
400 s = genlazyancestors([10, 1], inclusive=True)
401 printlazyancestors(s, [2, 10, 4, 5, -1, 0, 1])
402
403
404 # The C gca algorithm requires a real repo. These are textual descriptions of
405 # DAGs that have been known to be problematic, and, optionally, known pairs
406 # of revisions and their expected ancestor list.
407 dagtests = [
408 (b'+2*2*2/*3/2', {}),
409 (b'+3*3/*2*2/*4*4/*4/2*4/2*2', {}),
410 (b'+2*2*/2*4*/4*/3*2/4', {(6, 7): [3, 5]}),
411 ]
412
413
414 def test_gca():
415 u = uimod.ui.load()
416 for i, (dag, tests) in enumerate(dagtests):
417 repo = repo_factory.repository(u, b'gca%d' % i, create=1)
418 cl = repo.changelog
419 if not hasattr(cl.index, 'ancestors'):
420 # C version not available
421 return
422
423 debugcommands.debugbuilddag(u, repo, dag)
424 # Compare the results of the Python and C versions. This does not
425 # include choosing a winner when more than one gca exists -- we make
426 # sure both return exactly the same set of gcas.
427 # Also compare against expected results, if available.
428 for a in cl:
429 for b in cl:
430 cgcas = sorted(cl.index.ancestors(a, b))
431 pygcas = sorted(ancestor.ancestors(cl.parentrevs, a, b))
432 expected = None
433 if (a, b) in tests:
434 expected = tests[(a, b)]
435 if cgcas != pygcas or (expected and cgcas != expected):
436 print(
437 "test_gca: for dag %s, gcas for %d, %d:" % (dag, a, b)
438 )
439 print(" C returned: %s" % cgcas)
440 print(" Python returned: %s" % pygcas)
441 if expected:
442 print(" expected: %s" % expected)
443
444
445 def main():
446 seed = None
447 opts, args = getopt.getopt(sys.argv[1:], 's:', ['seed='])
448 for o, a in opts:
449 if o in ('-s', '--seed'):
450 seed = int(a, base=0) # accepts base 10 or 16 strings
451
452 if seed is None:
453 try:
454 seed = int(binascii.hexlify(os.urandom(16)), 16)
455 except AttributeError:
456 seed = int(time.time() * 1000)
457
458 rng = random.Random(seed)
459 test_missingancestors_explicit()
460 test_missingancestors(seed, rng)
461 test_lazyancestors()
462 test_gca()
463
464
465 if __name__ == '__main__':
466 main()