Skip to content

Avoid O(n²) scan when deduplicating reserved IPs - #2854

Open
neddp wants to merge 3 commits into
mainfrom
fix-dynamic-ip-allocation-quadratic-dedup
Open

neddp wants to merge 3 commits into
mainfrom
fix-dynamic-ip-allocation-quadratic-dedup

Conversation

@neddp

@neddp neddp commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

What

IpRepo#try_to_allocate_dynamic_ip deduplicates its set of unavailable addresses by removing any reservation already covered by a larger (smaller-prefix) block. It did this with a full pairwise scan - every entry compared against every other entry:

addresses_we_cant_allocate.reject! do |ip|
  addresses_we_cant_allocate.any? do |other_ip|
    includes = other_ip.include?(ip)
    includes && other_ip.prefix < ip.prefix
  end
end

addresses_we_cant_allocate starts from all_ip_addresses - every reserved IP in the director, across all deployments. The scan is therefore O(n²) in the total number of reserved IPs, and it runs on every dynamic IP allocation.

This change restricts the inner comparison to the only entries that can actually contain another - blocks that span more than one address (ip.count > 1), i.e. reserved CIDR ranges, of which there are very few. The /32 / /128 host reservations that dominate the table can never be containers, so excluding them from the scan produces identical dedup output while making the pass linear in the host count.

containing_blocks = addresses_we_cant_allocate.select { |ip| ip.count > 1 }
unless containing_blocks.empty?
  addresses_we_cant_allocate.reject! do |ip|
    containing_blocks.any? do |other_ip|
      includes = other_ip.include?(ip)
      includes && other_ip.prefix < ip.prefix
    end
  end
end

The identical dedup pattern appears in ManualNetworkSubnet.parse over the subnet's restricted_ips; the same transformation is applied there. It is not a hot path (that set is small and the dedup runs once per subnet-parse), but it is the same code and the same fix, so both are updated together for consistency.

Why / impact

On a busy director the quadratic scan pegs a worker CPU at 100% and stalls bosh deploy, with no cancellation checkpoint inside the loop (so the task is also uncancellable). It is paid per reservation, so it compounds across the instance IPs reserved during Preparing deployment and across each compilation VM IP reservation.

Measured cost of the dedup step alone (real IpAddrOrCidr objects):

reserved IPs (n) before (O(n²)) after
1,000 0.49 s 0.009 s
4,000 7.5 s 0.022 s
8,000 29.9 s 0.044 s
16,000 118.7 s 0.091 s

Correctness

The change is behaviour-preserving by construction: the predicate is unchanged, and the only (ip, other_ip) pairs removed from consideration are those where other_ip.prefix < ip.prefix can never hold - an other_ip at host width (count == 1) cannot be below any ip's prefix, since ip.prefix never exceeds host width. So containing_blocks captures every possible container.

Verified identical to the previous dedup (end-to-end allocated address from the real find_next_available_ip) across:

  • Edge cases (actual addresses): empty set, first-IP reserved, packed start, contiguous-then-gap, containing block with contained hosts, nested blocks (/24 ⊃ /26 ⊃ /32), mid-range reserved, sub-/32 block allocation (/30, /28, /124), fully-packed range, host just below first, many blocks + hosts, and IPv6 (host+block, nested, non-/128 allocation).
  • Big data: 1k–16k reserved IPs, identical allocation on every size.
  • Randomized sweep: 8,000 scenarios (blocks + contained hosts + scattered hosts, varied allocation prefix and range offset) → 0 divergences. A separate dedup-output equivalence run over 90,000 randomized sets (IPv4 + IPv6) also showed 0 mismatches.

The ManualNetworkSubnet.parse dedup was verified the same way - identical output to the original across 50,000 randomized IPv4 and IPv6 restricted_ips sets.

Testing

bosh-director unit specs pass, including the IP provider / repo, manual network (+ subnet), IpAddrOrCidr, network planner, and reservation suites.

Caution

This is not tested on an actual deployment.

try_to_allocate_dynamic_ip loads every reserved IP across all
deployments and, to drop addresses already covered by a larger block,
compared each entry against every other entry. That full pairwise scan
is O(n^2) in the total number of reserved IPs and runs on every dynamic
allocation, pegging a worker CPU and stalling "Preparing deployment" and
compilation-VM creation on busy directors.

Only an entry that spans more than one address (a reserved CIDR block)
can cover another entry; the /32 and /128 host reservations that make up
the bulk of the table never can. Restricting the inner scan to those
blocks produces identical dedup output while making the pass linear in
the host count.

Verified behaviour-identical to the previous dedup across edge cases,
IPv6, and randomized inputs, and on large sets (dedup at 16k reserved
IPs: ~117s -> ~0.09s).

Signed-off-by: Nayden Petrov <nayden.petrov@sap.com>
ManualNetworkSubnet.parse deduplicates restricted_ips with the same full
pairwise scan found in try_to_allocate_dynamic_ip. The set is small here
(reserved CIDR blocks plus a few host entries) so it is not a hot path,
but it is the identical O(n^2) pattern and the identical fix: only an
entry that spans more than one address can contain another, so the inner
scan is restricted to those blocks.

Behaviour-identical to the previous dedup, verified across randomized
IPv4 and IPv6 restricted-IP sets.

Signed-off-by: Nayden Petrov <nayden.petrov@sap.com>
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Dynamic IP allocation and manual subnet parsing now consider only multi-address reservations as potential containing blocks. Both paths remove reservations covered by a larger block. A new spec checks dynamic IP allocation time with 16,000 reservations.

Suggested reviewers: fmoehler, aramprice

Merge Risk: Minimal · up to bd0af

The change speeds up duplicate-reservation filtering for dynamic IP allocation while keeping the same output. No concrete defect was found. The author has noted they are still investigating whether this fully resolves the original report.

Pre-merge checks: Passed 3 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description is detailed and covers the change, rationale, correctness reasoning, and testing. It does not follow the repository template. The sections 'Please provide contextual information', 'How… Add the missing template sections: (1) link the Slack discussion and any related issues or PRs under contextual information; (2) add a bosh release notes entry written for operators, or state that none is needed; (3) state whether the chang…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title names the main change: the dedup of reserved IPs no longer uses an O(n²) scan. It matches the code change in IpRepo#try_to_allocate_dynamic_ip and ManualNetworkSubnet.parse, which only compa…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: the dedup of reserved IPs no longer uses an O(n²) scan. It matches the code change in IpRepo#try_to_allocate_dynamic_ip and ManualNetworkSubnet.parse, which only compare against multi-address reservations.

Full details: Description check

Explanation

The description is detailed and covers the change, rationale, correctness reasoning, and testing. It does not follow the repository template. The sections 'Please provide contextual information', 'How should this change be described in bosh release notes?', 'Does this PR introduce a breaking change?', 'Tag your pair, your PM, and/or team!', and 'AI Review Feedback' are missing. The 'What tests have you run' section is present but lists only unit suites and does not give exact commands. The PR objectives also say the author asked not to merge while they investigate further, which the description does not mention. The Slack discussion that motivated the change is not linked.

Resolution

Add the missing template sections: (1) link the Slack discussion and any related issues or PRs under contextual information; (2) add a bosh release notes entry written for operators, or state that none is needed; (3) state whether the change is breaking, most likely 'No'; (4) tag the pair, PM, or team; (5) state the status of AI review feedback threads. Also state the merge status, since the author asked for no merge while the investigation continues. Consider listing the exact test commands run.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: aadba0ce-7084-4f46-b640-e5f06371c768
Commits

Reviewing files that changed from the base of the PR and between 4aebba8 and bd0af23.

Files selected for processing: 2

  • src/bosh-director/lib/bosh/director/deployment_plan/ip_provider/ip_repo.rb
  • src/bosh-director/spec/unit/bosh/director/deployment_plan/ip_provider/ip_repo_spec.rb

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Nov 24, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are reported for the reserved-IP deduplication optimization.

No open issues 🎉

What changed in this PR

Optimizes reserved-IP deduplication in the director’s dynamic IP allocator and subnet parser by limiting containment checks to multi-address blocks, preserving the existing containment predicate.

Changes:

  • Excludes single-address reservations from potential containers, reducing work for host-heavy reservation sets.
  • Skips containment scans entirely when no multi-address blocks exist.
  • Applies the same optimization to restricted IPs during manual subnet parsing.
File Description
src/​bosh-director/​lib/​bosh/​director/​deployment_plan/​manual_network_subnet.rb Limits restricted-IP containment checks to multi-address blocks.
src/​bosh-director/​lib/​bosh/​director/​deployment_plan/​ip_provider/​ip_repo.rb Reduces deduplication work during dynamic IP allocation.

Review effort: Balanced

aramprice
aramprice previously approved these changes Nov 24, 2026

@aramprice aramprice left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would there be value in adding a sentinel test that checks a large CIDR to ensure we have viable performance.

Seems like we could safely expect a 16k allocation to be less than 3.seconds now.

Alphasite
Alphasite previously approved these changes Nov 25, 2026

@Alphasite Alphasite left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It took me a second to figure out why there were all these single IP exclusions...

I think it's worth the comment mentioning that the IP for each Nic is represented as an exclusion, so we can ignore those when checking ip block intersection.

@neddp

neddp commented Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Lets not merge for now. I am not convinced that this alone addresses the issue that was raised in Slack.
I will investigate it further.

Thank you for the suggestions!

  • Improved the wording in the code comment.
  • Added a performance test with 16k entries. Result from running it:
Without fix 135.24 s
With fix 0.13 s

- Explain in the comment that reserved IPs are per-NIC single-address
  exclusions (/32 or /128) alongside the occasional larger block, so only
  multi-address blocks can be containers and the scan is restricted to them.
- Add a spec that allocates a dynamic IP against 16k reserved IPs and asserts
  it completes well under 3 seconds, guarding against reintroducing the O(n^2)
  scan.

Signed-off-by: Nayden Petrov <nayden.petrov@sap.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Pending Merge | Prioritized

Development

Successfully merging this pull request may close these issues.

4 participants