##// END OF EJS Templates
setdiscovery: remove '_setupsample' function...
Pierre-Yves David -
r23817:813aaaf2 default
parent child Browse files
Show More
@@ -1,259 +1,250
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 node import nullid, nullrev
43 from node import nullid, nullrev
44 from i18n import _
44 from i18n import _
45 import random
45 import random
46 import util, dagutil
46 import util, dagutil
47
47
48 def _updatesample(dag, nodes, sample, quicksamplesize=0):
48 def _updatesample(dag, nodes, sample, quicksamplesize=0):
49 """update an existing sample to match the expected size
49 """update an existing sample to match the expected size
50
50
51 The sample is updated with nodes exponentially distant from each head of the
51 The sample is updated with nodes exponentially distant from each head of the
52 <nodes> set. (H~1, H~2, H~4, H~8, etc).
52 <nodes> set. (H~1, H~2, H~4, H~8, etc).
53
53
54 If a target size is specified, the sampling will stop once this size is
54 If a target size is specified, the sampling will stop once this size is
55 reached. Otherwise sampling will happen until roots of the <nodes> set are
55 reached. Otherwise sampling will happen until roots of the <nodes> set are
56 reached.
56 reached.
57
57
58 :dag: a dag object from dagutil
58 :dag: a dag object from dagutil
59 :nodes: set of nodes we want to discover (if None, assume the whole dag)
59 :nodes: set of nodes we want to discover (if None, assume the whole dag)
60 :sample: a sample to update
60 :sample: a sample to update
61 :quicksamplesize: optional target size of the sample"""
61 :quicksamplesize: optional target size of the sample"""
62 # if nodes is empty we scan the entire graph
62 # if nodes is empty we scan the entire graph
63 if nodes:
63 if nodes:
64 heads = dag.headsetofconnecteds(nodes)
64 heads = dag.headsetofconnecteds(nodes)
65 else:
65 else:
66 heads = dag.heads()
66 heads = dag.heads()
67 dist = {}
67 dist = {}
68 visit = util.deque(heads)
68 visit = util.deque(heads)
69 seen = set()
69 seen = set()
70 factor = 1
70 factor = 1
71 while visit:
71 while visit:
72 curr = visit.popleft()
72 curr = visit.popleft()
73 if curr in seen:
73 if curr in seen:
74 continue
74 continue
75 d = dist.setdefault(curr, 1)
75 d = dist.setdefault(curr, 1)
76 if d > factor:
76 if d > factor:
77 factor *= 2
77 factor *= 2
78 if d == factor:
78 if d == factor:
79 sample.add(curr)
79 sample.add(curr)
80 if quicksamplesize and (len(sample) >= quicksamplesize):
80 if quicksamplesize and (len(sample) >= quicksamplesize):
81 return
81 return
82 seen.add(curr)
82 seen.add(curr)
83 for p in dag.parents(curr):
83 for p in dag.parents(curr):
84 if not nodes or p in nodes:
84 if not nodes or p in nodes:
85 dist.setdefault(p, d + 1)
85 dist.setdefault(p, d + 1)
86 visit.append(p)
86 visit.append(p)
87
87
88 def _setupsample(dag, nodes, size):
89 always = dag.headsetofconnecteds(nodes)
90 desiredlen = size - len(always)
91 if desiredlen <= 0:
92 # This could be bad if there are very many heads, all unknown to the
93 # server. We're counting on long request support here.
94 return always, None, desiredlen
95 return always, set(), desiredlen
96
97 def _takequicksample(dag, nodes, size):
88 def _takequicksample(dag, nodes, size):
98 """takes a quick sample of size <size>
89 """takes a quick sample of size <size>
99
90
100 It is meant for initial sampling and focuses on querying heads and close
91 It is meant for initial sampling and focuses on querying heads and close
101 ancestors of heads.
92 ancestors of heads.
102
93
103 :dag: a dag object
94 :dag: a dag object
104 :nodes: set of nodes to discover
95 :nodes: set of nodes to discover
105 :size: the maximum size of the sample"""
96 :size: the maximum size of the sample"""
106 sample = dag.headsetofconnecteds(nodes)
97 sample = dag.headsetofconnecteds(nodes)
107 if size <= len(sample):
98 if size <= len(sample):
108 return _limitsample(sample, size)
99 return _limitsample(sample, size)
109 _updatesample(dag, None, sample, quicksamplesize=size)
100 _updatesample(dag, None, sample, quicksamplesize=size)
110 return sample
101 return sample
111
102
112 def _takefullsample(dag, nodes, size):
103 def _takefullsample(dag, nodes, size):
113 sample = dag.headsetofconnecteds(nodes)
104 sample = dag.headsetofconnecteds(nodes)
114 # update from heads
105 # update from heads
115 _updatesample(dag, nodes, sample)
106 _updatesample(dag, nodes, sample)
116 # update from roots
107 # update from roots
117 _updatesample(dag.inverse(), nodes, sample)
108 _updatesample(dag.inverse(), nodes, sample)
118 assert sample
109 assert sample
119 sample = _limitsample(sample, size)
110 sample = _limitsample(sample, size)
120 if len(sample) < size:
111 if len(sample) < size:
121 more = size - len(sample)
112 more = size - len(sample)
122 sample.update(random.sample(list(nodes - sample), more))
113 sample.update(random.sample(list(nodes - sample), more))
123 return sample
114 return sample
124
115
125 def _limitsample(sample, desiredlen):
116 def _limitsample(sample, desiredlen):
126 """return a random subset of sample of at most desiredlen item"""
117 """return a random subset of sample of at most desiredlen item"""
127 if len(sample) > desiredlen:
118 if len(sample) > desiredlen:
128 sample = set(random.sample(sample, desiredlen))
119 sample = set(random.sample(sample, desiredlen))
129 return sample
120 return sample
130
121
131 def findcommonheads(ui, local, remote,
122 def findcommonheads(ui, local, remote,
132 initialsamplesize=100,
123 initialsamplesize=100,
133 fullsamplesize=200,
124 fullsamplesize=200,
134 abortwhenunrelated=True):
125 abortwhenunrelated=True):
135 '''Return a tuple (common, anyincoming, remoteheads) used to identify
126 '''Return a tuple (common, anyincoming, remoteheads) used to identify
136 missing nodes from or in remote.
127 missing nodes from or in remote.
137 '''
128 '''
138 roundtrips = 0
129 roundtrips = 0
139 cl = local.changelog
130 cl = local.changelog
140 dag = dagutil.revlogdag(cl)
131 dag = dagutil.revlogdag(cl)
141
132
142 # early exit if we know all the specified remote heads already
133 # early exit if we know all the specified remote heads already
143 ui.debug("query 1; heads\n")
134 ui.debug("query 1; heads\n")
144 roundtrips += 1
135 roundtrips += 1
145 ownheads = dag.heads()
136 ownheads = dag.heads()
146 sample = _limitsample(ownheads, initialsamplesize)
137 sample = _limitsample(ownheads, initialsamplesize)
147 # indices between sample and externalized version must match
138 # indices between sample and externalized version must match
148 sample = list(sample)
139 sample = list(sample)
149 if remote.local():
140 if remote.local():
150 # stopgap until we have a proper localpeer that supports batch()
141 # stopgap until we have a proper localpeer that supports batch()
151 srvheadhashes = remote.heads()
142 srvheadhashes = remote.heads()
152 yesno = remote.known(dag.externalizeall(sample))
143 yesno = remote.known(dag.externalizeall(sample))
153 elif remote.capable('batch'):
144 elif remote.capable('batch'):
154 batch = remote.batch()
145 batch = remote.batch()
155 srvheadhashesref = batch.heads()
146 srvheadhashesref = batch.heads()
156 yesnoref = batch.known(dag.externalizeall(sample))
147 yesnoref = batch.known(dag.externalizeall(sample))
157 batch.submit()
148 batch.submit()
158 srvheadhashes = srvheadhashesref.value
149 srvheadhashes = srvheadhashesref.value
159 yesno = yesnoref.value
150 yesno = yesnoref.value
160 else:
151 else:
161 # compatibility with pre-batch, but post-known remotes during 1.9
152 # compatibility with pre-batch, but post-known remotes during 1.9
162 # development
153 # development
163 srvheadhashes = remote.heads()
154 srvheadhashes = remote.heads()
164 sample = []
155 sample = []
165
156
166 if cl.tip() == nullid:
157 if cl.tip() == nullid:
167 if srvheadhashes != [nullid]:
158 if srvheadhashes != [nullid]:
168 return [nullid], True, srvheadhashes
159 return [nullid], True, srvheadhashes
169 return [nullid], False, []
160 return [nullid], False, []
170
161
171 # start actual discovery (we note this before the next "if" for
162 # start actual discovery (we note this before the next "if" for
172 # compatibility reasons)
163 # compatibility reasons)
173 ui.status(_("searching for changes\n"))
164 ui.status(_("searching for changes\n"))
174
165
175 srvheads = dag.internalizeall(srvheadhashes, filterunknown=True)
166 srvheads = dag.internalizeall(srvheadhashes, filterunknown=True)
176 if len(srvheads) == len(srvheadhashes):
167 if len(srvheads) == len(srvheadhashes):
177 ui.debug("all remote heads known locally\n")
168 ui.debug("all remote heads known locally\n")
178 return (srvheadhashes, False, srvheadhashes,)
169 return (srvheadhashes, False, srvheadhashes,)
179
170
180 if sample and len(ownheads) <= initialsamplesize and util.all(yesno):
171 if sample and len(ownheads) <= initialsamplesize and util.all(yesno):
181 ui.note(_("all local heads known remotely\n"))
172 ui.note(_("all local heads known remotely\n"))
182 ownheadhashes = dag.externalizeall(ownheads)
173 ownheadhashes = dag.externalizeall(ownheads)
183 return (ownheadhashes, True, srvheadhashes,)
174 return (ownheadhashes, True, srvheadhashes,)
184
175
185 # full blown discovery
176 # full blown discovery
186
177
187 # own nodes I know we both know
178 # own nodes I know we both know
188 # treat remote heads (and maybe own heads) as a first implicit sample
179 # treat remote heads (and maybe own heads) as a first implicit sample
189 # response
180 # response
190 common = cl.incrementalmissingrevs(srvheads)
181 common = cl.incrementalmissingrevs(srvheads)
191 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
182 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
192 common.addbases(commoninsample)
183 common.addbases(commoninsample)
193 # own nodes where I don't know if remote knows them
184 # own nodes where I don't know if remote knows them
194 undecided = set(common.missingancestors(ownheads))
185 undecided = set(common.missingancestors(ownheads))
195 # own nodes I know remote lacks
186 # own nodes I know remote lacks
196 missing = set()
187 missing = set()
197
188
198 full = False
189 full = False
199 while undecided:
190 while undecided:
200
191
201 if sample:
192 if sample:
202 missinginsample = [n for i, n in enumerate(sample) if not yesno[i]]
193 missinginsample = [n for i, n in enumerate(sample) if not yesno[i]]
203 missing.update(dag.descendantset(missinginsample, missing))
194 missing.update(dag.descendantset(missinginsample, missing))
204
195
205 undecided.difference_update(missing)
196 undecided.difference_update(missing)
206
197
207 if not undecided:
198 if not undecided:
208 break
199 break
209
200
210 if full or common.hasbases():
201 if full or common.hasbases():
211 if full:
202 if full:
212 ui.note(_("sampling from both directions\n"))
203 ui.note(_("sampling from both directions\n"))
213 else:
204 else:
214 ui.debug("taking initial sample\n")
205 ui.debug("taking initial sample\n")
215 samplefunc = _takefullsample
206 samplefunc = _takefullsample
216 targetsize = fullsamplesize
207 targetsize = fullsamplesize
217 else:
208 else:
218 # use even cheaper initial sample
209 # use even cheaper initial sample
219 ui.debug("taking quick initial sample\n")
210 ui.debug("taking quick initial sample\n")
220 samplefunc = _takequicksample
211 samplefunc = _takequicksample
221 targetsize = initialsamplesize
212 targetsize = initialsamplesize
222 if len(undecided) < targetsize:
213 if len(undecided) < targetsize:
223 sample = list(undecided)
214 sample = list(undecided)
224 else:
215 else:
225 sample = samplefunc(dag, undecided, targetsize)
216 sample = samplefunc(dag, undecided, targetsize)
226 sample = _limitsample(sample, targetsize)
217 sample = _limitsample(sample, targetsize)
227
218
228 roundtrips += 1
219 roundtrips += 1
229 ui.progress(_('searching'), roundtrips, unit=_('queries'))
220 ui.progress(_('searching'), roundtrips, unit=_('queries'))
230 ui.debug("query %i; still undecided: %i, sample size is: %i\n"
221 ui.debug("query %i; still undecided: %i, sample size is: %i\n"
231 % (roundtrips, len(undecided), len(sample)))
222 % (roundtrips, len(undecided), len(sample)))
232 # indices between sample and externalized version must match
223 # indices between sample and externalized version must match
233 sample = list(sample)
224 sample = list(sample)
234 yesno = remote.known(dag.externalizeall(sample))
225 yesno = remote.known(dag.externalizeall(sample))
235 full = True
226 full = True
236
227
237 if sample:
228 if sample:
238 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
229 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
239 common.addbases(commoninsample)
230 common.addbases(commoninsample)
240 common.removeancestorsfrom(undecided)
231 common.removeancestorsfrom(undecided)
241
232
242 # heads(common) == heads(common.bases) since common represents common.bases
233 # heads(common) == heads(common.bases) since common represents common.bases
243 # and all its ancestors
234 # and all its ancestors
244 result = dag.headsetofconnecteds(common.bases)
235 result = dag.headsetofconnecteds(common.bases)
245 # common.bases can include nullrev, but our contract requires us to not
236 # common.bases can include nullrev, but our contract requires us to not
246 # return any heads in that case, so discard that
237 # return any heads in that case, so discard that
247 result.discard(nullrev)
238 result.discard(nullrev)
248 ui.progress(_('searching'), None)
239 ui.progress(_('searching'), None)
249 ui.debug("%d total queries\n" % roundtrips)
240 ui.debug("%d total queries\n" % roundtrips)
250
241
251 if not result and srvheadhashes != [nullid]:
242 if not result and srvheadhashes != [nullid]:
252 if abortwhenunrelated:
243 if abortwhenunrelated:
253 raise util.Abort(_("repository is unrelated"))
244 raise util.Abort(_("repository is unrelated"))
254 else:
245 else:
255 ui.warn(_("warning: repository is unrelated\n"))
246 ui.warn(_("warning: repository is unrelated\n"))
256 return (set([nullid]), True, srvheadhashes,)
247 return (set([nullid]), True, srvheadhashes,)
257
248
258 anyincoming = (srvheadhashes != [nullid])
249 anyincoming = (srvheadhashes != [nullid])
259 return dag.externalizeall(result), anyincoming, srvheadhashes
250 return dag.externalizeall(result), anyincoming, srvheadhashes
General Comments 0
You need to be logged in to leave comments. Login now