test_dht.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 run_node(node_id, peers, status_pipe: mp.Pipe):
  82. if asyncio.get_event_loop().is_running():
  83. asyncio.get_event_loop().stop() # if we're in jupyter, get rid of its built-in event loop
  84. asyncio.set_event_loop(asyncio.new_event_loop())
  85. loop = asyncio.get_event_loop()
  86. node = loop.run_until_complete(DHTNode.create(node_id, initial_peers=peers))
  87. status_pipe.send(node.port)
  88. while True:
  89. loop.run_forever()
  90. def test_dht():
  91. # create dht with 50 nodes + your 51-st node
  92. dht: Dict[Endpoint, DHTID] = {}
  93. processes: List[mp.Process] = []
  94. for i in range(50):
  95. node_id = DHTID.generate()
  96. peers = random.sample(dht.keys(), min(len(dht), 5))
  97. pipe_recv, pipe_send = mp.Pipe(duplex=False)
  98. proc = mp.Process(target=run_node, args=(node_id, peers, pipe_send), daemon=True)
  99. proc.start()
  100. port = pipe_recv.recv()
  101. processes.append(proc)
  102. dht[f"{LOCALHOST}:{port}"] = node_id
  103. test_success = mp.Event()
  104. def _tester():
  105. # note: we run everything in a separate process to re-initialize all global states from scratch
  106. # this helps us avoid undesirable side-effects when running multiple tests in sequence
  107. loop = asyncio.get_event_loop()
  108. me = loop.run_until_complete(DHTNode.create(initial_peers=random.sample(dht.keys(), 5)))
  109. # test 1: find self
  110. nearest = loop.run_until_complete(me.find_nearest_nodes(key_id=me.node_id, k_nearest=1))
  111. assert len(nearest) == 1 and nearest[me.node_id] == (LOCALHOST, me.port)
  112. # test 2: find others
  113. for i in range(10):
  114. ref_endpoint, query_id = random.choice(list(dht.items()))
  115. nearest = loop.run_until_complete(me.find_nearest_nodes(key_id=query_id, k_nearest=1))
  116. assert len(nearest) == 1 and next(iter(nearest.items())) == (query_id, ref_endpoint)
  117. # test 3: find neighbors to random nodes
  118. accuracy_numerator = accuracy_denominator = 0 # top-1 nearest neighbor accuracy
  119. jaccard_numerator = jaccard_denominator = 0 # jaccard similarity aka intersection over union
  120. all_node_ids = list(dht.values())
  121. for i in range(100):
  122. query_id = DHTID.generate()
  123. k_nearest = random.randint(1, 20)
  124. exclude_self = random.random() > 0.5
  125. nearest = loop.run_until_complete(
  126. me.find_nearest_nodes(key_id=query_id, k_nearest=k_nearest, exclude_self=exclude_self))
  127. nearest_nodes = list(nearest) # keys from ordered dict
  128. assert len(nearest_nodes) == k_nearest, "beam search must return exactly k_nearest results"
  129. assert me.node_id not in nearest_nodes or not exclude_self, "if exclude, results should not contain own node id"
  130. assert np.all(np.diff(query_id.xor_distance(nearest_nodes)) >= 0), "results must be sorted by distance"
  131. ref_nearest = heapq.nsmallest(k_nearest + 1, all_node_ids, key=query_id.xor_distance)
  132. if exclude_self and me.node_id in ref_nearest:
  133. ref_nearest.remove(me.node_id)
  134. if len(ref_nearest) > k_nearest:
  135. ref_nearest.pop()
  136. accuracy_numerator += nearest_nodes[0] == ref_nearest[0]
  137. accuracy_denominator += 1
  138. jaccard_numerator += len(set.intersection(set(nearest_nodes), set(ref_nearest)))
  139. jaccard_denominator += k_nearest
  140. accuracy = accuracy_numerator / accuracy_denominator
  141. print("Top-1 accuracy:", accuracy) # should be 98-100%
  142. jaccard_index = jaccard_numerator / jaccard_denominator
  143. print("Jaccard index (intersection over union):", jaccard_index) # should be 95-100%
  144. assert accuracy >= 0.9, f"Top-1 accuracy only {accuracy} ({accuracy_numerator} / {accuracy_denominator})"
  145. assert jaccard_index >= 0.9, f"Jaccard index only {accuracy} ({accuracy_numerator} / {accuracy_denominator})"
  146. # test 4: find all nodes
  147. nearest = loop.run_until_complete(me.find_nearest_nodes(key_id=DHTID.generate(), k_nearest=len(dht) + 100))
  148. assert len(nearest) == len(dht) + 1
  149. assert len(set.difference(set(nearest.keys()), set(all_node_ids) | {me.node_id})) == 0
  150. # test 5: node without peers
  151. other_node = loop.run_until_complete(DHTNode.create())
  152. nearest = loop.run_until_complete(other_node.find_nearest_nodes(DHTID.generate()))
  153. assert len(nearest) == 1 and nearest[other_node.node_id] == (LOCALHOST, other_node.port)
  154. nearest = loop.run_until_complete(other_node.find_nearest_nodes(DHTID.generate(), exclude_self=True))
  155. assert len(nearest) == 0
  156. # test 6 store and get value
  157. true_time = get_dht_time() + 1200
  158. assert loop.run_until_complete(me.store("mykey", ["Value", 10], true_time))
  159. for node in [me, other_node]:
  160. val, expiration_time = loop.run_until_complete(me.get("mykey"))
  161. assert expiration_time == true_time, "Wrong time"
  162. assert val == ["Value", 10], "Wrong value"
  163. test_success.set()
  164. tester = mp.Process(target=_tester, daemon=True)
  165. tester.start()
  166. tester.join()
  167. assert test_success.is_set()
  168. for proc in processes:
  169. proc.terminate()
  170. def test_hivemind_dht():
  171. peers = [hivemind.DHT(start=True)]
  172. for i in range(10):
  173. neighbors_i = [f'{LOCALHOST}:{node.port}' for node in random.sample(peers, min(3, len(peers)))]
  174. peers.append(hivemind.DHT(*neighbors_i, start=True))
  175. you: hivemind.dht.DHT = random.choice(peers)
  176. theguyshetoldyounottoworryabout: hivemind.dht.DHT = random.choice(peers)
  177. expert_uids = [str(uuid.uuid4()) for _ in range(110)]
  178. batch_size = 10
  179. for batch_start in range(0, len(expert_uids), batch_size):
  180. you.declare_experts(expert_uids[batch_start: batch_start + batch_size], 'localhost', 1234)
  181. found = theguyshetoldyounottoworryabout.get_experts(random.sample(expert_uids, 5) + ['foo', 'bar'])
  182. assert all(res is not None for res in found[:-2]), "Could not find some existing experts"
  183. assert all(res is None for res in found[-2:]), "Found non-existing experts"
  184. that_guys_expert, that_guys_port = str(uuid.uuid4()), random.randint(1000, 9999)
  185. theguyshetoldyounottoworryabout.declare_experts([that_guys_expert], 'that_host', that_guys_port)
  186. you_notfound, you_found = you.get_experts(['foobar', that_guys_expert])
  187. assert isinstance(you_found, hivemind.RemoteExpert)
  188. assert you_found.host == 'that_host', you_found.port == that_guys_port
  189. # test first_k_active
  190. assert theguyshetoldyounottoworryabout.first_k_active(expert_uids, k=10) == expert_uids[:10]
  191. some_permuted_experts = random.sample(expert_uids, k=32)
  192. assert theguyshetoldyounottoworryabout.first_k_active(some_permuted_experts, k=32) == some_permuted_experts
  193. assert theguyshetoldyounottoworryabout.first_k_active(some_permuted_experts, k=1) == some_permuted_experts[:1]
  194. fake_and_real_experts = list(chain(*zip(
  195. [str(uuid.uuid4()) for _ in some_permuted_experts], some_permuted_experts)))
  196. assert theguyshetoldyounottoworryabout.first_k_active(fake_and_real_experts, k=9) == some_permuted_experts[:9]
  197. for peer in peers:
  198. peer.shutdown()
  199. def test_store():
  200. d = LocalStorage()
  201. d.store(DHTID.generate("key"), b"val", get_dht_time() + 0.5)
  202. assert d.get(DHTID.generate("key"))[0] == b"val", "Wrong value"
  203. print("Test store passed")
  204. def test_get_expired():
  205. d = LocalStorage()
  206. d.store(DHTID.generate("key"), b"val", get_dht_time() + 0.1)
  207. time.sleep(0.5)
  208. assert d.get(DHTID.generate("key")) == (None, None), "Expired value must be deleted"
  209. print("Test get expired passed")
  210. def test_get_empty():
  211. d = LocalStorage()
  212. assert d.get(DHTID.generate(source="key")) == (None, None), "LocalStorage returned non-existent value"
  213. print("Test get expired passed")
  214. def test_change_expiration_time():
  215. d = LocalStorage()
  216. d.store(DHTID.generate("key"), b"val1", get_dht_time() + 1)
  217. assert d.get(DHTID.generate("key"))[0] == b"val1", "Wrong value"
  218. d.store(DHTID.generate("key"), b"val2", get_dht_time() + 200)
  219. time.sleep(1)
  220. assert d.get(DHTID.generate("key"))[0] == b"val2", "Value must be changed, but still kept in table"
  221. print("Test change expiration time passed")
  222. def test_maxsize_cache():
  223. d = LocalStorage(maxsize=1)
  224. d.store(DHTID.generate("key1"), b"val1", get_dht_time() + 1)
  225. d.store(DHTID.generate("key2"), b"val2", get_dht_time() + 200)
  226. assert d.get(DHTID.generate("key2"))[0] == b"val2", "Value with bigger exp. time must be kept"
  227. assert d.get(DHTID.generate("key1"))[0] is None, "Value with less exp time, must be deleted"