test_routing.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import heapq
  2. import operator
  3. import random
  4. from itertools import chain, zip_longest
  5. from hivemind import LOCALHOST
  6. from hivemind.dht.routing import DHTID, RoutingTable
  7. def test_ids_basic():
  8. # basic functionality tests
  9. for i in range(100):
  10. id1, id2 = DHTID.generate(), DHTID.generate()
  11. assert DHTID.MIN <= id1 < DHTID.MAX and DHTID.MIN <= id2 <= DHTID.MAX
  12. assert DHTID.xor_distance(id1, id1) == DHTID.xor_distance(id2, id2) == 0
  13. assert DHTID.xor_distance(id1, id2) > 0 or (id1 == id2)
  14. assert DHTID.from_bytes(bytes(id1)) == id1 and DHTID.from_bytes(id2.to_bytes()) == id2
  15. def test_ids_depth():
  16. for i in range(100):
  17. ids = [random.randint(0, 4096) for i in range(random.randint(1, 256))]
  18. ours = DHTID.longest_common_prefix_length(*map(DHTID, ids))
  19. ids_bitstr = ["".join(bin(bite)[2:].rjust(8, "0") for bite in uid.to_bytes(20, "big")) for uid in ids]
  20. reference = len(shared_prefix(*ids_bitstr))
  21. assert reference == ours, f"ours {ours} != reference {reference}, ids: {ids}"
  22. def test_routing_table_basic():
  23. node_id = DHTID.generate()
  24. routing_table = RoutingTable(node_id, bucket_size=20, depth_modulo=5)
  25. added_nodes = []
  26. for phony_neighbor_port in random.sample(range(10000), 100):
  27. phony_id = DHTID.generate()
  28. routing_table.add_or_update_node(phony_id, f"{LOCALHOST}:{phony_neighbor_port}")
  29. assert phony_id in routing_table
  30. assert f"{LOCALHOST}:{phony_neighbor_port}" in routing_table
  31. assert routing_table[phony_id] == f"{LOCALHOST}:{phony_neighbor_port}"
  32. assert routing_table[f"{LOCALHOST}:{phony_neighbor_port}"] == phony_id
  33. added_nodes.append(phony_id)
  34. assert routing_table.buckets[0].lower == DHTID.MIN and routing_table.buckets[-1].upper == DHTID.MAX
  35. for bucket in routing_table.buckets:
  36. assert len(bucket.replacement_nodes) == 0, "There should be no replacement nodes in a table with 100 entries"
  37. assert 3 <= len(routing_table.buckets) <= 10, len(routing_table.buckets)
  38. random_node = random.choice(added_nodes)
  39. assert routing_table.get(node_id=random_node) == routing_table[random_node]
  40. dummy_node = DHTID.generate()
  41. assert (dummy_node not in routing_table) == (routing_table.get(node_id=dummy_node) is None)
  42. for node in added_nodes:
  43. found_bucket_index = routing_table.get_bucket_index(node)
  44. for bucket_index, bucket in enumerate(routing_table.buckets):
  45. if bucket.lower <= node < bucket.upper:
  46. break
  47. else:
  48. raise ValueError("Naive search could not find bucket. Universe has gone crazy.")
  49. assert bucket_index == found_bucket_index
  50. def test_routing_table_parameters():
  51. for (bucket_size, modulo, min_nbuckets, max_nbuckets) in [
  52. (20, 5, 45, 65),
  53. (50, 5, 35, 45),
  54. (20, 10, 650, 800),
  55. (20, 1, 7, 15),
  56. ]:
  57. node_id = DHTID.generate()
  58. routing_table = RoutingTable(node_id, bucket_size=bucket_size, depth_modulo=modulo)
  59. for phony_neighbor_port in random.sample(range(1_000_000), 10_000):
  60. routing_table.add_or_update_node(DHTID.generate(), f"{LOCALHOST}:{phony_neighbor_port}")
  61. for bucket in routing_table.buckets:
  62. assert len(bucket.replacement_nodes) == 0 or len(bucket.nodes_to_peer_id) <= bucket.size
  63. assert (
  64. min_nbuckets <= len(routing_table.buckets) <= max_nbuckets
  65. ), f"Unexpected number of buckets: {min_nbuckets} <= {len(routing_table.buckets)} <= {max_nbuckets}"
  66. def test_routing_table_search():
  67. for table_size, lower_active, upper_active in [(10, 10, 10), (10_000, 800, 1100)]:
  68. node_id = DHTID.generate()
  69. routing_table = RoutingTable(node_id, bucket_size=20, depth_modulo=5)
  70. num_added = 0
  71. total_nodes = 0
  72. for phony_neighbor_port in random.sample(range(1_000_000), table_size):
  73. routing_table.add_or_update_node(DHTID.generate(), f"{LOCALHOST}:{phony_neighbor_port}")
  74. new_total = sum(len(bucket.nodes_to_peer_id) for bucket in routing_table.buckets)
  75. num_added += new_total > total_nodes
  76. total_nodes = new_total
  77. num_replacements = sum(len(bucket.replacement_nodes) for bucket in routing_table.buckets)
  78. all_active_neighbors = list(chain(*(bucket.nodes_to_peer_id.keys() for bucket in routing_table.buckets)))
  79. assert lower_active <= len(all_active_neighbors) <= upper_active
  80. assert len(all_active_neighbors) == num_added
  81. assert num_added + num_replacements == table_size
  82. # random queries
  83. for i in range(1000):
  84. k = random.randint(1, 100)
  85. query_id = DHTID.generate()
  86. exclude = query_id if random.random() < 0.5 else None
  87. our_knn, our_peer_ids = zip(*routing_table.get_nearest_neighbors(query_id, k=k, exclude=exclude))
  88. reference_knn = heapq.nsmallest(k, all_active_neighbors, key=query_id.xor_distance)
  89. assert all(our == ref for our, ref in zip_longest(our_knn, reference_knn))
  90. assert all(our_peer_id == routing_table[our_node] for our_node, our_peer_id in zip(our_knn, our_peer_ids))
  91. # queries from table
  92. for i in range(1000):
  93. k = random.randint(1, 100)
  94. query_id = random.choice(all_active_neighbors)
  95. our_knn, our_peer_ids = zip(*routing_table.get_nearest_neighbors(query_id, k=k, exclude=query_id))
  96. reference_knn = heapq.nsmallest(k + 1, all_active_neighbors, key=query_id.xor_distance)
  97. if query_id in reference_knn:
  98. reference_knn.remove(query_id)
  99. assert len(our_knn) == len(reference_knn)
  100. assert all(
  101. query_id.xor_distance(our) == query_id.xor_distance(ref)
  102. for our, ref in zip_longest(our_knn, reference_knn)
  103. )
  104. assert routing_table.get_nearest_neighbors(query_id, k=k, exclude=None)[0][0] == query_id
  105. def shared_prefix(*strings: str):
  106. for i in range(min(map(len, strings))):
  107. if len(set(map(operator.itemgetter(i), strings))) != 1:
  108. return strings[0][:i]
  109. return min(strings, key=len)