test_dht.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import time
  2. import asyncio
  3. import multiprocessing as mp
  4. import random
  5. import heapq
  6. import uuid
  7. from itertools import chain
  8. from typing import Optional
  9. import numpy as np
  10. import hivemind
  11. from typing import List, Dict
  12. from hivemind import get_dht_time
  13. from hivemind.dht.node import DHTID, Endpoint, DHTNode, LOCALHOST, DHTProtocol
  14. from hivemind.dht.protocol import LocalStorage
  15. def run_protocol_listener(port: int, dhtid: DHTID, started: mp.synchronize.Event, ping: Optional[Endpoint] = None):
  16. loop = asyncio.get_event_loop()
  17. protocol = loop.run_until_complete(DHTProtocol.create(
  18. dhtid, bucket_size=20, depth_modulo=5, num_replicas=3, wait_timeout=5, listen_on=f"{LOCALHOST}:{port}"))
  19. assert protocol.port == port
  20. print(f"Started peer id={protocol.node_id} port={port}", flush=True)
  21. if ping is not None:
  22. loop.run_until_complete(protocol.call_ping(ping))
  23. started.set()
  24. loop.run_until_complete(protocol.server.wait_for_termination())
  25. print(f"Finished peer id={protocol.node_id} port={port}", flush=True)
  26. def test_dht_protocol():
  27. # create the first peer
  28. peer1_port, peer1_id, peer1_started = hivemind.find_open_port(), DHTID.generate(), mp.Event()
  29. peer1_proc = mp.Process(target=run_protocol_listener, args=(peer1_port, peer1_id, peer1_started), daemon=True)
  30. peer1_proc.start(), peer1_started.wait()
  31. # create another peer that connects to the first peer
  32. peer2_port, peer2_id, peer2_started = hivemind.find_open_port(), DHTID.generate(), mp.Event()
  33. peer2_proc = mp.Process(target=run_protocol_listener, args=(peer2_port, peer2_id, peer2_started),
  34. kwargs={'ping': f'{LOCALHOST}:{peer1_port}'}, daemon=True)
  35. peer2_proc.start(), peer2_started.wait()
  36. test_success = mp.Event()
  37. def _tester():
  38. # note: we run everything in a separate process to re-initialize all global states from scratch
  39. # this helps us avoid undesirable side-effects when running multiple tests in sequence
  40. loop = asyncio.get_event_loop()
  41. for listen in [False, True]: # note: order matters, this test assumes that first run uses listen=False
  42. protocol = loop.run_until_complete(DHTProtocol.create(
  43. DHTID.generate(), bucket_size=20, depth_modulo=5, wait_timeout=5, num_replicas=3, listen=listen))
  44. print(f"Self id={protocol.node_id}", flush=True)
  45. assert loop.run_until_complete(protocol.call_ping(f'{LOCALHOST}:{peer1_port}')) == peer1_id
  46. key, value, expiration = DHTID.generate(), [random.random(), {'ololo': 'pyshpysh'}], get_dht_time() + 1e3
  47. store_ok = loop.run_until_complete(protocol.call_store(
  48. f'{LOCALHOST}:{peer1_port}', [key], [hivemind.MSGPackSerializer.dumps(value)], expiration)
  49. )
  50. assert all(store_ok), "DHT rejected a trivial store"
  51. # peer 1 must know about peer 2
  52. recv_value_bytes, recv_expiration, nodes_found = loop.run_until_complete(
  53. protocol.call_find(f'{LOCALHOST}:{peer1_port}', [key]))[key]
  54. recv_value = hivemind.MSGPackSerializer.loads(recv_value_bytes)
  55. (recv_id, recv_endpoint) = next(iter(nodes_found.items()))
  56. assert recv_id == peer2_id and recv_endpoint == f"{LOCALHOST}:{peer2_port}", \
  57. f"expected id={peer2_id}, peer={LOCALHOST}:{peer2_port} but got {recv_id}, {recv_endpoint}"
  58. assert recv_value == value and recv_expiration == expiration, "call_find_value expected " \
  59. f"{value} (expires by {expiration}) but got {recv_value} (expires by {recv_expiration})"
  60. # peer 2 must know about peer 1, but not have a *random* nonexistent value
  61. dummy_key = DHTID.generate()
  62. recv_dummy_value, recv_dummy_expiration, nodes_found_2 = loop.run_until_complete(
  63. protocol.call_find(f'{LOCALHOST}:{peer2_port}', [dummy_key]))[dummy_key]
  64. assert recv_dummy_value is None and recv_dummy_expiration is None, "Non-existent keys shouldn't have values"
  65. (recv_id, recv_endpoint) = next(iter(nodes_found_2.items()))
  66. assert recv_id == peer1_id and recv_endpoint == f"{LOCALHOST}:{peer1_port}", \
  67. f"expected id={peer1_id}, peer={LOCALHOST}:{peer1_port} but got {recv_id}, {recv_endpoint}"
  68. # cause a non-response by querying a nonexistent peer
  69. dummy_port = hivemind.find_open_port()
  70. assert loop.run_until_complete(protocol.call_find(f"{LOCALHOST}:{dummy_port}", [key])) is None
  71. if listen:
  72. loop.run_until_complete(protocol.shutdown())
  73. print("DHTProtocol test finished sucessfully!")
  74. test_success.set()
  75. tester = mp.Process(target=_tester, daemon=True)
  76. tester.start()
  77. tester.join()
  78. assert test_success.is_set()
  79. peer1_proc.terminate()
  80. peer2_proc.terminate()
  81. def test_empty_table():
  82. """ Test RPC methods with empty routing table """
  83. peer_port, peer_id, peer_started = hivemind.find_open_port(), DHTID.generate(), mp.Event()
  84. peer_proc = mp.Process(target=run_protocol_listener, args=(peer_port, peer_id, peer_started), daemon=True)
  85. peer_proc.start(), peer_started.wait()
  86. test_success = mp.Event()
  87. def _tester():
  88. # note: we run everything in a separate process to re-initialize all global states from scratch
  89. # this helps us avoid undesirable side-effects when running multiple tests in sequence
  90. loop = asyncio.get_event_loop()
  91. protocol = loop.run_until_complete(DHTProtocol.create(
  92. DHTID.generate(), bucket_size=20, depth_modulo=5, wait_timeout=5, num_replicas=3, listen=False))
  93. key, value, expiration = DHTID.generate(), [random.random(), {'ololo': 'pyshpysh'}], get_dht_time() + 1e3
  94. recv_value_bytes, recv_expiration, nodes_found = loop.run_until_complete(
  95. protocol.call_find(f'{LOCALHOST}:{peer_port}', [key]))[key]
  96. assert recv_value_bytes is None and recv_expiration is None and len(nodes_found) == 0
  97. assert all(loop.run_until_complete(protocol.call_store(
  98. f'{LOCALHOST}:{peer_port}', [key], [hivemind.MSGPackSerializer.dumps(value)], expiration)
  99. )), "peer rejected store"
  100. recv_value_bytes, recv_expiration, nodes_found = loop.run_until_complete(
  101. protocol.call_find(f'{LOCALHOST}:{peer_port}', [key]))[key]
  102. recv_value = hivemind.MSGPackSerializer.loads(recv_value_bytes)
  103. assert len(nodes_found) == 0
  104. assert recv_value == value and recv_expiration == expiration, "call_find_value expected " \
  105. f"{value} (expires by {expiration}) but got {recv_value} (expires by {recv_expiration})"
  106. assert loop.run_until_complete(protocol.call_ping(f'{LOCALHOST}:{peer_port}')) == peer_id
  107. assert loop.run_until_complete(protocol.call_ping(f'{LOCALHOST}:{hivemind.find_open_port()}')) is None
  108. test_success.set()
  109. tester = mp.Process(target=_tester, daemon=True)
  110. tester.start()
  111. tester.join()
  112. assert test_success.is_set()
  113. peer_proc.terminate()
  114. def run_node(node_id, peers, status_pipe: mp.Pipe):
  115. if asyncio.get_event_loop().is_running():
  116. asyncio.get_event_loop().stop() # if we're in jupyter, get rid of its built-in event loop
  117. asyncio.set_event_loop(asyncio.new_event_loop())
  118. loop = asyncio.get_event_loop()
  119. node = loop.run_until_complete(DHTNode.create(node_id, initial_peers=peers))
  120. status_pipe.send(node.port)
  121. while True:
  122. loop.run_forever()
  123. def test_dht_node():
  124. # create dht with 50 nodes + your 51-st node
  125. dht: Dict[Endpoint, DHTID] = {}
  126. processes: List[mp.Process] = []
  127. for i in range(50):
  128. node_id = DHTID.generate()
  129. peers = random.sample(dht.keys(), min(len(dht), 5))
  130. pipe_recv, pipe_send = mp.Pipe(duplex=False)
  131. proc = mp.Process(target=run_node, args=(node_id, peers, pipe_send), daemon=True)
  132. proc.start()
  133. port = pipe_recv.recv()
  134. processes.append(proc)
  135. dht[f"{LOCALHOST}:{port}"] = node_id
  136. test_success = mp.Event()
  137. def _tester():
  138. # note: we run everything in a separate process to re-initialize all global states from scratch
  139. # this helps us avoid undesirable side-effects when running multiple tests in sequence
  140. loop = asyncio.get_event_loop()
  141. me = loop.run_until_complete(DHTNode.create(initial_peers=random.sample(dht.keys(), 5), parallel_rpc=10))
  142. # test 1: find self
  143. nearest = loop.run_until_complete(me.find_nearest_nodes([me.node_id], k_nearest=1))[me.node_id]
  144. assert len(nearest) == 1 and nearest[me.node_id] == f"{LOCALHOST}:{me.port}"
  145. # test 2: find others
  146. for i in range(10):
  147. ref_endpoint, query_id = random.choice(list(dht.items()))
  148. nearest = loop.run_until_complete(me.find_nearest_nodes([query_id], k_nearest=1))[query_id]
  149. assert len(nearest) == 1 and next(iter(nearest.items())) == (query_id, ref_endpoint)
  150. # test 3: find neighbors to random nodes
  151. accuracy_numerator = accuracy_denominator = 0 # top-1 nearest neighbor accuracy
  152. jaccard_numerator = jaccard_denominator = 0 # jaccard similarity aka intersection over union
  153. all_node_ids = list(dht.values())
  154. for i in range(100):
  155. query_id = DHTID.generate()
  156. k_nearest = random.randint(1, 20)
  157. exclude_self = random.random() > 0.5
  158. nearest = loop.run_until_complete(
  159. me.find_nearest_nodes([query_id], k_nearest=k_nearest, exclude_self=exclude_self))[query_id]
  160. nearest_nodes = list(nearest) # keys from ordered dict
  161. assert len(nearest_nodes) == k_nearest, "beam search must return exactly k_nearest results"
  162. assert me.node_id not in nearest_nodes or not exclude_self, "if exclude, results shouldn't contain self"
  163. assert np.all(np.diff(query_id.xor_distance(nearest_nodes)) >= 0), "results must be sorted by distance"
  164. ref_nearest = heapq.nsmallest(k_nearest + 1, all_node_ids, key=query_id.xor_distance)
  165. if exclude_self and me.node_id in ref_nearest:
  166. ref_nearest.remove(me.node_id)
  167. if len(ref_nearest) > k_nearest:
  168. ref_nearest.pop()
  169. accuracy_numerator += nearest_nodes[0] == ref_nearest[0]
  170. accuracy_denominator += 1
  171. jaccard_numerator += len(set.intersection(set(nearest_nodes), set(ref_nearest)))
  172. jaccard_denominator += k_nearest
  173. accuracy = accuracy_numerator / accuracy_denominator
  174. print("Top-1 accuracy:", accuracy) # should be 98-100%
  175. jaccard_index = jaccard_numerator / jaccard_denominator
  176. print("Jaccard index (intersection over union):", jaccard_index) # should be 95-100%
  177. assert accuracy >= 0.9, f"Top-1 accuracy only {accuracy} ({accuracy_numerator} / {accuracy_denominator})"
  178. assert jaccard_index >= 0.9, f"Jaccard index only {accuracy} ({accuracy_numerator} / {accuracy_denominator})"
  179. # test 4: find all nodes
  180. dummy = DHTID.generate()
  181. nearest = loop.run_until_complete(me.find_nearest_nodes([dummy], k_nearest=len(dht) + 100))[dummy]
  182. assert len(nearest) == len(dht) + 1
  183. assert len(set.difference(set(nearest.keys()), set(all_node_ids) | {me.node_id})) == 0
  184. # test 5: node without peers
  185. other_node = loop.run_until_complete(DHTNode.create())
  186. nearest = loop.run_until_complete(other_node.find_nearest_nodes([dummy]))[dummy]
  187. assert len(nearest) == 1 and nearest[other_node.node_id] == f"{LOCALHOST}:{other_node.port}"
  188. nearest = loop.run_until_complete(other_node.find_nearest_nodes([dummy], exclude_self=True))[dummy]
  189. assert len(nearest) == 0
  190. # test 6 store and get value
  191. true_time = get_dht_time() + 1200
  192. assert loop.run_until_complete(me.store("mykey", ["Value", 10], true_time))
  193. for node in [me, other_node]:
  194. val, expiration_time = loop.run_until_complete(me.get("mykey"))
  195. assert expiration_time == true_time, "Wrong time"
  196. assert val == ["Value", 10], "Wrong value"
  197. # test 7: bulk store and bulk get
  198. keys = 'foo', 'bar', 'baz', 'zzz'
  199. values = 3, 2, 'batman', [1, 2, 3]
  200. store_ok = loop.run_until_complete(me.store_many(keys, values, expiration=get_dht_time() + 999))
  201. assert all(store_ok.values()), "failed to store one or more keys"
  202. response = loop.run_until_complete(me.get_many(keys[::-1]))
  203. for key, value in zip(keys, values):
  204. assert key in response and response[key][0] == value
  205. test_success.set()
  206. tester = mp.Process(target=_tester, daemon=True)
  207. tester.start()
  208. tester.join()
  209. assert test_success.is_set()
  210. for proc in processes:
  211. proc.terminate()
  212. def test_hivemind_dht():
  213. peers = [hivemind.DHT(start=True)]
  214. for i in range(10):
  215. neighbors_i = [f'{LOCALHOST}:{node.port}' for node in random.sample(peers, min(3, len(peers)))]
  216. peers.append(hivemind.DHT(*neighbors_i, start=True))
  217. you: hivemind.dht.DHT = random.choice(peers)
  218. theguyshetoldyounottoworryabout: hivemind.dht.DHT = random.choice(peers)
  219. expert_uids = [str(uuid.uuid4()) for _ in range(110)]
  220. batch_size = 10
  221. for batch_start in range(0, len(expert_uids), batch_size):
  222. you.declare_experts(expert_uids[batch_start: batch_start + batch_size], 'localhost', 1234)
  223. found = theguyshetoldyounottoworryabout.get_experts(random.sample(expert_uids, 5) + ['foo', 'bar'])
  224. assert all(res is not None for res in found[:-2]), "Could not find some existing experts"
  225. assert all(res is None for res in found[-2:]), "Found non-existing experts"
  226. that_guys_expert, that_guys_port = str(uuid.uuid4()), random.randint(1000, 9999)
  227. theguyshetoldyounottoworryabout.declare_experts([that_guys_expert], 'that_host', that_guys_port)
  228. you_notfound, you_found = you.get_experts(['foobar', that_guys_expert])
  229. assert isinstance(you_found, hivemind.RemoteExpert)
  230. assert you_found.host == 'that_host', you_found.port == that_guys_port
  231. # test first_k_active
  232. assert theguyshetoldyounottoworryabout.first_k_active(expert_uids, k=10) == expert_uids[:10]
  233. some_permuted_experts = random.sample(expert_uids, k=32)
  234. assert theguyshetoldyounottoworryabout.first_k_active(some_permuted_experts, k=32) == some_permuted_experts
  235. assert theguyshetoldyounottoworryabout.first_k_active(some_permuted_experts, k=1) == some_permuted_experts[:1]
  236. fake_and_real_experts = list(chain(*zip(
  237. [str(uuid.uuid4()) for _ in some_permuted_experts], some_permuted_experts)))
  238. assert theguyshetoldyounottoworryabout.first_k_active(fake_and_real_experts, k=9) == some_permuted_experts[:9]
  239. for peer in peers:
  240. peer.shutdown()
  241. def test_store():
  242. d = LocalStorage()
  243. d.store(DHTID.generate("key"), b"val", get_dht_time() + 0.5)
  244. assert d.get(DHTID.generate("key"))[0] == b"val", "Wrong value"
  245. print("Test store passed")
  246. def test_get_expired():
  247. d = LocalStorage()
  248. d.store(DHTID.generate("key"), b"val", get_dht_time() + 0.1)
  249. time.sleep(0.5)
  250. assert d.get(DHTID.generate("key")) == (None, None), "Expired value must be deleted"
  251. print("Test get expired passed")
  252. def test_get_empty():
  253. d = LocalStorage()
  254. assert d.get(DHTID.generate(source="key")) == (None, None), "LocalStorage returned non-existent value"
  255. print("Test get expired passed")
  256. def test_change_expiration_time():
  257. d = LocalStorage()
  258. d.store(DHTID.generate("key"), b"val1", get_dht_time() + 1)
  259. assert d.get(DHTID.generate("key"))[0] == b"val1", "Wrong value"
  260. d.store(DHTID.generate("key"), b"val2", get_dht_time() + 200)
  261. time.sleep(1)
  262. assert d.get(DHTID.generate("key"))[0] == b"val2", "Value must be changed, but still kept in table"
  263. print("Test change expiration time passed")
  264. def test_maxsize_cache():
  265. d = LocalStorage(maxsize=1)
  266. d.store(DHTID.generate("key1"), b"val1", get_dht_time() + 1)
  267. d.store(DHTID.generate("key2"), b"val2", get_dht_time() + 200)
  268. assert d.get(DHTID.generate("key2"))[0] == b"val2", "Value with bigger exp. time must be kept"
  269. assert d.get(DHTID.generate("key1"))[0] is None, "Value with less exp time, must be deleted"