From aa7c7dec54afdba0f8789cbc57b2fa5c617b33a3 Mon Sep 17 00:00:00 2001 From: Gagan Deep Date: Fri, 4 Dec 2026 19:01:10 +0530 Subject: [PATCH 1/5] [fix] Skipped allocated IPs across the subnet hierarchy #275 Matched automatic allocation to hierarchy-wide duplicate validation so parent requests skip occupied descendant addresses instead of failing. Fixes #275 --- openwisp_ipam/base/models.py | 10 ++++++++-- openwisp_ipam/tests/test_models.py | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/openwisp_ipam/base/models.py b/openwisp_ipam/base/models.py index e16398b..4908969 100644 --- a/openwisp_ipam/base/models.py +++ b/openwisp_ipam/base/models.py @@ -294,9 +294,15 @@ def get_next_available_ip(self): """Return the next assignable, unallocated IP address in this subnet. Usability is checked against this subnet and its ancestors. Existing - IP address records directly assigned to this subnet are skipped. + IP address records in this subnet, its ancestors and descendants are + skipped, matching duplicate validation when the address is saved. """ - ipaddress_set = set(self.ipaddress_set.values_list("ip_address", flat=True)) + ipaddress_set = set( + load_model("openwisp_ipam", "IpAddress") + .objects.filter(subnet_id__in=self.get_related_subnet_pks()) + .values_list("ip_address", flat=True) + .iterator() + ) containing_networks = self._get_containing_networks() subnet_hosts = self.subnet.hosts() for host in subnet_hosts: diff --git a/openwisp_ipam/tests/test_models.py b/openwisp_ipam/tests/test_models.py index 6429b99..85fe254 100644 --- a/openwisp_ipam/tests/test_models.py +++ b/openwisp_ipam/tests/test_models.py @@ -816,3 +816,17 @@ def test_get_or_create_org(self): "“new-org”", str(context_manager.exception), ) + + def test_request_ip_skips_related_subnet_allocations(self): + parent = self._create_subnet(subnet="10.0.0.0/29") + child = self._create_subnet(subnet="10.0.0.0/30", master_subnet=parent) + grandchild = self._create_subnet(subnet="10.0.0.1/32", master_subnet=child) + self._create_ipaddress(subnet=grandchild, ip_address="10.0.0.1") + + with self.subTest("parent skips descendant allocation"): + self.assertEqual(parent.get_next_available_ip(), "10.0.0.2") + self.assertEqual(parent.request_ip().ip_address, "10.0.0.2") + + with self.subTest("child exhausted by ancestor and descendant allocations"): + self.assertEqual(child.get_next_available_ip(), None) + self.assertEqual(child.request_ip(), None) From 50d857770978a8568aa21fadda48b4ff7c6f7bb2 Mon Sep 17 00:00:00 2001 From: Gagan Deep Date: Fri, 4 Dec 2026 19:08:27 +0530 Subject: [PATCH 2/5] [chores] Addressed review feedback --- openwisp_ipam/tests/test_models.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/openwisp_ipam/tests/test_models.py b/openwisp_ipam/tests/test_models.py index 85fe254..463dafe 100644 --- a/openwisp_ipam/tests/test_models.py +++ b/openwisp_ipam/tests/test_models.py @@ -828,5 +828,10 @@ def test_request_ip_skips_related_subnet_allocations(self): self.assertEqual(parent.request_ip().ip_address, "10.0.0.2") with self.subTest("child exhausted by ancestor and descendant allocations"): + parent = self._create_subnet(subnet="10.0.1.0/29") + child = self._create_subnet(subnet="10.0.1.0/30", master_subnet=parent) + grandchild = self._create_subnet(subnet="10.0.1.1/32", master_subnet=child) + self._create_ipaddress(subnet=grandchild, ip_address="10.0.1.1") + self._create_ipaddress(subnet=parent, ip_address="10.0.1.2") self.assertEqual(child.get_next_available_ip(), None) self.assertEqual(child.request_ip(), None) From 9795021bc273f69b20f254d0134bdda059e5b2b2 Mon Sep 17 00:00:00 2001 From: Gagan Deep Date: Fri, 4 Dec 2026 19:48:33 +0530 Subject: [PATCH 3/5] [chores] Addressed review feedback Bound allocation lookups to batches of candidate addresses so a child request does not load unrelated allocations from large ancestors. Equality queries preserve IPv4 and IPv6 behavior on SQLite and PostgreSQL. Added regressions for unrelated ancestor addresses and a full first batch. --- openwisp_ipam/base/models.py | 34 +++++++++++++-------- openwisp_ipam/tests/test_models.py | 47 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 12 deletions(-) diff --git a/openwisp_ipam/base/models.py b/openwisp_ipam/base/models.py index 4908969..973230c 100644 --- a/openwisp_ipam/base/models.py +++ b/openwisp_ipam/base/models.py @@ -2,6 +2,7 @@ from bisect import bisect_right from io import StringIO from ipaddress import ip_address, ip_network +from itertools import islice import openpyxl from django.core.exceptions import ValidationError @@ -297,20 +298,29 @@ def get_next_available_ip(self): IP address records in this subnet, its ancestors and descendants are skipped, matching duplicate validation when the address is saved. """ - ipaddress_set = set( - load_model("openwisp_ipam", "IpAddress") - .objects.filter(subnet_id__in=self.get_related_subnet_pks()) - .values_list("ip_address", flat=True) - .iterator() + related_ips = load_model("openwisp_ipam", "IpAddress").objects.filter( + subnet_id__in=self.get_related_subnet_pks() ) containing_networks = self._get_containing_networks() - subnet_hosts = self.subnet.hosts() - for host in subnet_hosts: - if ( - self._is_ip_usable(host, containing_networks) - and str(host) not in ipaddress_set - ): - return str(host) + subnet_hosts = ( + str(host) + for host in self.subnet.hosts() + if self._is_ip_usable(host, containing_networks) + ) + # Bound fetched allocations to candidate addresses, not entire ancestors. + # Equality works on both SQLite text fields and PostgreSQL inet fields. + while True: + candidates = list(islice(subnet_hosts, 256)) + if not candidates: + break + ipaddress_set = set( + related_ips.filter(ip_address__in=candidates) + .values_list("ip_address", flat=True) + .iterator() + ) + for host in candidates: + if host not in ipaddress_set: + return host return None def get_allocation(self, organization_filter=None): diff --git a/openwisp_ipam/tests/test_models.py b/openwisp_ipam/tests/test_models.py index 463dafe..1b8dbee 100644 --- a/openwisp_ipam/tests/test_models.py +++ b/openwisp_ipam/tests/test_models.py @@ -5,6 +5,7 @@ from unittest.mock import patch from django.core.exceptions import ValidationError +from django.db.models import QuerySet from django.test import TestCase from swapper import load_model @@ -835,3 +836,49 @@ def test_request_ip_skips_related_subnet_allocations(self): self._create_ipaddress(subnet=parent, ip_address="10.0.1.2") self.assertEqual(child.get_next_available_ip(), None) self.assertEqual(child.request_ip(), None) + + def test_child_allocation_does_not_read_unrelated_parent_ips(self): + original_iterator = QuerySet.iterator + addresses_read = [] + + def track_addresses(queryset, *args, **kwargs): + for value in original_iterator(queryset, *args, **kwargs): + if queryset.model is IpAddress: + addresses_read.append(value) + yield value + + with self.subTest("IPv4 ancestor allocations outside the child"): + parent = self._create_subnet(subnet="10.0.0.0/24") + child = self._create_subnet(subnet="10.0.0.1/32", master_subnet=parent) + self._create_ipaddress(subnet=parent, ip_address="10.0.0.2") + self._create_ipaddress(subnet=parent, ip_address="10.0.0.10") + with patch.object(QuerySet, "iterator", track_addresses): + self.assertEqual(child.get_next_available_ip(), "10.0.0.1") + self.assertEqual( + addresses_read, [], "Child allocation must not fetch unrelated IPs." + ) + + with self.subTest("IPv6 ancestor allocations outside the child"): + addresses_read.clear() + parent = self._create_subnet(subnet="2001:db8::/120") + child = self._create_subnet(subnet="2001:db8::1/128", master_subnet=parent) + self._create_ipaddress(subnet=parent, ip_address="2001:db8::2") + self._create_ipaddress(subnet=parent, ip_address="2001:db8::10") + with patch.object(QuerySet, "iterator", track_addresses): + self.assertEqual(child.get_next_available_ip(), "2001:db8::1") + self.assertEqual( + addresses_read, [], "Child allocation must not fetch unrelated IPs." + ) + + def test_request_ip_after_full_allocation_batch(self): + parent = self._create_subnet(subnet="10.0.0.0/22") + child = self._create_subnet(subnet="10.0.0.0/23", master_subnet=parent) + # Bulk insertion keeps the allocation regression independent of validation. + IpAddress.objects.bulk_create( + [ + IpAddress(subnet=parent, ip_address=str(address)) + for address in islice(child.subnet.hosts(), 256) + ] + ) + self.assertEqual(child.get_next_available_ip(), "10.0.1.1") + self.assertEqual(child.request_ip().ip_address, "10.0.1.1") From a63f0791a7798742e40bcb9e0e82445e58b16736 Mon Sep 17 00:00:00 2001 From: Gagan Deep Date: Fri, 4 Dec 2026 20:14:48 +0530 Subject: [PATCH 4/5] [chores] Addressed review feedback Added a composite subnet and IP address index so candidate batches can look up occupied addresses without rescanning each related subnet. Kept the bounded allocation strategy and documented migration requirements for custom apps inheriting the abstract model. --- docs/developer/extending.rst | 7 +++++++ openwisp_ipam/base/models.py | 2 ++ .../0006_ipaddress_allocation_index.py | 18 ++++++++++++++++++ openwisp_ipam/tests/test_models.py | 16 ++++++++++++++++ .../sample_ipam/migrations/0001_initial.py | 6 ++++++ 5 files changed, 49 insertions(+) create mode 100644 openwisp_ipam/migrations/0006_ipaddress_allocation_index.py diff --git a/docs/developer/extending.rst b/docs/developer/extending.rst index d64021b..cdacb8c 100644 --- a/docs/developer/extending.rst +++ b/docs/developer/extending.rst @@ -203,6 +203,13 @@ For more information, refer to the `"Migrations" section in the django documentation `_. +When upgrading an existing custom app, generate and apply its migrations +again to include changes inherited from the abstract models. In +particular, ``AbstractIpAddress.Meta`` defines a composite index on +``subnet`` and ``ip_address`` so allocation batches do not repeatedly scan +all addresses in related subnets. If your custom model overrides +``Meta.indexes``, include the inherited indexes as well. + 10. Create the Admin -------------------- diff --git a/openwisp_ipam/base/models.py b/openwisp_ipam/base/models.py index 973230c..f4bf3ab 100644 --- a/openwisp_ipam/base/models.py +++ b/openwisp_ipam/base/models.py @@ -540,6 +540,8 @@ class Meta: abstract = True verbose_name = _("IP address") verbose_name_plural = _("IP addresses") + # Candidate batches must not rescan every allocation in each related subnet. + indexes = [models.Index(fields=["subnet", "ip_address"])] def __str__(self): return self.ip_address diff --git a/openwisp_ipam/migrations/0006_ipaddress_allocation_index.py b/openwisp_ipam/migrations/0006_ipaddress_allocation_index.py new file mode 100644 index 0000000..e3dbcb5 --- /dev/null +++ b/openwisp_ipam/migrations/0006_ipaddress_allocation_index.py @@ -0,0 +1,18 @@ +"""Index candidate lookups without scanning all allocations in related subnets.""" + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("openwisp_ipam", "0005_default_groups_permissions"), + ] + + operations = [ + migrations.AddIndex( + model_name="ipaddress", + index=models.Index( + fields=["subnet", "ip_address"], name="openwisp_ip_subnet__f3f94b_idx" + ), + ), + ] diff --git a/openwisp_ipam/tests/test_models.py b/openwisp_ipam/tests/test_models.py index 1b8dbee..ed24cc8 100644 --- a/openwisp_ipam/tests/test_models.py +++ b/openwisp_ipam/tests/test_models.py @@ -5,6 +5,7 @@ from unittest.mock import patch from django.core.exceptions import ValidationError +from django.db import connection from django.db.models import QuerySet from django.test import TestCase from swapper import load_model @@ -882,3 +883,18 @@ def test_request_ip_after_full_allocation_batch(self): ) self.assertEqual(child.get_next_available_ip(), "10.0.1.1") self.assertEqual(child.request_ip().ip_address, "10.0.1.1") + + def test_ip_allocation_composite_index(self): + with connection.cursor() as cursor: + constraints = connection.introspection.get_constraints( + cursor, IpAddress._meta.db_table + ) + self.assertIn( + ["subnet_id", "ip_address"], + [ + constraint["columns"] + for constraint in constraints.values() + if constraint["index"] + ], + "Candidate batches need a composite index to avoid rescanning subnet IPs.", + ) diff --git a/tests/openwisp2/sample_ipam/migrations/0001_initial.py b/tests/openwisp2/sample_ipam/migrations/0001_initial.py index 54b7e56..450d055 100644 --- a/tests/openwisp2/sample_ipam/migrations/0001_initial.py +++ b/tests/openwisp2/sample_ipam/migrations/0001_initial.py @@ -143,4 +143,10 @@ class Migration(migrations.Migration): model_name="subnet", index=models.Index(fields=["subnet"], name="subnet_idx"), ), + migrations.AddIndex( + model_name="ipaddress", + index=models.Index( + fields=["subnet", "ip_address"], name="sample_ipam_subnet__643acf_idx" + ), + ), ] From 2de40c962ec0a0f489b6bb401807b98415e6e394 Mon Sep 17 00:00:00 2001 From: Gagan Deep Date: Fri, 4 Dec 2026 22:01:00 +0530 Subject: [PATCH 5/5] [chores] Addressed review feedback Streamed related allocations once and retained only addresses in the requested subnet. This avoids repeated batch scans and a schema change, but still reads ancestor allocations and retains in-subnet addresses. --- docs/developer/extending.rst | 7 -- openwisp_ipam/base/models.py | 40 +++++------ .../0006_ipaddress_allocation_index.py | 18 ----- openwisp_ipam/tests/test_models.py | 68 ++++++++----------- .../sample_ipam/migrations/0001_initial.py | 6 -- 5 files changed, 43 insertions(+), 96 deletions(-) delete mode 100644 openwisp_ipam/migrations/0006_ipaddress_allocation_index.py diff --git a/docs/developer/extending.rst b/docs/developer/extending.rst index cdacb8c..d64021b 100644 --- a/docs/developer/extending.rst +++ b/docs/developer/extending.rst @@ -203,13 +203,6 @@ For more information, refer to the `"Migrations" section in the django documentation `_. -When upgrading an existing custom app, generate and apply its migrations -again to include changes inherited from the abstract models. In -particular, ``AbstractIpAddress.Meta`` defines a composite index on -``subnet`` and ``ip_address`` so allocation batches do not repeatedly scan -all addresses in related subnets. If your custom model overrides -``Meta.indexes``, include the inherited indexes as well. - 10. Create the Admin -------------------- diff --git a/openwisp_ipam/base/models.py b/openwisp_ipam/base/models.py index f4bf3ab..5bff9e5 100644 --- a/openwisp_ipam/base/models.py +++ b/openwisp_ipam/base/models.py @@ -2,7 +2,6 @@ from bisect import bisect_right from io import StringIO from ipaddress import ip_address, ip_network -from itertools import islice import openpyxl from django.core.exceptions import ValidationError @@ -298,29 +297,24 @@ def get_next_available_ip(self): IP address records in this subnet, its ancestors and descendants are skipped, matching duplicate validation when the address is saved. """ - related_ips = load_model("openwisp_ipam", "IpAddress").objects.filter( - subnet_id__in=self.get_related_subnet_pks() + related_ips = ( + load_model("openwisp_ipam", "IpAddress") + .objects.filter(subnet_id__in=self.get_related_subnet_pks()) + .values_list("ip_address", flat=True) + .iterator() ) - containing_networks = self._get_containing_networks() - subnet_hosts = ( - str(host) - for host in self.subnet.hosts() - if self._is_ip_usable(host, containing_networks) + # Filter as addresses are read so unrelated ancestor IPs are not retained. + # Python membership also works with SQLite text and PostgreSQL inet fields. + ipaddress_set = set( + address for address in related_ips if ip_address(address) in self.subnet ) - # Bound fetched allocations to candidate addresses, not entire ancestors. - # Equality works on both SQLite text fields and PostgreSQL inet fields. - while True: - candidates = list(islice(subnet_hosts, 256)) - if not candidates: - break - ipaddress_set = set( - related_ips.filter(ip_address__in=candidates) - .values_list("ip_address", flat=True) - .iterator() - ) - for host in candidates: - if host not in ipaddress_set: - return host + containing_networks = self._get_containing_networks() + for host in self.subnet.hosts(): + if ( + self._is_ip_usable(host, containing_networks) + and str(host) not in ipaddress_set + ): + return str(host) return None def get_allocation(self, organization_filter=None): @@ -540,8 +534,6 @@ class Meta: abstract = True verbose_name = _("IP address") verbose_name_plural = _("IP addresses") - # Candidate batches must not rescan every allocation in each related subnet. - indexes = [models.Index(fields=["subnet", "ip_address"])] def __str__(self): return self.ip_address diff --git a/openwisp_ipam/migrations/0006_ipaddress_allocation_index.py b/openwisp_ipam/migrations/0006_ipaddress_allocation_index.py deleted file mode 100644 index e3dbcb5..0000000 --- a/openwisp_ipam/migrations/0006_ipaddress_allocation_index.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Index candidate lookups without scanning all allocations in related subnets.""" - -from django.db import migrations, models - - -class Migration(migrations.Migration): - dependencies = [ - ("openwisp_ipam", "0005_default_groups_permissions"), - ] - - operations = [ - migrations.AddIndex( - model_name="ipaddress", - index=models.Index( - fields=["subnet", "ip_address"], name="openwisp_ip_subnet__f3f94b_idx" - ), - ), - ] diff --git a/openwisp_ipam/tests/test_models.py b/openwisp_ipam/tests/test_models.py index ed24cc8..ea6e1be 100644 --- a/openwisp_ipam/tests/test_models.py +++ b/openwisp_ipam/tests/test_models.py @@ -6,8 +6,8 @@ from django.core.exceptions import ValidationError from django.db import connection -from django.db.models import QuerySet from django.test import TestCase +from django.test.utils import CaptureQueriesContext from swapper import load_model from openwisp_ipam.base.models import CsvImportException @@ -838,40 +838,35 @@ def test_request_ip_skips_related_subnet_allocations(self): self.assertEqual(child.get_next_available_ip(), None) self.assertEqual(child.request_ip(), None) - def test_child_allocation_does_not_read_unrelated_parent_ips(self): - original_iterator = QuerySet.iterator - addresses_read = [] + def test_child_allocation_retains_only_addresses_in_subnet(self): + retained_addresses = [] - def track_addresses(queryset, *args, **kwargs): - for value in original_iterator(queryset, *args, **kwargs): - if queryset.model is IpAddress: - addresses_read.append(value) - yield value + def capture_set(values): + result = set(values) + retained_addresses.append(result) + return result + # Observe the set because the result alone cannot show retained memory. with self.subTest("IPv4 ancestor allocations outside the child"): parent = self._create_subnet(subnet="10.0.0.0/24") - child = self._create_subnet(subnet="10.0.0.1/32", master_subnet=parent) - self._create_ipaddress(subnet=parent, ip_address="10.0.0.2") + child = self._create_subnet(subnet="10.0.0.0/30", master_subnet=parent) + self._create_ipaddress(subnet=parent, ip_address="10.0.0.1") self._create_ipaddress(subnet=parent, ip_address="10.0.0.10") - with patch.object(QuerySet, "iterator", track_addresses): - self.assertEqual(child.get_next_available_ip(), "10.0.0.1") - self.assertEqual( - addresses_read, [], "Child allocation must not fetch unrelated IPs." - ) + with patch("openwisp_ipam.base.models.set", capture_set, create=True): + self.assertEqual(child.get_next_available_ip(), "10.0.0.2") + self.assertEqual(retained_addresses, [{"10.0.0.1"}]) with self.subTest("IPv6 ancestor allocations outside the child"): - addresses_read.clear() + retained_addresses.clear() parent = self._create_subnet(subnet="2001:db8::/120") - child = self._create_subnet(subnet="2001:db8::1/128", master_subnet=parent) - self._create_ipaddress(subnet=parent, ip_address="2001:db8::2") + child = self._create_subnet(subnet="2001:db8::/126", master_subnet=parent) + self._create_ipaddress(subnet=parent, ip_address="2001:db8::1") self._create_ipaddress(subnet=parent, ip_address="2001:db8::10") - with patch.object(QuerySet, "iterator", track_addresses): - self.assertEqual(child.get_next_available_ip(), "2001:db8::1") - self.assertEqual( - addresses_read, [], "Child allocation must not fetch unrelated IPs." - ) + with patch("openwisp_ipam.base.models.set", capture_set, create=True): + self.assertEqual(child.get_next_available_ip(), "2001:db8::2") + self.assertEqual(retained_addresses, [{"2001:db8::1"}]) - def test_request_ip_after_full_allocation_batch(self): + def test_request_ip_after_many_related_allocations(self): parent = self._create_subnet(subnet="10.0.0.0/22") child = self._create_subnet(subnet="10.0.0.0/23", master_subnet=parent) # Bulk insertion keeps the allocation regression independent of validation. @@ -881,20 +876,11 @@ def test_request_ip_after_full_allocation_batch(self): for address in islice(child.subnet.hosts(), 256) ] ) - self.assertEqual(child.get_next_available_ip(), "10.0.1.1") + with CaptureQueriesContext(connection) as queries: + self.assertEqual(child.get_next_available_ip(), "10.0.1.1") + ip_table = connection.ops.quote_name(IpAddress._meta.db_table) + allocation_queries = [ + query for query in queries if f"FROM {ip_table}" in query["sql"] + ] + self.assertEqual(len(allocation_queries), 1) self.assertEqual(child.request_ip().ip_address, "10.0.1.1") - - def test_ip_allocation_composite_index(self): - with connection.cursor() as cursor: - constraints = connection.introspection.get_constraints( - cursor, IpAddress._meta.db_table - ) - self.assertIn( - ["subnet_id", "ip_address"], - [ - constraint["columns"] - for constraint in constraints.values() - if constraint["index"] - ], - "Candidate batches need a composite index to avoid rescanning subnet IPs.", - ) diff --git a/tests/openwisp2/sample_ipam/migrations/0001_initial.py b/tests/openwisp2/sample_ipam/migrations/0001_initial.py index 450d055..54b7e56 100644 --- a/tests/openwisp2/sample_ipam/migrations/0001_initial.py +++ b/tests/openwisp2/sample_ipam/migrations/0001_initial.py @@ -143,10 +143,4 @@ class Migration(migrations.Migration): model_name="subnet", index=models.Index(fields=["subnet"], name="subnet_idx"), ), - migrations.AddIndex( - model_name="ipaddress", - index=models.Index( - fields=["subnet", "ip_address"], name="sample_ipam_subnet__643acf_idx" - ), - ), ]