KatInterview

Traverse a Concurrent Dependency Graph with Rate Control and Retries

Trees & GraphsModel answer
MediumModel answerTrees & Graphstrees-graphsdesign-dsstacks-queues

Last 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 in roots must 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) raises TransientError, retry up to max_retries additional times (total attempts $\le \text{max_retries} + 1$). If all retries fail, place the package in res.failed with the message "gave up after N attempts" where $N$ is the total number of attempts.
  • If fetch_fn(name) raises NotFoundError, do not retry. Record it in res.failed with "not found".
  • If max_depth is specified, packages at depth == max_depth should 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:

  1. At most workers tasks may run concurrent fetch_fn calls at any given moment.
  2. 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.
  3. Locks & Latency: Do not hold synchronization locks while waiting on network execution (fetch_fn).
  4. 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.
  5. 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.