##// END OF EJS Templates
setdiscovery: pass head revisions into sample functions...
Gregory Szorc -
r39207:abce899c default
parent child Browse files
Show More
@@ -1,291 +1,292 b''
1 # setdiscovery.py - improved discovery of common nodeset for mercurial
1 # setdiscovery.py - improved discovery of common nodeset for mercurial
2 #
2 #
3 # Copyright 2010 Benoit Boissinot <bboissin@gmail.com>
3 # Copyright 2010 Benoit Boissinot <bboissin@gmail.com>
4 # and Peter Arrenbrecht <peter@arrenbrecht.ch>
4 # and Peter Arrenbrecht <peter@arrenbrecht.ch>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8 """
8 """
9 Algorithm works in the following way. You have two repository: local and
9 Algorithm works in the following way. You have two repository: local and
10 remote. They both contains a DAG of changelists.
10 remote. They both contains a DAG of changelists.
11
11
12 The goal of the discovery protocol is to find one set of node *common*,
12 The goal of the discovery protocol is to find one set of node *common*,
13 the set of nodes shared by local and remote.
13 the set of nodes shared by local and remote.
14
14
15 One of the issue with the original protocol was latency, it could
15 One of the issue with the original protocol was latency, it could
16 potentially require lots of roundtrips to discover that the local repo was a
16 potentially require lots of roundtrips to discover that the local repo was a
17 subset of remote (which is a very common case, you usually have few changes
17 subset of remote (which is a very common case, you usually have few changes
18 compared to upstream, while upstream probably had lots of development).
18 compared to upstream, while upstream probably had lots of development).
19
19
20 The new protocol only requires one interface for the remote repo: `known()`,
20 The new protocol only requires one interface for the remote repo: `known()`,
21 which given a set of changelists tells you if they are present in the DAG.
21 which given a set of changelists tells you if they are present in the DAG.
22
22
23 The algorithm then works as follow:
23 The algorithm then works as follow:
24
24
25 - We will be using three sets, `common`, `missing`, `unknown`. Originally
25 - We will be using three sets, `common`, `missing`, `unknown`. Originally
26 all nodes are in `unknown`.
26 all nodes are in `unknown`.
27 - Take a sample from `unknown`, call `remote.known(sample)`
27 - Take a sample from `unknown`, call `remote.known(sample)`
28 - For each node that remote knows, move it and all its ancestors to `common`
28 - For each node that remote knows, move it and all its ancestors to `common`
29 - For each node that remote doesn't know, move it and all its descendants
29 - For each node that remote doesn't know, move it and all its descendants
30 to `missing`
30 to `missing`
31 - Iterate until `unknown` is empty
31 - Iterate until `unknown` is empty
32
32
33 There are a couple optimizations, first is instead of starting with a random
33 There are a couple optimizations, first is instead of starting with a random
34 sample of missing, start by sending all heads, in the case where the local
34 sample of missing, start by sending all heads, in the case where the local
35 repo is a subset, you computed the answer in one round trip.
35 repo is a subset, you computed the answer in one round trip.
36
36
37 Then you can do something similar to the bisecting strategy used when
37 Then you can do something similar to the bisecting strategy used when
38 finding faulty changesets. Instead of random samples, you can try picking
38 finding faulty changesets. Instead of random samples, you can try picking
39 nodes that will maximize the number of nodes that will be
39 nodes that will maximize the number of nodes that will be
40 classified with it (since all ancestors or descendants will be marked as well).
40 classified with it (since all ancestors or descendants will be marked as well).
41 """
41 """
42
42
43 from __future__ import absolute_import
43 from __future__ import absolute_import
44
44
45 import collections
45 import collections
46 import random
46 import random
47
47
48 from .i18n import _
48 from .i18n import _
49 from .node import (
49 from .node import (
50 nullid,
50 nullid,
51 nullrev,
51 nullrev,
52 )
52 )
53 from . import (
53 from . import (
54 dagutil,
54 dagutil,
55 error,
55 error,
56 util,
56 util,
57 )
57 )
58
58
59 def _updatesample(dag, revs, heads, sample, quicksamplesize=0):
59 def _updatesample(dag, revs, heads, sample, quicksamplesize=0):
60 """update an existing sample to match the expected size
60 """update an existing sample to match the expected size
61
61
62 The sample is updated with revs exponentially distant from each head of the
62 The sample is updated with revs exponentially distant from each head of the
63 <revs> set. (H~1, H~2, H~4, H~8, etc).
63 <revs> set. (H~1, H~2, H~4, H~8, etc).
64
64
65 If a target size is specified, the sampling will stop once this size is
65 If a target size is specified, the sampling will stop once this size is
66 reached. Otherwise sampling will happen until roots of the <revs> set are
66 reached. Otherwise sampling will happen until roots of the <revs> set are
67 reached.
67 reached.
68
68
69 :dag: a dag object from dagutil
69 :dag: a dag object from dagutil
70 :revs: set of revs we want to discover (if None, assume the whole dag)
70 :revs: set of revs we want to discover (if None, assume the whole dag)
71 :heads: set of DAG head revs
71 :heads: set of DAG head revs
72 :sample: a sample to update
72 :sample: a sample to update
73 :quicksamplesize: optional target size of the sample"""
73 :quicksamplesize: optional target size of the sample"""
74 dist = {}
74 dist = {}
75 visit = collections.deque(heads)
75 visit = collections.deque(heads)
76 seen = set()
76 seen = set()
77 factor = 1
77 factor = 1
78 while visit:
78 while visit:
79 curr = visit.popleft()
79 curr = visit.popleft()
80 if curr in seen:
80 if curr in seen:
81 continue
81 continue
82 d = dist.setdefault(curr, 1)
82 d = dist.setdefault(curr, 1)
83 if d > factor:
83 if d > factor:
84 factor *= 2
84 factor *= 2
85 if d == factor:
85 if d == factor:
86 sample.add(curr)
86 sample.add(curr)
87 if quicksamplesize and (len(sample) >= quicksamplesize):
87 if quicksamplesize and (len(sample) >= quicksamplesize):
88 return
88 return
89 seen.add(curr)
89 seen.add(curr)
90 for p in dag.parents(curr):
90 for p in dag.parents(curr):
91 if not revs or p in revs:
91 if not revs or p in revs:
92 dist.setdefault(p, d + 1)
92 dist.setdefault(p, d + 1)
93 visit.append(p)
93 visit.append(p)
94
94
95 def _takequicksample(repo, dag, revs, size):
95 def _takequicksample(repo, dag, headrevs, revs, size):
96 """takes a quick sample of size <size>
96 """takes a quick sample of size <size>
97
97
98 It is meant for initial sampling and focuses on querying heads and close
98 It is meant for initial sampling and focuses on querying heads and close
99 ancestors of heads.
99 ancestors of heads.
100
100
101 :dag: a dag object
101 :dag: a dag object
102 :headrevs: set of head revisions in local DAG to consider
102 :revs: set of revs to discover
103 :revs: set of revs to discover
103 :size: the maximum size of the sample"""
104 :size: the maximum size of the sample"""
104 sample = set(repo.revs('heads(%ld)', revs))
105 sample = set(repo.revs('heads(%ld)', revs))
105
106
106 if len(sample) >= size:
107 if len(sample) >= size:
107 return _limitsample(sample, size)
108 return _limitsample(sample, size)
108
109
109 _updatesample(dag, None, dag.heads(), sample, quicksamplesize=size)
110 _updatesample(dag, None, headrevs, sample, quicksamplesize=size)
110 return sample
111 return sample
111
112
112 def _takefullsample(repo, dag, revs, size):
113 def _takefullsample(repo, dag, headrevs, revs, size):
113 sample = set(repo.revs('heads(%ld)', revs))
114 sample = set(repo.revs('heads(%ld)', revs))
114
115
115 # update from heads
116 # update from heads
116 _updatesample(dag, revs, dag.headsetofconnecteds(revs), sample)
117 _updatesample(dag, revs, dag.headsetofconnecteds(revs), sample)
117 # update from roots
118 # update from roots
118 inverteddag = dag.inverse()
119 inverteddag = dag.inverse()
119 _updatesample(inverteddag, revs, inverteddag.headsetofconnecteds(revs),
120 _updatesample(inverteddag, revs, inverteddag.headsetofconnecteds(revs),
120 sample)
121 sample)
121 assert sample
122 assert sample
122 sample = _limitsample(sample, size)
123 sample = _limitsample(sample, size)
123 if len(sample) < size:
124 if len(sample) < size:
124 more = size - len(sample)
125 more = size - len(sample)
125 sample.update(random.sample(list(revs - sample), more))
126 sample.update(random.sample(list(revs - sample), more))
126 return sample
127 return sample
127
128
128 def _limitsample(sample, desiredlen):
129 def _limitsample(sample, desiredlen):
129 """return a random subset of sample of at most desiredlen item"""
130 """return a random subset of sample of at most desiredlen item"""
130 if len(sample) > desiredlen:
131 if len(sample) > desiredlen:
131 sample = set(random.sample(sample, desiredlen))
132 sample = set(random.sample(sample, desiredlen))
132 return sample
133 return sample
133
134
134 def findcommonheads(ui, local, remote,
135 def findcommonheads(ui, local, remote,
135 initialsamplesize=100,
136 initialsamplesize=100,
136 fullsamplesize=200,
137 fullsamplesize=200,
137 abortwhenunrelated=True,
138 abortwhenunrelated=True,
138 ancestorsof=None):
139 ancestorsof=None):
139 '''Return a tuple (common, anyincoming, remoteheads) used to identify
140 '''Return a tuple (common, anyincoming, remoteheads) used to identify
140 missing nodes from or in remote.
141 missing nodes from or in remote.
141 '''
142 '''
142 start = util.timer()
143 start = util.timer()
143
144
144 roundtrips = 0
145 roundtrips = 0
145 cl = local.changelog
146 cl = local.changelog
146 clnode = cl.node
147 clnode = cl.node
147 clrev = cl.rev
148 clrev = cl.rev
148
149
149 if ancestorsof is not None:
150 if ancestorsof is not None:
150 ownheads = [clrev(n) for n in ancestorsof]
151 ownheads = [clrev(n) for n in ancestorsof]
151 else:
152 else:
152 ownheads = [rev for rev in cl.headrevs() if rev != nullrev]
153 ownheads = [rev for rev in cl.headrevs() if rev != nullrev]
153
154
154 dag = dagutil.revlogdag(cl, localsubset=ownheads)
155 dag = dagutil.revlogdag(cl, localsubset=ownheads)
155
156
156 # early exit if we know all the specified remote heads already
157 # early exit if we know all the specified remote heads already
157 ui.debug("query 1; heads\n")
158 ui.debug("query 1; heads\n")
158 roundtrips += 1
159 roundtrips += 1
159 sample = _limitsample(ownheads, initialsamplesize)
160 sample = _limitsample(ownheads, initialsamplesize)
160 # indices between sample and externalized version must match
161 # indices between sample and externalized version must match
161 sample = list(sample)
162 sample = list(sample)
162
163
163 with remote.commandexecutor() as e:
164 with remote.commandexecutor() as e:
164 fheads = e.callcommand('heads', {})
165 fheads = e.callcommand('heads', {})
165 fknown = e.callcommand('known', {
166 fknown = e.callcommand('known', {
166 'nodes': [clnode(r) for r in sample],
167 'nodes': [clnode(r) for r in sample],
167 })
168 })
168
169
169 srvheadhashes, yesno = fheads.result(), fknown.result()
170 srvheadhashes, yesno = fheads.result(), fknown.result()
170
171
171 if cl.tip() == nullid:
172 if cl.tip() == nullid:
172 if srvheadhashes != [nullid]:
173 if srvheadhashes != [nullid]:
173 return [nullid], True, srvheadhashes
174 return [nullid], True, srvheadhashes
174 return [nullid], False, []
175 return [nullid], False, []
175
176
176 # start actual discovery (we note this before the next "if" for
177 # start actual discovery (we note this before the next "if" for
177 # compatibility reasons)
178 # compatibility reasons)
178 ui.status(_("searching for changes\n"))
179 ui.status(_("searching for changes\n"))
179
180
180 srvheads = []
181 srvheads = []
181 for node in srvheadhashes:
182 for node in srvheadhashes:
182 if node == nullid:
183 if node == nullid:
183 continue
184 continue
184
185
185 try:
186 try:
186 srvheads.append(clrev(node))
187 srvheads.append(clrev(node))
187 # Catches unknown and filtered nodes.
188 # Catches unknown and filtered nodes.
188 except error.LookupError:
189 except error.LookupError:
189 continue
190 continue
190
191
191 if len(srvheads) == len(srvheadhashes):
192 if len(srvheads) == len(srvheadhashes):
192 ui.debug("all remote heads known locally\n")
193 ui.debug("all remote heads known locally\n")
193 return srvheadhashes, False, srvheadhashes
194 return srvheadhashes, False, srvheadhashes
194
195
195 if len(sample) == len(ownheads) and all(yesno):
196 if len(sample) == len(ownheads) and all(yesno):
196 ui.note(_("all local heads known remotely\n"))
197 ui.note(_("all local heads known remotely\n"))
197 ownheadhashes = [clnode(r) for r in ownheads]
198 ownheadhashes = [clnode(r) for r in ownheads]
198 return ownheadhashes, True, srvheadhashes
199 return ownheadhashes, True, srvheadhashes
199
200
200 # full blown discovery
201 # full blown discovery
201
202
202 # own nodes I know we both know
203 # own nodes I know we both know
203 # treat remote heads (and maybe own heads) as a first implicit sample
204 # treat remote heads (and maybe own heads) as a first implicit sample
204 # response
205 # response
205 common = cl.incrementalmissingrevs(srvheads)
206 common = cl.incrementalmissingrevs(srvheads)
206 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
207 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
207 common.addbases(commoninsample)
208 common.addbases(commoninsample)
208 # own nodes where I don't know if remote knows them
209 # own nodes where I don't know if remote knows them
209 undecided = set(common.missingancestors(ownheads))
210 undecided = set(common.missingancestors(ownheads))
210 # own nodes I know remote lacks
211 # own nodes I know remote lacks
211 missing = set()
212 missing = set()
212
213
213 full = False
214 full = False
214 progress = ui.makeprogress(_('searching'), unit=_('queries'))
215 progress = ui.makeprogress(_('searching'), unit=_('queries'))
215 while undecided:
216 while undecided:
216
217
217 if sample:
218 if sample:
218 missinginsample = [n for i, n in enumerate(sample) if not yesno[i]]
219 missinginsample = [n for i, n in enumerate(sample) if not yesno[i]]
219
220
220 if missing:
221 if missing:
221 missing.update(local.revs('descendants(%ld) - descendants(%ld)',
222 missing.update(local.revs('descendants(%ld) - descendants(%ld)',
222 missinginsample, missing))
223 missinginsample, missing))
223 else:
224 else:
224 missing.update(local.revs('descendants(%ld)', missinginsample))
225 missing.update(local.revs('descendants(%ld)', missinginsample))
225
226
226 undecided.difference_update(missing)
227 undecided.difference_update(missing)
227
228
228 if not undecided:
229 if not undecided:
229 break
230 break
230
231
231 if full or common.hasbases():
232 if full or common.hasbases():
232 if full:
233 if full:
233 ui.note(_("sampling from both directions\n"))
234 ui.note(_("sampling from both directions\n"))
234 else:
235 else:
235 ui.debug("taking initial sample\n")
236 ui.debug("taking initial sample\n")
236 samplefunc = _takefullsample
237 samplefunc = _takefullsample
237 targetsize = fullsamplesize
238 targetsize = fullsamplesize
238 else:
239 else:
239 # use even cheaper initial sample
240 # use even cheaper initial sample
240 ui.debug("taking quick initial sample\n")
241 ui.debug("taking quick initial sample\n")
241 samplefunc = _takequicksample
242 samplefunc = _takequicksample
242 targetsize = initialsamplesize
243 targetsize = initialsamplesize
243 if len(undecided) < targetsize:
244 if len(undecided) < targetsize:
244 sample = list(undecided)
245 sample = list(undecided)
245 else:
246 else:
246 sample = samplefunc(local, dag, undecided, targetsize)
247 sample = samplefunc(local, dag, ownheads, undecided, targetsize)
247
248
248 roundtrips += 1
249 roundtrips += 1
249 progress.update(roundtrips)
250 progress.update(roundtrips)
250 ui.debug("query %i; still undecided: %i, sample size is: %i\n"
251 ui.debug("query %i; still undecided: %i, sample size is: %i\n"
251 % (roundtrips, len(undecided), len(sample)))
252 % (roundtrips, len(undecided), len(sample)))
252 # indices between sample and externalized version must match
253 # indices between sample and externalized version must match
253 sample = list(sample)
254 sample = list(sample)
254
255
255 with remote.commandexecutor() as e:
256 with remote.commandexecutor() as e:
256 yesno = e.callcommand('known', {
257 yesno = e.callcommand('known', {
257 'nodes': [clnode(r) for r in sample],
258 'nodes': [clnode(r) for r in sample],
258 }).result()
259 }).result()
259
260
260 full = True
261 full = True
261
262
262 if sample:
263 if sample:
263 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
264 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
264 common.addbases(commoninsample)
265 common.addbases(commoninsample)
265 common.removeancestorsfrom(undecided)
266 common.removeancestorsfrom(undecided)
266
267
267 # heads(common) == heads(common.bases) since common represents common.bases
268 # heads(common) == heads(common.bases) since common represents common.bases
268 # and all its ancestors
269 # and all its ancestors
269 result = dag.headsetofconnecteds(common.bases)
270 result = dag.headsetofconnecteds(common.bases)
270 # common.bases can include nullrev, but our contract requires us to not
271 # common.bases can include nullrev, but our contract requires us to not
271 # return any heads in that case, so discard that
272 # return any heads in that case, so discard that
272 result.discard(nullrev)
273 result.discard(nullrev)
273 elapsed = util.timer() - start
274 elapsed = util.timer() - start
274 progress.complete()
275 progress.complete()
275 ui.debug("%d total queries in %.4fs\n" % (roundtrips, elapsed))
276 ui.debug("%d total queries in %.4fs\n" % (roundtrips, elapsed))
276 msg = ('found %d common and %d unknown server heads,'
277 msg = ('found %d common and %d unknown server heads,'
277 ' %d roundtrips in %.4fs\n')
278 ' %d roundtrips in %.4fs\n')
278 missing = set(result) - set(srvheads)
279 missing = set(result) - set(srvheads)
279 ui.log('discovery', msg, len(result), len(missing), roundtrips,
280 ui.log('discovery', msg, len(result), len(missing), roundtrips,
280 elapsed)
281 elapsed)
281
282
282 if not result and srvheadhashes != [nullid]:
283 if not result and srvheadhashes != [nullid]:
283 if abortwhenunrelated:
284 if abortwhenunrelated:
284 raise error.Abort(_("repository is unrelated"))
285 raise error.Abort(_("repository is unrelated"))
285 else:
286 else:
286 ui.warn(_("warning: repository is unrelated\n"))
287 ui.warn(_("warning: repository is unrelated\n"))
287 return ({nullid}, True, srvheadhashes,)
288 return ({nullid}, True, srvheadhashes,)
288
289
289 anyincoming = (srvheadhashes != [nullid])
290 anyincoming = (srvheadhashes != [nullid])
290 result = {clnode(r) for r in result}
291 result = {clnode(r) for r in result}
291 return result, anyincoming, srvheadhashes
292 return result, anyincoming, srvheadhashes
General Comments 0
You need to be logged in to leave comments. Login now