Traverse a Concurrent Dependency Graph with Rate Control and Retries
Trees & GraphsModel answerLast updated
Discover the full transitive dependency graph of a package using sequential BFS and concurrent worker pools with retry handling and exact termination logic.
When installing a package in a modern software ecosystem, a package manager must explore the remote package registry to construct the full transitive dependency tree. Because remote registry requests involve latency and intermittent network failures, fetching packages sequentially can be excessively slow.
You are provided a remote API function with the signature:
def fetch(name: str) -> list[str]:
"""Returns a list of direct dependency package names for a given package.
Raises:
TransientError: On network timeouts or temporary 5xx errors (retryable).
NotFoundError: When the package does not exist in the registry (non-retryable).
"""
You must populate and return a data object representing the final graph state:
from dataclasses import dataclass, field
@dataclass
class Resolution:
deps: dict[str, list[str]] = field(default_factory=dict) # package_name -> direct dependencies list
failed: dict[str, str] = field(default_factory=dict) # package_name -> error message description
depth: dict[str, int] = field(default_factory=dict) # package_name -> distance/depth from root
Part 1: Sequential Graph Resolution
Implement resolve_sequential(roots: list[str], fetch_fn, max_retries: int = 2, max_depth: int | None = None) -> Resolution.
Rules:
- Roots start at
depth = 0. Duplicate entries inrootsmust be deduplicated while preserving discovery depth as 0. - Every package should be fetched at most once successfully.
- Dependency graphs can contain cycles (e.g.,
A -> B -> A) or shared sub-trees. Do not get stuck in infinite loops. - If
fetch_fn(name)raisesTransientError, retry up tomax_retriesadditional times (total attempts $\le \text{max_retries} + 1$). If all retries fail, place the package inres.failedwith the message"gave up after N attempts"where $N$ is the total number of attempts. - If
fetch_fn(name)raisesNotFoundError, do not retry. Record it inres.failedwith"not found". - If
max_depthis specified, packages atdepth == max_depthshould be fetched, but their children must not be traversed or added to the resolution maps.
Part 2: Bounded Concurrent Graph Resolution
Implement ConcurrentResolver(fetch_fn, workers: int = 8, max_retries: int = 2, max_depth: int | None = None).resolve(roots: list[str]) -> Resolution.
Requirements:
- At most
workerstasks may run concurrentfetch_fncalls at any given moment. - Atomic Reservation: Two concurrent workers discovering the same dependency must not both issue a network request for it. Mark a package as discovered at the instant it is scheduled.
- Locks & Latency: Do not hold synchronization locks while waiting on network execution (
fetch_fn). - Termination Condition: The process must safely terminate only when no work remains in the task queue and no worker threads are actively executing a fetch request.
- No Busy-Waiting: Threads waiting for work must block efficiently using standard synchronization primitives (e.g., condition variables or thread-safe queues).
Hints
Hint 1
To prevent duplicate requests, mark a package as seen (reserve its depth entry) as soon as it is enqueued, rather than when it is popped or completed.
Hint 2
Evaluating completion requires tracking both the work queue length and the active work count under a single synchronized boundary. A queue being empty does not mean resolution is complete if an active worker is currently fetching dependencies that will produce new queue items.
Hint 3
Use `threading.Condition` to manage worker execution. A worker waiting for work must block on the condition variable and be notified whenever new work is enqueued or when active worker counts change.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Architecture
Graph traversal with remote network requests presents two key implementation challenges: state deduplication and correct concurrent termination.
1. Deduplication via Early Reservation
In a standard BFS, nodes are marked as visited as soon as they are added to the queue (reservation), rather than when popped. If we wait until a node is popped or finished fetching, multiple paths to the same node (e.g., A -> C and B -> C) will enqueue C multiple times.
We use res.depth to store reservations: if name is present in res.depth, it has already been claimed and queued.
2. Synchronized State in Concurrent Worker Pool
When executing with K worker threads, multiple workers can complete tasks and discover identical dependencies simultaneously. To guarantee that a package is fetched at most once:
- Critical Section for Discovery: The check
if dep not in res.depthand settingres.depth[dep]must happen inside a lock. - Locking Scope: Acquire the lock, pop a unit of work, increment
in_flight, release the lock, callfetch_fn, re-acquire the lock, update state/enqueue children, decrementin_flight, and notify waiting threads.
3. Complete & Non-blocking Termination Detection
A naive termination check of len(queue) == 0 is incorrect because worker threads may be actively executing network requests (in_flight > 0) that will yield more dependencies.
The global graph resolution is finished if and only if: $$\text{queue is empty} \quad \text{AND} \quad \text{in_flight} == 0$$
Using a threading.Condition, workers block on cond.wait() when queue is empty but in_flight > 0. When the last active worker finishes (in_flight == 0 and queue empty), it broadcasts a signal via cond.notify_all(), causing all parked worker threads to exit cleanly.
Python 3 Implementation
import threading
from collections import deque
from dataclasses import dataclass, field
class TransientError(Exception):
"""Network timeout or transient HTTP 5xx error."""
class NotFoundError(Exception):
"""Target package does not exist."""
@dataclass
class Resolution:
deps: dict[str, list[str]] = field(default_factory=dict)
failed: dict[str, str] = field(default_factory=dict)
depth: dict[str, int] = field(default_factory=dict)
def resolve_sequential(
roots: list[str],
fetch_fn,
max_retries: int = 2,
max_depth: int | None = None,
) -> Resolution:
res = Resolution()
queue = deque()
# Deduplicate root elements while preserving zero depth
for r in dict.fromkeys(roots):
res.depth[r] = 0
queue.append(r)
while queue:
name = queue.popleft()
fetched_deps = None
for attempt in range(1, max_retries + 2):
try:
fetched_deps = fetch_fn(name)
break
except NotFoundError:
res.failed[name] = "not found"
break
except TransientError:
if attempt == max_retries + 1:
res.failed[name] = f"gave up after {attempt} attempts"
if name in res.failed:
continue
res.deps[name] = fetched_deps
current_depth = res.depth[name]
# Stop traversal if max_depth limit is met
if max_depth is not None and current_depth >= max_depth:
continue
for child in fetched_deps:
if child not in res.depth:
res.depth[child] = current_depth + 1
queue.append(child)
return res
class ConcurrentResolver:
def __init__(
self,
fetch_fn,
workers: int = 8,
max_retries: int = 2,
max_depth: int | None = None,
):
self.fetch_fn = fetch_fn
self.workers = workers
self.max_retries = max_retries
self.max_depth = max_depth
def resolve(self, roots: list[str]) -> Resolution:
res = Resolution()
attempts = {}
queue = deque()
in_flight = 0
cond = threading.Condition()
for r in dict.fromkeys(roots):
res.depth[r] = 0
queue.append(r)
def worker():
nonlocal in_flight
while True:
with cond:
# Wait if queue is temporarily empty but other workers are processing
while not queue and in_flight > 0:
cond.wait()
# Termination state: no tasks left and no active network requests
if not queue and in_flight == 0:
cond.notify_all()
return
name = queue.popleft()
in_flight += 1
# I/O Execution (Outside Critical Section)
err_kind = None
fetched_deps = None
try:
fetched_deps = self.fetch_fn(name)
except NotFoundError:
err_kind = "not_found"
except TransientError:
err_kind = "transient"
# State Updates & Scheduling (Inside Critical Section)
with cond:
in_flight -= 1
if err_kind == "transient":
attempts[name] = attempts.get(name, 0) + 1
if attempts[name] <= self.max_retries:
queue.append(name) # Re-enqueue for retry
else:
res.failed[name] = f"gave up after {attempts[name]} attempts"
elif err_kind == "not_found":
res.failed[name] = "not found"
else:
res.deps[name] = fetched_deps
curr_d = res.depth[name]
if self.max_depth is None or curr_d < self.max_depth:
for child in fetched_deps:
if child not in res.depth: # Atomic reservation
res.depth[child] = curr_d + 1
queue.append(child)
# Notify waiting threads of new work or completed task
cond.notify_all()
threads = [threading.Thread(target=worker) for _ in range(self.workers)]
for t in threads:
t.start()
for t in threads:
t.join()
return res
Complexity & Performance Analysis
- Time Complexity:
- Sequential: $\mathcal{O}(V + E \cdot R)$ where $V$ is the number of unique reachable packages, $E$ is total dependency links, and $R = \text{max_retries} + 1$.
- Concurrent: $\mathcal{O}\left(\frac{V \cdot L}{K} + V + E\right)$ where $L$ is network latency per request and $K$ is the worker pool count (
workers).
- Space Complexity: $\mathcal{O}(V + E)$ to maintain graph metadata in
res.deps,res.depth, and thread queues. - Synchronization Overhead: Minimized by performing heavy network operations strictly outside
with cond:blocks.