Fix algorithmic bug causing exponential blowup in dependency analysis #2218
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix exponential time complexity in build target depth computation
Problem
The
targetDepthsAndDependents
function inBuildSystemManager
was taking ~24 seconds to process 636 build targets, causing significant delays during build system initialization and target change notifications.This should complete in well under a second for this number of targets.
Root Cause
The issue was an algorithmic bug in the dependency traversal logic. The function was checking the wrong variable when deciding whether to add dependencies to the work queue:
This caused dependencies to be added to the work list even when they had already been processed with adequate depth, leading to exponential time complexity as the same nodes were visited repeatedly.
Solution
Fixed the condition to check the dependency's depth instead of the current target's depth:
This ensures proper memoization and restores the intended O(V+E) linear time complexity.
Impact
Testing
The fix maintains the same algorithmic correctness while dramatically improving performance. The function still correctly computes:
But now does so efficiently without redundant work.
Files Changed:
Sources/BuildSystemIntegration/BuildSystemManager.swift
- Fixed variable name in depth checking condition