Designing async bidirectional BFS with concurrency limits
The plan is to implement a Python async bidirectional BFS searching Wikipedia links forward (outgoing) and backward (backlinks), using a concurrency-limited aiohttp client and proper continuation handling to find the shortest path from source to target efficiently without overloading the API.
Below is a self–contained Python implementation of a “Six Degrees of Wikipedia” search. It uses a bidirectional breadth–first search (BFS) over the Wikipedia link graph and limits concurrent HTTP requests to stay within reasonable API usage and avoid getting throttled or banned.
import asyncio
from typing import Dict, Iterable, List, Optional, Set, Tuple
import aiohttp
API_URL = "https://en.wikipedia.org/w/api.php"
async def fetch_links(
session: aiohttp.ClientSession,
title: str,
sem: asyncio.Semaphore,
direction: str = "out",
) -> Set[str]:
"""
Fetch all links for a given page title.
:param direction: "out" for outgoing links (prop=links),
"in" for backlinks (list=backlinks).
:return: Set of linked page titles (namespace 0).
"""
links: Set[str] = set()
cont_param = "plcontinue" if direction == "out" else "blcontinue"
params = {
"format": "json",
"action": "query",
"redirects": 1,
"maxlag": 2,
"formatversion": "2",
}
if direction == "out":
params.update(
{
"prop": "links",
"titles": title,
"plnamespace": 0, # main/article namespace
"pllimit": "max",
}
)
else:
params.update(
{
"list": "backlinks",
"bltitle": title,
"blnamespace": 0,
"bllimit": "max",
}
)
cont: Dict[str, str] = {}
while True:
q = params | cont
async with sem:
async with session.get(API_URL, params=q) as resp:
resp.raise_for_status()
data = await resp.json()
if direction == "out":
for page in data.get("query", {}).get("pages", []):
for link in page.get("links", []):
links.add(link["title"])
else:
for bl in data.get("query", {}).get("backlinks", []):
links.add(bl["title"])
if "continue" in data and cont_param in data["continue"]:
cont = {cont_param: data["continue"][cont_param]}
else:
break
return links
def reconstruct_path(
meeting: str,
parent_fwd: Dict[str, Optional[str]],
parent_bwd: Dict[str, Optional[str]],
) -> List[str]:
"""Reconstruct full path from source to target given the meeting node."""
path_forward: List[str] = []
node = meeting
while node is not None:
path_forward.append(node)
node = parent_fwd[node]
path_forward.reverse()
path_backward: List[str] = []
node = parent_bwd[meeting]
# parent_bwd maps a node to the next node toward target
while node is not None:
path_backward.append(node)
node = parent_bwd[node]
return path_forward + path_backward
async def bidirectional_bfs(
source: str,
target: str,
max_concurrency: int = 5,
max_depth: int = 6,
) -> Optional[List[str]]:
"""
Perform bidirectional BFS from source to target on Wikipedia links.
:param max_concurrency: limit for simultaneous HTTP requests.
:param max_depth: maximum depth to explore in each direction.
:return: list of page titles forming the shortest path, or None.
"""
if source == target:
return [source]
sem = asyncio.Semaphore(max_concurrency)
headers = {
# Be a good citizen: identify your app/email per API etiquette.
"User-Agent": "SixDegreesSearch/1.0 (example@example.com)",
}
async with aiohttp.ClientSession(headers=headers) as session:
fwd_frontier: Set[str] = {source}
bwd_frontier: Set[str] = {target}
visited_fwd: Set[str] = {source}
visited_bwd: Set[str] = {target}
parent_fwd: Dict[str, Optional[str]] = {source: None}
parent_bwd: Dict[str, Optional[str]] = {target: None}
depth = 0
while fwd_frontier and bwd_frontier and depth < max_depth * 2:
# Expand the smaller frontier to keep the search balanced
if len(fwd_frontier) <= len(bwd_frontier):
direction = "out"
frontier = fwd_frontier
else:
direction = "in"
frontier = bwd_frontier
tasks = [fetch_links(session, title, sem, direction) for title in frontier]
neighbors_list: List[Set[str]] = await asyncio.gather(*tasks)
next_frontier: Set[str] = set()
for current, neighbors in zip(frontier, neighbors_list):
for neighbor in neighbors:
if direction == "out":
if neighbor in visited_fwd:
continue
visited_fwd.add(neighbor)
parent_fwd[neighbor] = current
if neighbor in visited_bwd:
return reconstruct_path(neighbor, parent_fwd, parent_bwd)
next_frontier.add(neighbor)
else:
if neighbor in visited_bwd:
continue
visited_bwd.add(neighbor)
parent_bwd[neighbor] = current # current links to neighbor
if neighbor in visited_fwd:
return reconstruct_path(neighbor, parent_fwd, parent_bwd)
next_frontier.add(neighbor)
if direction == "out":
fwd_frontier = next_frontier
else:
bwd_frontier = next_frontier
depth += 1
return None
if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
print("Usage: python six_degrees.py 'Source Page' 'Target Page'")
sys.exit(1)
src, dst = sys.argv[1], sys.argv[2]
path = asyncio.run(bidirectional_bfs(src, dst, max_concurrency=5, max_depth=10))
if path:
print(" -> ".join(path))
else:
print(f"No path found from '{src}' to '{dst}' within depth limit.")
How it works
- The MediaWiki API is queried for outgoing links (
prop=links) when expanding from the source side and for incoming links (list=backlinks) when expanding from the target side.
- A bidirectional BFS keeps track of visited nodes and parent pointers in each direction. The search always expands the smaller frontier to minimize the number of requests.
- Once a node appears in both visited sets, a meeting point has been found and the full path is reconstructed by combining the forward and backward parent chains.
aiohttp and an asyncio.Semaphore are used to limit concurrent HTTP requests (max_concurrency), which helps avoid tripping API throttling or IP bans. A descriptive User-Agent header is also set per Wikipedia API etiquette.
You can adjust max_concurrency or max_depth as needed.