Browse Source

Fixes #23791: Record reference releases before deletions (#23793)

* Fixes #23791: Record reference releases before deletions

Deleting an object recorded its deletion before the updates to the
objects which referred to it, so the change log could not be undone in
reverse order: each reference was restored before the object it points
to. References are now released, and recorded, ahead of the deletion,
including when both objects are deleted in the same request.

Creating an interface with a primary MAC address, or a virtual chassis
with a master, now records the reference in a change of its own, after
the other object has been updated to belong to the new one.

* Address review: protection rules, delete events, failed creates

Run deletion protection rules while the object is still referenced,
describe a deleted object in its event as it was before its references
were released, and leave an interface or virtual chassis unsaved when
its three-step creation fails. A MAC address deleted along with its
interface through a queryset no longer updates the interface after
its deletion is recorded.

* review fixes

* Save only released fields when clearing primary IPs

* review fixes

* Save custom field defaults when releasing references

Saves that release a reference ahead of a deletion now write
custom_field_data when save() populates a default, so the database
matches the recorded change. Releasing a primary IP also skips an
object deleted concurrently, as main's signal handlers do.

* review fixes
Arthur Hanson 11 hours ago
parent
commit
085cfb92ed

+ 10 - 0
docs/features/change-logging.md

@@ -16,6 +16,16 @@ When editing an object via the web UI, the "Changelog message" field appears at
 
 For information on including changelog messages when making changes via the REST API, see [Changelog Messages](../integrations/rest-api.md#changelog-messages).
 
+## Order of Changes
+
+Saving or deleting an object can lead NetBox to change other objects as well. Where it does, NetBox records the changes in an order in which each one is valid by itself, given only the changes before it, and can be undone by itself, given only the changes after it. For example:
+
+* Deleting a cable records an update to each interface it was attached to, clearing the cable, ahead of the deletion of the cable.
+* Creating an interface with an existing MAC address as its primary records the creation of the interface, then the assignment of the MAC address to it, and only then an update to the interface designating that MAC address as primary.
+
+!!! note
+    Deleting objects through a queryset (`queryset.delete()`) bypasses the model hook which records the release of references ahead of a deletion. Delete objects individually where the order of changes matters.
+
 ## Correlating Changes by Request
 
 Every request made to NetBox is assigned a random unique ID that can be used to correlate change records. For example, if you change the status of three sites using the UI's bulk edit feature, you will see three new change records (one for each site) all referencing the same request ID. This shows that all three changes were made as part of the same request.

+ 14 - 14
netbox/circuits/models/circuits.py

@@ -3,7 +3,7 @@ from itertools import batched
 from django.apps import apps
 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
 from django.core.exceptions import ValidationError
-from django.db import models
+from django.db import models, transaction
 from django.urls import reverse
 from django.utils.translation import gettext_lazy as _
 
@@ -11,6 +11,7 @@ from circuits.choices import *
 from dcim.models import CabledObjectModel
 from dcim.utils import rebuild_paths
 from netbox.models import ChangeLoggedModel, OrganizationalModel, PrimaryModel
+from netbox.models.deletion import release_update_fields
 from netbox.models.features import (
     ContactsMixin,
     CustomFieldsMixin,
@@ -248,17 +249,11 @@ def _set_circuit_terminations(circuit, fields, using):
     """
     Set or clear a Circuit's cached `termination_a`/`termination_z` fields, recording the change.
     """
-    from extras.models import CustomField
-
     circuit.snapshot()
     for field_name, value in fields.items():
         setattr(circuit, field_name, value)
 
-    # Write custom_field_data only if save() will populate a default, which the change log serializes
-    update_fields = [*fields, 'last_updated']
-    if CustomField.objects.get_defaults_for_model(circuit).keys() - circuit.custom_field_data.keys():
-        update_fields.append('custom_field_data')
-    circuit.save(using=using, update_fields=update_fields)
+    circuit.save(using=using, update_fields=release_update_fields(circuit, fields))
 
 
 class CircuitTermination(
@@ -444,11 +439,10 @@ class CircuitTermination(
     @classmethod
     def clear_cached_references(cls, instances, collector):
         # Called by CustomCollector ahead of the DELETE, for explicit and cascaded deletions alike
-        doomed_circuits = {circuit.pk for circuit in collector.data.get(Circuit, ())}
-
-        # A circuit only points at its own terminations, so any deleted along with it need no clear
-        pks = {instance.pk for instance in instances if instance.circuit_id not in doomed_circuits}
-        circuit_ids = {instance.circuit_id for instance in instances if instance.pk in pks}
+        # A circuit deleted along with its terminations is cleared too: restoring it (when the deletion is
+        # replayed in reverse) precedes restoring them, so it can't be restored still pointing at them
+        pks = {instance.pk for instance in instances}
+        circuit_ids = {instance.circuit_id for instance in instances}
 
         for batch in batched(circuit_ids, 1000):
             # Read and write on the deletion's alias, inside its transaction
@@ -460,7 +454,13 @@ class CircuitTermination(
                     if getattr(circuit, f'{name}_id') in pks
                 }
                 if fields:
-                    _set_circuit_terminations(circuit, fields, using=collector.using)
+                    # Prevent recreation of a concurrently deleted circuit without aborting the deletion transaction
+                    try:
+                        with transaction.atomic(using=collector.using):
+                            _set_circuit_terminations(circuit, fields, using=collector.using)
+                    except Circuit.NotUpdated:
+                        continue
+                    collector.update_collected(circuit, fields)
 
     def cache_related_objects(self):
         self._provider_network = self._region = self._site_group = self._site = self._location = None

+ 13 - 8
netbox/core/signals.py

@@ -198,7 +198,8 @@ def handle_deleted_object(sender, instance, using=None, **kwargs):
     model_name = f'{sender._meta.app_label}.{sender._meta.model_name}'
     validators = get_config_value_ci(get_config().PROTECTION_RULES, model_name, default=[])
     try:
-        run_validators(instance, validators)
+        # Validate the object as it was before any references were released ahead of its deletion
+        run_validators(getattr(instance, '_pre_release_state', instance), validators)
     except ValidationError as e:
         raise AbortRequest(
             _("Deletion is prevented by a protection rule: {message}").format(message=e)
@@ -219,16 +220,10 @@ def handle_deleted_object(sender, instance, using=None, **kwargs):
         return
     _signals_received.pre_delete.add(signature)
 
-    # Record an ObjectChange if applicable
-    object_change_id = None
+    # Capture the object's state before any related objects are detached from it below
     if hasattr(instance, 'to_objectchange'):
         if hasattr(instance, 'snapshot') and not getattr(instance, '_prechange_snapshot', None):
             instance.snapshot()
-        objectchange = instance.to_objectchange(ObjectChangeActionChoices.ACTION_DELETE)
-        objectchange.user = request.user
-        objectchange.request_id = request.id
-        objectchange.save()
-        object_change_id = objectchange.pk
 
     # Django does not automatically send an m2m_changed signal for the reverse direction of a
     # many-to-many relationship (see https://code.djangoproject.com/ticket/17688), so we need to
@@ -282,6 +277,16 @@ def handle_deleted_object(sender, instance, using=None, **kwargs):
                     except related_model.NotUpdated:
                         continue
 
+    # Record an ObjectChange if applicable. It follows the changes recorded above, so that each reference to
+    # the object is released before its deletion (and restored after it when the log is replayed in reverse).
+    object_change_id = None
+    if hasattr(instance, 'to_objectchange'):
+        objectchange = instance.to_objectchange(ObjectChangeActionChoices.ACTION_DELETE)
+        objectchange.user = request.user
+        objectchange.request_id = request.id
+        objectchange.save()
+        object_change_id = objectchange.pk
+
     # Enqueue the object for event processing
     queue = events_queue.get()
     enqueue_event(queue, instance, request, OBJECT_DELETED, object_change_id=object_change_id)

+ 675 - 0
netbox/core/tests/test_changelog_replay.py

@@ -0,0 +1,675 @@
+import uuid
+from unittest.mock import patch
+
+from django.db import transaction
+from django.test import RequestFactory, TestCase, override_settings
+from django.urls import reverse
+
+from circuits.models import Circuit, CircuitTermination, CircuitType, Provider
+from core.choices import ObjectChangeActionChoices
+from core.models import ObjectChange, ObjectType
+from core.signals import _signals_received
+from dcim.choices import SubdeviceRoleChoices
+from dcim.models import (
+    Cable,
+    CableTermination,
+    Device,
+    DeviceBay,
+    DeviceType,
+    Interface,
+    MACAddress,
+    Site,
+    VirtualChassis,
+    VirtualDeviceContext,
+)
+from extras.choices import CustomFieldTypeChoices
+from extras.models import CustomField, Tag
+from extras.validators import CustomValidator
+from ipam.models import IPAddress
+from netbox.context import events_queue
+from netbox.context_managers import event_tracking
+from users.models import User
+from utilities.exceptions import AbortRequest
+from utilities.fields import CounterCacheField
+from utilities.serialization import deserialize_object, serialize_object
+from utilities.testing.utils import create_test_device, create_test_virtualmachine
+from virtualization.models import VirtualMachine, VMInterface
+
+CREATE = ObjectChangeActionChoices.ACTION_CREATE
+UPDATE = ObjectChangeActionChoices.ACTION_UPDATE
+DELETE = ObjectChangeActionChoices.ACTION_DELETE
+
+# Not compared: set by each save, or (CablePaths) rebuilt with new IDs
+IGNORED_FIELDS = ('created', 'last_updated', '_path', '_config_context_generation')
+
+
+class ChangeLogReplayTestCase(TestCase):
+    """
+    Check that the changes recorded for a request can be replayed in the order recorded, and reversed in the opposite
+    order, one at a time: each must be valid given only the changes before it (or, in reverse, after it). Changes made
+    as a side effect of saving or deleting another object are the ones at risk.
+
+    The replay here is deliberately simple: an update sets the fields which changed, validates and saves; a deletion is
+    reversed by validating and saving the recorded object.
+    """
+
+    @classmethod
+    def setUpTestData(cls):
+        cls.user = User.objects.create_user(username='testuser')
+
+    def setUp(self):
+        _signals_received.pre_delete = set()
+
+    #
+    # Helpers
+    #
+
+    def _record(self, change):
+        """Make a change under change logging and return the ObjectChanges recorded, in order."""
+        last_pk = ObjectChange.objects.order_by('-pk').values_list('pk', flat=True).first() or 0
+        request = RequestFactory().get(reverse('home'))
+        request.id = uuid.uuid4()
+        request.user = self.user
+        with event_tracking(request):
+            change()
+        return list(ObjectChange.objects.filter(pk__gt=last_pk).order_by('pk'))
+
+    @staticmethod
+    def _state(models):
+        state = {}
+        for model in models:
+            # Counter caches are recorded with each change, so replaying the changes to the objects counted as well
+            # counts them twice (a separate problem from the order of the changes)
+            counters = [field.name for field in model._meta.concrete_fields if isinstance(field, CounterCacheField)]
+            for obj in model.objects.order_by('pk'):
+                data = serialize_object(obj)
+                for field in (*IGNORED_FIELDS, *counters):
+                    data.pop(field, None)
+                state[(model._meta.label, obj.pk)] = data
+        return state
+
+    def _assert_state(self, models, expected, msg):
+        actual = self._state(models)
+        differences = {}
+        for key in actual.keys() | expected.keys():
+            a, e = actual.get(key), expected.get(key)
+            if a is None or e is None:
+                differences[key] = 'unexpected' if e is None else 'missing'
+            elif a != e:
+                differences[key] = {field: (a.get(field), e.get(field)) for field in a if a.get(field) != e.get(field)}
+        self.assertEqual(differences, {}, msg)
+
+    @staticmethod
+    def _insert(model, pk, data, raw):
+        instance = deserialize_object(model, data, pk=pk)
+        instance.object.full_clean()
+        if raw:
+            instance.save()
+        else:
+            instance.object.save(force_insert=True)
+            for accessor, objects in (instance.m2m_data or {}).items():
+                getattr(instance.object, accessor).set(objects)
+
+    @staticmethod
+    def _update(model, pk, source, target):
+        obj = model.objects.get(pk=pk)
+        m2m = {}
+        for key in source.keys() | target.keys():
+            if source.get(key) == (value := target.get(key)):
+                continue
+            if key == 'custom_fields':
+                obj.custom_field_data = value
+            elif key == 'tags':
+                m2m[key] = Tag.objects.filter(name__in=value)
+            elif key not in {field.name for field in model._meta.get_fields()}:
+                # Not a field (e.g. a cable's terminations, which are recorded as changes of their own)
+                continue
+            elif (field := model._meta.get_field(key)).many_to_many:
+                m2m[key] = value
+            elif field.is_relation:
+                setattr(obj, field.attname, value)
+            else:
+                setattr(obj, key, field.to_python(value))
+        obj.full_clean()
+        obj.save()
+        for key, value in m2m.items():
+            getattr(obj, key).set(value)
+
+    def _apply(self, change, reverse=False):
+        model = change.changed_object_type.model_class()
+        pk = change.changed_object_id
+        action = change.action
+        if reverse and action != UPDATE:
+            action = DELETE if action == CREATE else CREATE
+        if action == CREATE:
+            # A reversed deletion is saved normally, so that the model derives what the clean data leaves out
+            self._insert(model, pk, change.prechange_data_clean if reverse else change.postchange_data, raw=not reverse)
+        elif action == DELETE:
+            model.objects.get(pk=pk).delete()
+        elif reverse:
+            self._update(model, pk, change.postchange_data_clean, change.prechange_data_clean)
+        else:
+            self._update(model, pk, change.prechange_data_clean, change.postchange_data_clean)
+
+    def _replay(self, changes, reverse=False):
+        for change in reversed(changes) if reverse else changes:
+            try:
+                self._apply(change, reverse=reverse)
+            except Exception as e:
+                position = changes.index(change) + 1
+                verb = 'reversing' if reverse else 'replaying'
+                e.add_note(f'While {verb} change {position} of {len(changes)}: {change}')
+                raise
+
+    def assertReplayable(self, change, models, expected):
+        """
+        Make a change, check the changes recorded for it against `expected`, a list of (action, model), then reverse,
+        replay and reverse them again, checking the state of `models` each time.
+        """
+        original = self._state(models)
+        changes = self._record(change)
+        changed = self._state(models)
+        self.assertNotEqual(changed, original)
+
+        recorded = [(change.action, change.changed_object_type.model_class()) for change in changes]
+        self.assertEqual(recorded, expected)
+
+        self._replay(changes, reverse=True)
+        self._assert_state(models, original, 'Unexpected state after reversing the changes')
+        self._replay(changes)
+        self._assert_state(models, changed, 'Unexpected state after replaying the changes')
+        self._replay(changes, reverse=True)
+        self._assert_state(models, original, 'Unexpected state after reversing the changes again')
+
+        return changes
+
+    @staticmethod
+    def _create_cabled_interfaces():
+        devices = [create_test_device(f'Device {i}') for i in (1, 2)]
+        interfaces = [Interface.objects.create(device=device, name='eth0', type='1000base-t') for device in devices]
+        cable = Cable(a_terminations=[interfaces[0]], b_terminations=[interfaces[1]])
+        cable.save()
+        return cable, interfaces
+
+    #
+    # References released ahead of a deletion
+    #
+
+    def test_cable_delete(self):
+        cable, _ = self._create_cabled_interfaces()
+
+        self.assertReplayable(
+            lambda: Cable.objects.get(pk=cable.pk).delete(),
+            (Cable, CableTermination, Interface),
+            [
+                (DELETE, CableTermination),
+                (UPDATE, Interface),
+                (DELETE, CableTermination),
+                (UPDATE, Interface),
+                (DELETE, Cable),
+            ],
+        )
+
+    def test_cable_queryset_delete(self):
+        cable, _ = self._create_cabled_interfaces()
+
+        self.assertReplayable(
+            lambda: Cable.objects.filter(pk=cable.pk).delete(),
+            (Cable, CableTermination, Interface),
+            [
+                (DELETE, CableTermination),
+                (UPDATE, Interface),
+                (DELETE, CableTermination),
+                (UPDATE, Interface),
+                (DELETE, Cable),
+            ],
+        )
+
+    def test_cable_create(self):
+        devices = [create_test_device(f'Device {i}') for i in (1, 2)]
+        interfaces = [Interface.objects.create(device=device, name='eth0', type='1000base-t') for device in devices]
+
+        def change():
+            Cable(
+                a_terminations=[Interface.objects.get(pk=interfaces[0].pk)],
+                b_terminations=[Interface.objects.get(pk=interfaces[1].pk)],
+            ).save()
+
+        self.assertReplayable(
+            change,
+            (Cable, CableTermination, Interface),
+            [
+                (CREATE, Cable),
+                (CREATE, CableTermination),
+                (UPDATE, Interface),
+                (CREATE, CableTermination),
+                (UPDATE, Interface),
+                (UPDATE, Cable),
+            ],
+        )
+
+    def test_nullable_reference_delete(self):
+        """An object referring to a deleted object through a nullable foreign key is updated ahead of the deletion."""
+        device = create_test_device('Device 1')
+        lag = Interface.objects.create(device=device, name='ae0', type='lag')
+        Interface.objects.create(device=device, name='eth0', type='1000base-t', lag=lag)
+
+        self.assertReplayable(
+            lambda: Interface.objects.get(pk=lag.pk).delete(),
+            (Interface,),
+            [(UPDATE, Interface), (DELETE, Interface)],
+        )
+
+    def test_tag_delete(self):
+        """An object assigned a deleted tag is updated ahead of the deletion."""
+        site = Site.objects.create(name='Site 1', slug='site-1')
+        tag = Tag.objects.create(name='Tag 1', slug='tag-1')
+        site.tags.add(tag)
+
+        self.assertReplayable(
+            lambda: Tag.objects.get(pk=tag.pk).delete(),
+            (Tag, Site),
+            [(UPDATE, Site), (DELETE, Tag)],
+        )
+
+    def _create_device_ip(self, field_name):
+        device = create_test_device('Device 1')
+        interface = Interface.objects.create(device=device, name='eth0', type='1000base-t')
+        ip = IPAddress.objects.create(address='192.0.2.1/24', assigned_object=interface)
+        device.refresh_from_db()
+        setattr(device, field_name, ip)
+        device.save()
+        return device, ip
+
+    def test_primary_ip_delete(self):
+        _, ip = self._create_device_ip('primary_ip4')
+
+        self.assertReplayable(
+            lambda: IPAddress.objects.get(pk=ip.pk).delete(),
+            (IPAddress, Device),
+            [(UPDATE, Device), (DELETE, IPAddress)],
+        )
+
+    def test_primary_ip_queryset_delete(self):
+        """A queryset bypasses the model's deletion hook, so the reference is released after the deletion."""
+        _, ip = self._create_device_ip('primary_ip4')
+
+        changes = self._record(lambda: IPAddress.objects.filter(pk=ip.pk).delete())
+
+        self.assertEqual(
+            [(change.action, change.changed_object_type.model_class()) for change in changes],
+            [(DELETE, IPAddress), (UPDATE, Device)],
+        )
+
+    def test_oob_ip_delete(self):
+        _, ip = self._create_device_ip('oob_ip')
+
+        self.assertReplayable(
+            lambda: IPAddress.objects.get(pk=ip.pk).delete(),
+            (IPAddress, Device),
+            [(UPDATE, Device), (DELETE, IPAddress)],
+        )
+
+    def test_virtual_machine_primary_ip_delete(self):
+        vm = create_test_virtualmachine('VM 1')
+        interface = VMInterface.objects.create(virtual_machine=vm, name='eth0')
+        ip = IPAddress.objects.create(address='2001:db8::1/64', assigned_object=interface)
+        vm.primary_ip6 = ip
+        vm.save()
+
+        self.assertReplayable(
+            lambda: IPAddress.objects.get(pk=ip.pk).delete(),
+            (IPAddress, VirtualMachine),
+            [(UPDATE, VirtualMachine), (DELETE, IPAddress)],
+        )
+
+    def test_device_with_primary_ip_delete(self):
+        """A device deleted along with its primary IP address releases it first, as it is restored before it."""
+        device, _ = self._create_device_ip('primary_ip4')
+
+        self.assertReplayable(
+            lambda: Device.objects.get(pk=device.pk).delete(),
+            (IPAddress, Interface, Device),
+            [(UPDATE, Device), (DELETE, IPAddress), (DELETE, Interface), (DELETE, Device)],
+        )
+
+    def test_parent_device_primary_ip_delete(self):
+        """Releasing a parent device's primary IP does not re-save (and queue an event for) its child devices."""
+        parent, ip = self._create_device_ip('primary_ip4')
+        parent.device_type.subdevice_role = SubdeviceRoleChoices.ROLE_PARENT
+        parent.device_type.save()
+        child_type = DeviceType.objects.create(
+            manufacturer=parent.device_type.manufacturer,
+            model='Child Device Type',
+            slug='child-device-type',
+            u_height=0,
+            subdevice_role=SubdeviceRoleChoices.ROLE_CHILD,
+        )
+        child = Device.objects.create(name='Child Device', site=parent.site, device_type=child_type, role=parent.role)
+        DeviceBay.objects.create(device=parent, name='Bay 1', installed_device=child)
+        request = RequestFactory().get(reverse('home'))
+        request.id = uuid.uuid4()
+        request.user = self.user
+
+        with event_tracking(request), patch('netbox.context_managers.flush_events'):
+            IPAddress.objects.get(pk=ip.pk).delete()
+            queued = set(events_queue.get())
+
+        self.assertIn(f'dcim.device:{parent.pk}', queued)
+        self.assertNotIn(f'dcim.device:{child.pk}', queued)
+
+    def test_virtual_device_context_primary_ip_delete(self):
+        device, ip = self._create_device_ip('primary_ip4')
+        VirtualDeviceContext.objects.create(device=device, name='VDC 1', status='active', primary_ip4=ip)
+
+        self.assertReplayable(
+            lambda: IPAddress.objects.get(pk=ip.pk).delete(),
+            (IPAddress, Device, VirtualDeviceContext),
+            [(UPDATE, Device), (UPDATE, VirtualDeviceContext), (DELETE, IPAddress)],
+        )
+
+    def test_delete_event_describes_object_before_references_are_released(self):
+        device, ip = self._create_device_ip('primary_ip4')
+        request = RequestFactory().get(reverse('home'))
+        request.id = uuid.uuid4()
+        request.user = self.user
+
+        with event_tracking(request), patch('netbox.context_managers.flush_events'):
+            Device.objects.get(pk=device.pk).delete()
+            event = events_queue.get()[f'dcim.device:{device.pk}']
+
+        self.assertEqual(event['event_type'], 'object_deleted')
+        self.assertEqual(event['data']['primary_ip4']['id'], ip.pk)
+
+    def _create_primary_mac(self):
+        device = create_test_device('Device 1')
+        interface = Interface.objects.create(device=device, name='eth0', type='1000base-t')
+        mac = MACAddress.objects.create(mac_address='00:11:22:33:44:55', assigned_object=interface)
+        interface.primary_mac_address = mac
+        interface.save()
+        return interface, mac
+
+    def test_primary_mac_delete(self):
+        _, mac = self._create_primary_mac()
+
+        self.assertReplayable(
+            lambda: MACAddress.objects.get(pk=mac.pk).delete(),
+            (MACAddress, Interface),
+            [(UPDATE, Interface), (DELETE, MACAddress)],
+        )
+
+    def test_interface_with_primary_mac_delete(self):
+        """An interface deleted along with its primary MAC address releases it first, as it is restored before it."""
+        interface, _ = self._create_primary_mac()
+
+        self.assertReplayable(
+            lambda: Interface.objects.get(pk=interface.pk).delete(),
+            (MACAddress, Interface),
+            [(UPDATE, Interface), (DELETE, MACAddress), (DELETE, Interface)],
+        )
+
+    def _create_circuit(self):
+        provider = Provider.objects.create(name='Provider 1', slug='provider-1')
+        circuit_type = CircuitType.objects.create(name='Circuit Type 1', slug='circuit-type-1')
+        circuit = Circuit.objects.create(cid='Circuit 1', provider=provider, type=circuit_type)
+        site = Site.objects.create(name='Site 1', slug='site-1')
+        termination = CircuitTermination.objects.create(circuit=circuit, term_side='A', termination=site)
+        return circuit, termination
+
+    def test_circuit_termination_delete(self):
+        _, termination = self._create_circuit()
+
+        self.assertReplayable(
+            lambda: CircuitTermination.objects.get(pk=termination.pk).delete(),
+            (Circuit, CircuitTermination),
+            [(UPDATE, Circuit), (DELETE, CircuitTermination)],
+        )
+
+    def test_circuit_delete(self):
+        """A circuit deleted along with its terminations releases them first, as it is restored before them."""
+        circuit, _ = self._create_circuit()
+
+        self.assertReplayable(
+            lambda: Circuit.objects.get(pk=circuit.pk).delete(),
+            (Circuit, CircuitTermination),
+            [(UPDATE, Circuit), (DELETE, CircuitTermination), (DELETE, Circuit)],
+        )
+
+    #
+    # References between two objects, each made in a change of its own
+    #
+
+    def test_interface_create_with_primary_mac(self):
+        device = create_test_device('Device 1')
+        mac = MACAddress.objects.create(mac_address='00:11:22:33:44:55')
+
+        def change():
+            Interface.objects.create(
+                device=device, name='eth0', type='1000base-t', primary_mac_address=MACAddress.objects.get(pk=mac.pk)
+            )
+
+        changes = self.assertReplayable(
+            change,
+            (Interface, MACAddress),
+            [(CREATE, Interface), (UPDATE, MACAddress), (UPDATE, Interface)],
+        )
+        self.assertIsNone(changes[0].postchange_data['primary_mac_address'])
+        self.assertEqual(changes[2].postchange_data['primary_mac_address'], mac.pk)
+
+    def test_vminterface_create_with_primary_mac(self):
+        vm = create_test_virtualmachine('VM 1')
+        mac = MACAddress.objects.create(mac_address='00:11:22:33:44:55')
+
+        def change():
+            VMInterface.objects.create(
+                virtual_machine=vm, name='eth0', primary_mac_address=MACAddress.objects.get(pk=mac.pk)
+            )
+
+        self.assertReplayable(
+            change,
+            (VMInterface, MACAddress),
+            [(CREATE, VMInterface), (UPDATE, MACAddress), (UPDATE, VMInterface)],
+        )
+
+    def test_virtual_chassis_create_with_master(self):
+        device = create_test_device('Device 1')
+
+        changes = self.assertReplayable(
+            lambda: VirtualChassis.objects.create(name='VC 1', master=Device.objects.get(pk=device.pk)),
+            (VirtualChassis, Device),
+            [(CREATE, VirtualChassis), (UPDATE, Device), (UPDATE, VirtualChassis)],
+        )
+        self.assertIsNone(changes[0].postchange_data['master'])
+        self.assertEqual(changes[2].postchange_data['master'], device.pk)
+
+    def test_virtual_chassis_delete(self):
+        devices = [create_test_device(f'Device {i}') for i in (1, 2)]
+        vc = VirtualChassis.objects.create(name='VC 1', master=devices[0])
+        member = Device.objects.get(pk=devices[1].pk)
+        member.virtual_chassis = vc
+        member.vc_position = 2
+        member.vc_priority = 10
+        member.save()
+
+        changes = self.assertReplayable(
+            lambda: VirtualChassis.objects.get(pk=vc.pk).delete(),
+            (VirtualChassis, Device),
+            [(UPDATE, VirtualChassis), (UPDATE, Device), (UPDATE, Device), (DELETE, VirtualChassis)],
+        )
+        self.assertIsNone(changes[0].postchange_data['master'])
+        self.assertIsNone(changes[3].prechange_data['master'])
+
+    #
+    # Protection rules and queryset deletions
+    #
+
+    def test_protection_rule_sees_object_before_references_are_released(self):
+        device, _ = self._create_device_ip('primary_ip4')
+        seen = []
+
+        class Validator(CustomValidator):
+            def validate(self, instance, request):
+                seen.append(instance.primary_ip4_id)
+
+        with override_settings(PROTECTION_RULES={'dcim.device': [Validator()]}):
+            self._record(lambda: Device.objects.get(pk=device.pk).delete())
+
+        self.assertEqual(seen, [device.primary_ip4_id])
+
+    def test_primary_mac_queryset_delete(self):
+        """A queryset bypasses the model's deletion hook, but the release of the primary MAC is still recorded."""
+        interface, mac = self._create_primary_mac()
+
+        changes = self._record(lambda: MACAddress.objects.filter(pk=mac.pk).delete())
+
+        self.assertEqual(
+            [(change.action, change.changed_object_type.model_class()) for change in changes],
+            [(DELETE, MACAddress), (UPDATE, Interface)],
+        )
+        interface.refresh_from_db()
+        self.assertIsNone(interface.primary_mac_address)
+
+    def test_interface_create_with_primary_mac_is_atomic(self):
+        device = create_test_device('Device 1')
+        mac = MACAddress.objects.create(mac_address='00:11:22:33:44:55')
+        interface = Interface(device=device, name='eth0', type='1000base-t', primary_mac_address=mac)
+
+        with patch.object(MACAddress, 'save', side_effect=RuntimeError), self.assertRaises(RuntimeError):
+            interface.save()
+
+        self.assertFalse(Interface.objects.filter(device=device).exists())
+        self.assertEqual(interface.primary_mac_address, mac)
+        self.assertIsNone(interface.pk)
+
+        # The interface can be saved again as if for the first time
+        interface.save()
+        mac.refresh_from_db()
+        self.assertEqual(mac.assigned_object, interface)
+
+    def test_protection_rule_sees_object_while_still_referenced(self):
+        _, ip = self._create_device_ip('primary_ip4')
+        rules = {'ipam.ipaddress': [{'is_primary_ip': {'eq': False}}]}
+
+        with override_settings(PROTECTION_RULES=rules), self.assertRaises(AbortRequest):
+            self._record(lambda: IPAddress.objects.get(pk=ip.pk).delete())
+
+    def test_aborted_delete_restores_released_references(self):
+        """A deletion aborted after its references were released leaves the caller's instance as it was."""
+        device, ip = self._create_device_ip('primary_ip4')
+        device = Device.objects.get(pk=device.pk)
+        last_updated = device.last_updated
+        rules = {'dcim.interface': [{'name': {'neq': 'eth0'}}]}
+
+        with override_settings(PROTECTION_RULES=rules), self.assertRaises(AbortRequest):
+            with transaction.atomic():
+                self._record(device.delete)
+
+        self.assertEqual(device.primary_ip4_id, ip.pk)
+        self.assertEqual(device.last_updated, last_updated)
+        self.assertFalse(hasattr(device, '_pre_release_state'))
+
+    def test_reused_instance_delete_event_describes_the_new_object(self):
+        """An instance deleted, saved again as a new object and deleted again is described as the new object."""
+        device, _ = self._create_device_ip('primary_ip4')
+        device = Device.objects.get(pk=device.pk)
+        self._record(device.delete)
+        self.assertFalse(hasattr(device, '_pre_release_state'))
+
+        device.save()
+        interface = Interface.objects.create(device=device, name='eth0', type='1000base-t')
+        ip = IPAddress.objects.create(address='192.0.2.2/24', assigned_object=interface)
+        device.primary_ip4 = ip
+        device.save()
+        pk = device.pk
+        request = RequestFactory().get(reverse('home'))
+        request.id = uuid.uuid4()
+        request.user = self.user
+
+        with event_tracking(request), patch('netbox.context_managers.flush_events'):
+            device.delete()
+            event = events_queue.get()[f'dcim.device:{pk}']
+
+        self.assertEqual(event['data']['id'], pk)
+        self.assertEqual(event['data']['primary_ip4']['id'], ip.pk)
+
+    def test_primary_mac_delete_tolerates_concurrently_deleted_interface(self):
+        _, mac = self._create_primary_mac()
+
+        with patch.object(Interface, 'save', side_effect=Interface.NotUpdated):
+            self._record(lambda: MACAddress.objects.get(pk=mac.pk).delete())
+
+        self.assertFalse(MACAddress.objects.filter(pk=mac.pk).exists())
+
+    def test_circuit_termination_delete_tolerates_concurrently_deleted_circuit(self):
+        _, termination = self._create_circuit()
+
+        with patch.object(Circuit, 'save', side_effect=Circuit.NotUpdated):
+            self._record(lambda: CircuitTermination.objects.get(pk=termination.pk).delete())
+
+        self.assertFalse(CircuitTermination.objects.filter(pk=termination.pk).exists())
+
+    def test_primary_mac_delete_event_describes_it_as_primary(self):
+        _, mac = self._create_primary_mac()
+        request = RequestFactory().get(reverse('home'))
+        request.id = uuid.uuid4()
+        request.user = self.user
+
+        with event_tracking(request), patch('netbox.context_managers.flush_events'):
+            MACAddress.objects.get(pk=mac.pk).delete()
+            event = events_queue.get()[f'dcim.macaddress:{mac.pk}']
+
+        self.assertTrue(event['data']['is_primary'])
+
+    def test_parent_device_narrow_save_updates_child_devices(self):
+        """A child device follows its parent's site however the save names the field."""
+        parent = create_test_device('Device 1')
+        parent.device_type.subdevice_role = SubdeviceRoleChoices.ROLE_PARENT
+        parent.device_type.save()
+        child_type = DeviceType.objects.create(
+            manufacturer=parent.device_type.manufacturer,
+            model='Child Device Type',
+            slug='child-device-type',
+            u_height=0,
+            subdevice_role=SubdeviceRoleChoices.ROLE_CHILD,
+        )
+        child = Device.objects.create(name='Child Device', site=parent.site, device_type=child_type, role=parent.role)
+        DeviceBay.objects.create(device=parent, name='Bay 1', installed_device=child)
+        sites = [Site.objects.create(name=f'Site {i}', slug=f'site-{i}') for i in (2, 3)]
+
+        for site, update_fields in zip(sites, (['site_id', 'last_updated'], iter(['site', 'last_updated']))):
+            parent.site = site
+            parent.save(update_fields=update_fields)
+            child.refresh_from_db()
+            self.assertEqual(child.site, site)
+
+    def test_interface_queryset_delete_records_nothing_after_the_deletion(self):
+        """An interface deleted through a queryset along with its primary MAC is not updated after its deletion."""
+        interface, _ = self._create_primary_mac()
+
+        changes = self._record(lambda: Interface.objects.filter(pk=interface.pk).delete())
+
+        interface_changes = [change.action for change in changes if change.changed_object_type.model == 'interface']
+        self.assertEqual(interface_changes[-1], DELETE)
+        self.assertEqual(interface_changes.count(DELETE), 1)
+        self.assertNotIn(UPDATE, interface_changes)
+
+    def test_released_references_save_custom_field_defaults(self):
+        """A custom field default populated by a release save is written, as its recorded change says."""
+        cf = CustomField.objects.create(name='cf1', type=CustomFieldTypeChoices.TYPE_TEXT, default='foo')
+        cf.object_types.set([ObjectType.objects.get_for_model(Interface)])
+
+        def check(model, pk, change):
+            obj = model.objects.get(pk=pk)
+            self.assertEqual(obj.custom_field_data, {'cf1': 'foo'})
+            self.assertEqual(change.postchange_data['custom_fields'], {'cf1': 'foo'})
+
+        for delete in (
+            lambda mac: MACAddress.objects.get(pk=mac.pk).delete(),
+            lambda mac: MACAddress.objects.filter(pk=mac.pk).delete(),
+        ):
+            with self.subTest(delete=delete), transaction.atomic():
+                interface, mac = self._create_primary_mac()
+                Interface.objects.filter(pk=interface.pk).update(custom_field_data={})
+                changes = self._record(lambda: delete(mac))
+                check(Interface, interface.pk, next(c for c in changes if c.changed_object_type.model == 'interface'))
+                transaction.set_rollback(True)

+ 2 - 2
netbox/dcim/models/cables.py

@@ -98,7 +98,7 @@ class Cable(PrimaryModel):
     A physical connection between two endpoints.
     """
     # Per-thread tracking of Cable PKs currently being deleted; referenced by
-    # dcim.signals.nullify_connected_endpoints to record the disconnect on each terminating object and
+    # dcim.signals.record_cable_disconnect to record the disconnect on each terminating object and
     # to skip per-CableTermination path retracing during the cascade (retrace_cable_paths does it once).
     _deletion_tracking = threading.local()
 
@@ -439,7 +439,7 @@ class Cable(PrimaryModel):
     @classmethod
     def _track_deletion(cls, pk):
         """
-        Track a Cable as being deleted, so that the post_delete handler for its cascaded CableTerminations can
+        Track a Cable as being deleted, so that the signal handlers for its cascaded CableTerminations can
         record the disconnect on each terminating object and skip redundant path retracing (retrace_cable_paths()
         retraces each affected path once, after the Cable itself is deleted). The tracking set lives on a
         threading.local() to isolate concurrent deletions across threads.

+ 38 - 4
netbox/dcim/models/device_components.py

@@ -884,9 +884,9 @@ class BaseInterface(models.Model):
                 'qinq_svlan': _("Only Q-in-Q interfaces may specify a service VLAN.")
             })
 
-        # A primary MAC address must belong to this interface. On create the MAC is assigned by a
-        # post_save signal after this runs, so an as-yet-unassigned MAC is only rejected on update
-        # (self._state.adding is False), where no such signal fires. These are raised as non-field
+        # A primary MAC address must belong to this interface. On create the MAC is assigned by save()
+        # after this runs, so an as-yet-unassigned MAC is only rejected on update (self._state.adding
+        # is False), where save() assigns nothing. These are raised as non-field
         # errors: primary_mac_address is not an InterfaceForm field (it's edited via the mac_address
         # shortcut), so a field-keyed error would raise in the form's add_error() rather than render.
         if self.primary_mac_address:
@@ -913,7 +913,41 @@ class BaseInterface(models.Model):
         if not self._state.adding and self.mode != InterfaceModeChoices.MODE_TAGGED:
             self.tagged_vlans.clear()
 
-        return super().save(*args, **kwargs)
+        # A primary MAC address designated on create is assigned to the interface once it exists, then designated
+        # as primary in a change of its own, so that each recorded change is valid (and reversible) by itself.
+        primary_mac_address = None
+        if self._state.adding and self.primary_mac_address_id:
+            primary_mac_address, self.primary_mac_address = self.primary_mac_address, None
+
+        if primary_mac_address is None:
+            return super().save(*args, **kwargs)
+
+        using = kwargs.get('using') or router.db_for_write(type(self), instance=self)
+        try:
+            with transaction.atomic(using=using):
+                super().save(*args, **kwargs)
+
+                # Keep any snapshot the caller took before making unsaved changes to the MAC address
+                if not hasattr(primary_mac_address, '_prechange_snapshot'):
+                    primary_mac_address.snapshot()
+                primary_mac_address.assigned_object = self
+                primary_mac_address.save(using=using)
+                # Discard the snapshot so that a later save of the MAC address takes a fresh one
+                primary_mac_address.__dict__.pop('_prechange_snapshot', None)
+
+                self.snapshot()
+                self.primary_mac_address = primary_mac_address
+                super().save(using=using, update_fields=['primary_mac_address', 'last_updated'])
+                self.__dict__.pop('_prechange_snapshot', None)
+        except Exception:
+            # The creation was rolled back, so the interface is unsaved again
+            self.pk = None
+            self._state.adding = True
+            self.primary_mac_address = primary_mac_address
+            raise
+        finally:
+            # Anything which read the MAC address while the interface had none has cached that
+            self.__dict__.pop('mac_address', None)
 
     def set_primary_mac_address(self, mac):
         """

+ 101 - 26
netbox/dcim/models/devices.py

@@ -1,7 +1,9 @@
+import copy
 import decimal
 from functools import cached_property, partial
 
 import yaml
+from django.apps import apps
 from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.postgres.indexes import GistIndex
@@ -25,6 +27,7 @@ from extras.querysets import ConfigContextModelQuerySet
 from netbox.choices import ColorChoices
 from netbox.config import ConfigItem
 from netbox.models import NestedLtreeGroupModel, OrganizationalModel, PrimaryModel
+from netbox.models.deletion import release_update_fields, run_protection_rules
 from netbox.models.features import ContactsMixin, ImageAttachmentsMixin
 from netbox.models.mixins import WeightMixin
 from utilities.data import normalize_update_fields
@@ -1174,6 +1177,7 @@ class Device(
         if self.rack and self.rack.location:
             self.location = self.rack.location
 
+        update_fields = normalize_update_fields(kwargs)
         super().save(*args, **kwargs)
 
         # If this is a new Device, instantiate all the related components per the DeviceType definition
@@ -1198,20 +1202,21 @@ class Device(
             update_interface_parents(self, self.device_type.interfacetemplates.all())
             update_interface_bridges(self, self.device_type.interfacetemplates.all())
 
-        # Update Site and Rack assignment for any child Devices
-        using = self._state.db
-        devices = Device.objects.using(using).filter(parent_bay__device=self)
-        for device in devices:
-            device.snapshot()
-            device.site = self.site
-            device.rack = self.rack
-            device.location = self.location
-            # Prevent recreation of concurrently deleted child devices without aborting this save
-            try:
-                with transaction.atomic(using=using):
-                    device.save(using=using, force_update=True)
-            except Device.NotUpdated:
-                continue
+        # Update Site and Rack assignment for any child Devices (unless this save leaves them unchanged)
+        inherited = {'site', 'site_id', 'rack', 'rack_id', 'location', 'location_id'}
+        if update_fields is None or inherited & update_fields:
+            using = self._state.db
+            for device in Device.objects.using(using).filter(parent_bay__device=self):
+                device.snapshot()
+                device.site = self.site
+                device.rack = self.rack
+                device.location = self.location
+                # Prevent recreation of concurrently deleted child devices without aborting this save
+                try:
+                    with transaction.atomic(using=using):
+                        device.save(using=using, force_update=True)
+                except Device.NotUpdated:
+                    continue
 
     @property
     def label(self):
@@ -1360,6 +1365,38 @@ class VirtualChassis(PrimaryModel):
                 )
             })
 
+    def save(self, *args, **kwargs):
+        # A master designated on create is assigned to the virtual chassis once it exists, then designated as
+        # master in a change of its own, so that each recorded change is valid (and reversible) by itself.
+        master = None
+        if self._state.adding and self.master_id:
+            master, self.master = self.master, None
+
+        if master is None:
+            return super().save(*args, **kwargs)
+
+        using = kwargs.get('using') or router.db_for_write(self.__class__, instance=self)
+        try:
+            with transaction.atomic(using=using):
+                super().save(*args, **kwargs)
+
+                member = Device.objects.using(using).get(pk=master.pk)
+                member.snapshot()
+                member.virtual_chassis = self
+                member.vc_position = 1
+                member.save(using=using)
+
+                self.snapshot()
+                self.master = master
+                super().save(using=using, update_fields=['master', 'last_updated'])
+                self.__dict__.pop('_prechange_snapshot', None)
+        except Exception:
+            # The creation was rolled back, so the virtual chassis is unsaved again
+            self.pk = None
+            self._state.adding = True
+            self.master = master
+            raise
+
     def delete(self, *args, **kwargs):
         # Check for LAG interfaces split across member chassis
         interfaces = Interface.objects.filter(
@@ -1377,19 +1414,35 @@ class VirtualChassis(PrimaryModel):
                 set(interfaces),
             )
 
-        # Core's pre_delete handler detaches each member (clearing virtual_chassis) and records that change. Clear the
-        # now-meaningless position and priority afterwards, as a second change which is valid on its own.
+        # Release the master, then detach each member, each as a recorded change which is valid on its own and
+        # precedes the deletion: replayed in reverse, the virtual chassis is restored before its members rejoin it.
         using = kwargs.get('using') or router.db_for_write(self.__class__, instance=self)
-        member_ids = list(self.members.values_list('pk', flat=True))
-        with transaction.atomic(using=using):
-            ret = super().delete(*args, **kwargs)
-            for device in Device.objects.using(using).filter(pk__in=member_ids):
-                device.snapshot()
-                device.vc_position = None
-                device.vc_priority = None
-                device.save(using=using)
-
-        return ret
+        master = self.master
+        try:
+            with transaction.atomic(using=using):
+                # Deletion protection rules must see the virtual chassis while it still has its master and members
+                run_protection_rules(self)
+                self._pre_release_state = copy.copy(self)
+                if self.master_id:
+                    self.snapshot()
+                    self.master = None
+                    super().save(using=using, update_fields=release_update_fields(self, ['master']))
+                    self.__dict__.pop('_prechange_snapshot', None)
+                for device in Device.objects.using(using).filter(virtual_chassis=self.pk):
+                    device.snapshot()
+                    device.virtual_chassis = None
+                    device.vc_position = None
+                    device.vc_priority = None
+                    device.save(using=using)
+
+                return super().delete(*args, **kwargs)
+        except Exception:
+            # The deletion was rolled back, so the virtual chassis still has its master
+            self.master = master
+            raise
+        finally:
+            # The copy must not outlive this deletion on an instance which is reused
+            self.__dict__.pop('_pre_release_state', None)
 
 
 class VirtualDeviceContext(PrimaryModel):
@@ -1568,3 +1621,25 @@ class MACAddress(PrimaryModel):
                     raise ValidationError(
                         _("Cannot reassign MAC Address while it is designated as the primary MAC for an object")
                     )
+
+    @classmethod
+    def clear_cached_references(cls, instances, collector):
+        # Called by CustomCollector ahead of the DELETE, so each primary MAC is released before it is deleted
+        pks = {instance.pk for instance in instances}
+        # Resolve (and cache) whether each is primary while it still is, for its deletion's rules and event
+        for instance in instances:
+            instance.is_primary
+        for model in (apps.get_model('dcim', 'Interface'), apps.get_model('virtualization', 'VMInterface')):
+            for interface in model.objects.using(collector.using).filter(primary_mac_address__in=pks):
+                interface.snapshot()
+                interface.primary_mac_address = None
+                # Prevent recreation of concurrently deleted interfaces without aborting the deletion transaction
+                try:
+                    with transaction.atomic(using=collector.using):
+                        interface.save(
+                            using=collector.using,
+                            update_fields=release_update_fields(interface, ['primary_mac_address']),
+                        )
+                except model.NotUpdated:
+                    continue
+                collector.update_collected(interface, ['primary_mac_address'])

+ 84 - 86
netbox/dcim/signals.py

@@ -2,10 +2,11 @@ import logging
 
 from django.contrib.contenttypes.models import ContentType
 from django.db import transaction
-from django.db.models.signals import post_delete, post_save, pre_save
+from django.db.models.signals import post_delete, post_save, pre_delete, pre_save
 from django.dispatch import receiver
 
 from dcim.choices import CableEndChoices, LinkStatusChoices
+from netbox.models.deletion import release_update_fields
 from netbox.search.backends import search_backend
 from utilities.querysets import chunked_update
 from virtualization.models import VMInterface
@@ -18,6 +19,7 @@ from .models import (
     FrontPort,
     Interface,
     Location,
+    MACAddress,
     PathEndpoint,
     PortMapping,
     PowerPanel,
@@ -228,19 +230,6 @@ def handle_rack_site_change(instance, created, raw=False, using=None, update_fie
 # Virtual chassis
 #
 
-@receiver(post_save, sender=VirtualChassis)
-def assign_virtualchassis_master(instance, created, **kwargs):
-    """
-    When a VirtualChassis is created, automatically assign its master device (if any) to the VC.
-    """
-    if created and instance.master:
-        master = Device.objects.get(pk=instance.master.pk)
-        master.snapshot()
-        master.virtual_chassis = instance
-        master.vc_position = 1
-        master.save()
-
-
 @receiver(post_save, sender=VirtualChassis)
 def update_virtualchassis_member_search_cache(instance, created, raw=False, update_fields=None, **kwargs):
     """
@@ -326,74 +315,72 @@ def update_passthrough_port_paths(instance, update_fields=None, **kwargs):
         cablepath.retrace()
 
 
-@receiver(post_delete, sender=CableTermination)
-def nullify_connected_endpoints(instance, using, **kwargs):
+@receiver(pre_delete, sender=CableTermination)
+def record_cable_disconnect(instance, using, **kwargs):
     """
-    Disassociate the Cable from the termination object, and retrace any affected CablePaths.
+    When a Cable is deleted, clear it from the object each of its terminations attaches to, recording the change.
     """
-    model = instance.termination_type.model_class()
-
     # Deleting a Cable deletes its terminations in bulk, bypassing CableTermination.delete() and the
     # change-logged clear it performs on the terminating object; do the same here so the disconnect is
-    # recorded. `cable` is a SET_NULL FK which the deletion collector has already nulled by now, so the
-    # pre-delete values are restored before snapshotting, or the record would show no change. They are
-    # restored field by field rather than via set_cable_termination(), whose Interface override would
-    # propagate the cable back onto the channel subinterfaces we are about to clear.
-    termination = None
-    if Cable._is_being_deleted(instance.cable_id):
-        # The change record serializes the object twice (before and after), and ComponentModel.save()
-        # re-caches its denormalized references off the parent device: fetch both up front so neither
-        # costs a round trip per terminating object. Both the read and the save below use the alias the
-        # deletion ran on, so routing can't return a stale row or miss the object entirely.
-        queryset = model.objects.using(using).filter(pk=instance.termination_id).prefetch_related('tags')
-        if hasattr(model, 'device'):
-            queryset = queryset.select_related('device__site', 'device__location', 'device__rack')
-        termination = queryset.first()
-
-    if termination is not None:
-        termination.cable_id = instance.cable_id
-        termination.cable_end = instance.cable_end
-        termination.cable_connector = instance.connector
-        termination.cable_positions = instance.positions
-        termination.snapshot()
-        # clear_cable_termination() also clears the mirrored attributes on any channel subinterfaces
-        termination.clear_cable_termination(instance)
-        update_fields = ['cable', 'cable_end', 'cable_connector', 'cable_positions', 'last_updated']
-
-        # retrace_cable_paths() tears down the originating path once the Cable itself is deleted, clearing
-        # _path outside the changelog. Clear it here so the recorded state doesn't outlive the path.
-        if isinstance(termination, PathEndpoint):
-            termination._path = None
-            update_fields.append('_path')
-
-        # A narrow write: this row was read mid-cascade, and its full save() would pull in unrelated work
-        termination.save(using=using, update_fields=update_fields)
-    else:
-        # Already recorded by CableTermination.delete(), or the terminating object is going away too.
-        model.objects.filter(pk=instance.termination_id).update(
-            cable=None,
-            cable_end=None,
-            cable_connector=None,
-            cable_positions=None,
-        )
+    # recorded. This runs ahead of the deletion so that the disconnect precedes the Cable's own change record:
+    # replayed in reverse, the Cable is then restored before the terminating object is pointed back at it.
+    if not Cable._is_being_deleted(instance.cable_id):
+        return
+    model = instance.termination_type.model_class()
 
-        # If the removed termination was a channelized interface, also clear the cable attributes mirrored onto
-        # its channel subinterfaces. This must happen before the retrace below so that each channel's (now dead)
-        # path is torn down rather than rebuilt from a stale cable reference. These writes are deliberately not
-        # change-logged, matching propagate_channel_cables(), which doesn't log them when it sets them either.
-        # A subinterface saved through a change-logged path while connected does record its mirrored cable
-        # fields, so its disconnect goes unlogged here; that gap predates this receiver and is untouched by it.
-        if model is Interface:
-            Interface.objects.filter(parent_id=instance.termination_id, channel_id__isnull=False).update(
-                cable=None, cable_end='', cable_connector=None, cable_positions=None
-            )
+    # The change record serializes the object twice (before and after), and ComponentModel.save()
+    # re-caches its denormalized references off the parent device: fetch both up front so neither
+    # costs a round trip per terminating object. Both the read and the save below use the alias the
+    # deletion runs on, so routing can't return a stale row or miss the object entirely.
+    queryset = model.objects.using(using).filter(pk=instance.termination_id).prefetch_related('tags')
+    if hasattr(model, 'device'):
+        queryset = queryset.select_related('device__site', 'device__location', 'device__rack')
+    if (termination := queryset.first()) is None:
+        return
+
+    termination.snapshot()
+    # clear_cable_termination() also clears the mirrored attributes on any channel subinterfaces
+    termination.clear_cable_termination(instance)
+    update_fields = ['cable', 'cable_end', 'cable_connector', 'cable_positions', 'last_updated']
+
+    # retrace_cable_paths() tears down the originating path once the Cable itself is deleted, clearing
+    # _path outside the changelog. Clear it here so the recorded state doesn't outlive the path.
+    if isinstance(termination, PathEndpoint):
+        termination._path = None
+        update_fields.append('_path')
 
-    # If the parent Cable is being deleted in this same operation, skip the
-    # per-termination retrace; retrace_cable_paths() will retrace each affected
-    # path once after the Cable is deleted.
+    # A narrow write: this row is read mid-cascade, and its full save() would pull in unrelated work
+    termination.save(using=using, update_fields=update_fields)
+
+
+@receiver(post_delete, sender=CableTermination)
+def nullify_connected_endpoints(instance, using, **kwargs):
+    """
+    Disassociate the Cable from the termination object, and retrace any affected CablePaths.
+    """
+    # If the parent Cable is being deleted in this same operation, record_cable_disconnect() has already
+    # cleared the terminating object, and retrace_cable_paths() will retrace each affected path once after
+    # the Cable is deleted.
     if Cable._is_being_deleted(instance.cable_id):
         return
 
+    model = instance.termination_type.model_class()
+
+    # Already recorded by CableTermination.delete(), or the terminating object is going away too.
+    model.objects.filter(pk=instance.termination_id).update(
+        cable=None,
+        cable_end=None,
+        cable_connector=None,
+        cable_positions=None,
+    )
+
+    # Also clear the cable attributes mirrored onto a channelized interface's subinterfaces, before the
+    # retrace below. Not change-logged, matching propagate_channel_cables().
+    if model is Interface:
+        Interface.objects.filter(parent_id=instance.termination_id, channel_id__isnull=False).update(
+            cable=None, cable_end='', cable_connector=None, cable_positions=None
+        )
+
     for cablepath in CablePath.objects.filter(_nodes__contains=instance.cable):
         # Remove the deleted CableTermination if it's one of the path's originating nodes
         if instance.termination in cablepath.origins:
@@ -498,18 +485,29 @@ def cleanup_channel_subinterface_paths(instance, **kwargs):
             rebuild_cable_paths(parent.cable)
 
 
-@receiver(post_save, sender=Interface)
-@receiver(post_save, sender=VMInterface)
-def update_mac_address_interface(instance, created, raw, **kwargs):
+#
+# MAC addresses
+#
+
+@receiver(pre_delete, sender=MACAddress)
+def clear_primary_mac_address(instance, using, origin=None, **kwargs):
     """
-    When creating a new Interface or VMInterface, check whether a MACAddress has been designated as its primary. If so,
-    assign the MACAddress to the interface.
+    When a MACAddress is deleted, trigger save() on any interface for which it was the primary MAC address.
+    MACAddress.clear_cached_references() has already done so unless the deletion was made through a queryset.
     """
-    if created and not raw and instance.primary_mac_address:
-        # Keep any snapshot the caller took before making unsaved changes to the MAC address
-        if not hasattr(instance.primary_mac_address, '_prechange_snapshot'):
-            instance.primary_mac_address.snapshot()
-        instance.primary_mac_address.assigned_object = instance
-        instance.primary_mac_address.save()
-        # Discard the snapshot so that a later save of the MAC address takes a fresh one
-        instance.primary_mac_address.__dict__.pop('_prechange_snapshot', None)
+    # A MAC address deleted along with its interface needs no release, and the interface's deletion may already
+    # have been recorded
+    if getattr(origin, 'model', type(origin)) is not MACAddress:
+        return
+    for model in (Interface, VMInterface):
+        if interface := model.objects.using(using).filter(primary_mac_address=instance.pk).first():
+            interface.snapshot()
+            interface.primary_mac_address = None
+            # Prevent recreation of a concurrently deleted interface without aborting the deletion transaction
+            try:
+                with transaction.atomic(using=using):
+                    interface.save(
+                        using=using, update_fields=release_update_fields(interface, ['primary_mac_address'])
+                    )
+            except model.NotUpdated:
+                continue

+ 2 - 12
netbox/dcim/tests/test_signals.py

@@ -599,8 +599,7 @@ class DeviceComponentScopeTriggerTestCase(TestCase):
 
 class VirtualChassisMasterSignalTestCase(TestCase):
     """
-    Verify dcim.signals.assign_virtualchassis_master links the master device back to a
-    newly-created VirtualChassis.
+    Verify VirtualChassis.save() links the master device back to a newly-created VirtualChassis.
     """
 
     @classmethod
@@ -907,8 +906,7 @@ class CableSignalTestCase(TestCase):
 
 class MACAddressInterfaceSignalTestCase(TestCase):
     """
-    Verify dcim.signals.update_mac_address_interface assigns a designated primary MAC to
-    the newly-created Interface or VMInterface.
+    Verify BaseInterface.save() assigns a designated primary MAC to the newly-created Interface or VMInterface.
     """
 
     @classmethod
@@ -1063,14 +1061,6 @@ class CableSignalDirectHandlerTestCase(SimpleTestCase):
             cablepath_model.objects.filter.return_value, is_active=False
         )
 
-    def test_update_mac_address_interface_raw_import_is_a_no_op(self):
-        primary_mac = SimpleNamespace(save=MagicMock())
-        interface = SimpleNamespace(primary_mac_address=primary_mac)
-
-        signals.update_mac_address_interface(instance=interface, created=True, raw=True)
-
-        primary_mac.save.assert_not_called()
-
 
 class CableTerminationDenormalizationTriggerTestCase(TestCase):
     """

+ 22 - 23
netbox/dcim/tests/test_views.py

@@ -6172,31 +6172,30 @@ class VirtualChassisTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             self.assertIsNone(member.vc_position)
             self.assertIsNone(member.vc_priority)
 
-            # Each member is detached and then cleared in two changes, each with prechange data and valid on
-            # its own (a virtual chassis is never recorded without a position)
-            changes = list(self._get_member_changes(member))
-            self.assertEqual(len(changes), 2)
-            detach, clear = changes
-            self.assertEqual(detach.action, ObjectChangeActionChoices.ACTION_UPDATE)
-            self.assertEqual(detach.prechange_data['virtual_chassis'], vc.pk)
-            self.assertIsNotNone(detach.prechange_data['vc_position'])
-            self.assertIsNone(detach.postchange_data['virtual_chassis'])
-            self.assertEqual(detach.postchange_data['vc_position'], detach.prechange_data['vc_position'])
-            self.assertEqual(clear.action, ObjectChangeActionChoices.ACTION_UPDATE)
-            self.assertIsNone(clear.prechange_data['virtual_chassis'])
-            self.assertEqual(clear.prechange_data['vc_position'], detach.postchange_data['vc_position'])
-            self.assertIsNone(clear.postchange_data['vc_position'])
-            self.assertIsNone(clear.postchange_data['vc_priority'])
-        self.assertEqual(self._get_member_changes(members[0]).first().prechange_data['vc_priority'], 10)
-
-        # The VC deletion is recorded once, before its (former) master is detached
-        vc_change = ObjectChange.objects.get(
+            # Each member is detached and cleared in a single change which is valid on its own
+            change = self._get_member_changes(member).get()
+            self.assertEqual(change.action, ObjectChangeActionChoices.ACTION_UPDATE)
+            self.assertEqual(change.prechange_data['virtual_chassis'], vc.pk)
+            self.assertIsNotNone(change.prechange_data['vc_position'])
+            self.assertIsNone(change.postchange_data['virtual_chassis'])
+            self.assertIsNone(change.postchange_data['vc_position'])
+            self.assertIsNone(change.postchange_data['vc_priority'])
+        self.assertEqual(self._get_member_changes(members[0]).get().prechange_data['vc_priority'], 10)
+
+        # The master is released, then the members detached, then the VC deleted, so that reversing the changes
+        # restores the VC before its members rejoin it, and its master only once it is a member again
+        release, deletion = ObjectChange.objects.filter(
             changed_object_type=ContentType.objects.get_for_model(VirtualChassis),
             changed_object_id=vc.pk,
-        )
-        self.assertEqual(vc_change.action, ObjectChangeActionChoices.ACTION_DELETE)
-        self.assertEqual(vc_change.prechange_data['master'], members[0].pk)
-        self.assertLess(vc_change.pk, self._get_member_changes(members[0]).first().pk)
+        ).order_by('pk')
+        self.assertEqual(release.action, ObjectChangeActionChoices.ACTION_UPDATE)
+        self.assertEqual(release.prechange_data['master'], members[0].pk)
+        self.assertIsNone(release.postchange_data['master'])
+        self.assertEqual(deletion.action, ObjectChangeActionChoices.ACTION_DELETE)
+        self.assertIsNone(deletion.prechange_data['master'])
+        member_change_pks = [self._get_member_changes(member).get().pk for member in members]
+        self.assertLess(release.pk, min(member_change_pks))
+        self.assertGreater(deletion.pk, max(member_change_pks))
 
     def _add_constrained_permission(self, model, actions, constraints):
         obj_perm = ObjectPermission(name='Test permission', actions=actions, constraints=constraints)

+ 2 - 1
netbox/extras/events.py

@@ -160,7 +160,8 @@ def enqueue_event(queue, instance, request, event_type, object_change_id=None):
     # For delete events, eagerly serialize the payload before the row is gone.
     # This covers both first-time enqueues and coalesced update→delete promotions.
     if event_type == OBJECT_DELETED:
-        queue[key].freeze_data(instance)
+        # Describe the object as it was before any references were released ahead of its deletion
+        queue[key].freeze_data(getattr(instance, '_pre_release_state', None) or instance)
 
 
 def process_event_rules(event_rules, object_type, event):

+ 31 - 2
netbox/ipam/models/ip.py

@@ -1,10 +1,11 @@
 import netaddr
+from django.apps import apps
 from django.contrib.contenttypes.fields import GenericForeignKey
 from django.contrib.contenttypes.models import ContentType
 from django.contrib.postgres.indexes import GistIndex
 from django.core.exceptions import ValidationError
-from django.db import models
-from django.db.models import F
+from django.db import models, transaction
+from django.db.models import F, Q
 from django.db.models.functions import Cast
 from django.utils.functional import cached_property
 from django.utils.translation import gettext_lazy as _
@@ -19,6 +20,7 @@ from ipam.querysets import IPRangeQuerySet, PrefixQuerySet
 from ipam.validators import DNSValidator
 from netbox.config import get_config
 from netbox.models import OrganizationalModel, PrimaryModel
+from netbox.models.deletion import release_update_fields
 from netbox.models.features import ContactsMixin
 
 __all__ = (
@@ -1184,6 +1186,33 @@ class IPAddress(ContactsMixin, PrimaryModel):
 
         super().save(*args, **kwargs)
 
+    @classmethod
+    def clear_cached_references(cls, instances, collector):
+        # Called by CustomCollector ahead of the DELETE, so each primary/OOB IP is released before it is deleted
+        pks = {instance.pk for instance in instances}
+        for model, field_names in (
+            (apps.get_model('dcim', 'Device'), ('primary_ip4', 'primary_ip6', 'oob_ip')),
+            (apps.get_model('dcim', 'VirtualDeviceContext'), ('primary_ip4', 'primary_ip6')),
+            (apps.get_model('virtualization', 'VirtualMachine'), ('primary_ip4', 'primary_ip6')),
+        ):
+            query = Q()
+            for field_name in field_names:
+                query |= Q(**{f'{field_name}__in': pks})
+            for parent in model.objects.using(collector.using).filter(query):
+                parent.snapshot()
+                for field_name in field_names:
+                    if getattr(parent, f'{field_name}_id') in pks:
+                        setattr(parent, field_name, None)
+                # Prevent recreation of concurrently deleted objects without aborting the deletion transaction
+                try:
+                    with transaction.atomic(using=collector.using):
+                        parent.save(
+                            using=collector.using, update_fields=release_update_fields(parent, field_names)
+                        )
+                except model.NotUpdated:
+                    continue
+                collector.update_collected(parent, field_names)
+
     def clone(self):
         attrs = super().clone()
 

+ 2 - 0
netbox/ipam/signals.py

@@ -57,6 +57,7 @@ def handle_prefix_deleted(instance, using=None, **kwargs):
 def clear_primary_ip(instance, using=None, **kwargs):
     """
     When an IPAddress is deleted, trigger save() on any Devices/VirtualMachines for which it was a primary IP.
+    IPAddress.clear_cached_references() has already done so unless the deletion was made through a queryset.
     """
     field_name = f'primary_ip{instance.family}'
     for model in (Device, VirtualMachine):
@@ -75,6 +76,7 @@ def clear_primary_ip(instance, using=None, **kwargs):
 def clear_oob_ip(instance, using=None, **kwargs):
     """
     When an IPAddress is deleted, trigger save() on any Devices for which it was a OOB IP.
+    IPAddress.clear_cached_references() has already done so unless the deletion was made through a queryset.
     """
     if device := Device.objects.using(using).filter(oob_ip=instance).first():
         device.snapshot()

+ 83 - 5
netbox/netbox/models/deletion.py

@@ -1,6 +1,8 @@
+import copy
 import logging
 
 from django.contrib.contenttypes.fields import GenericRelation
+from django.core.exceptions import FieldDoesNotExist
 from django.db import router, transaction
 from django.db.models.deletion import CASCADE, Collector
 from django.utils.translation import gettext as _
@@ -8,6 +10,41 @@ from django.utils.translation import gettext as _
 logger = logging.getLogger("netbox.models.deletion")
 
 
+def run_protection_rules(instance):
+    """
+    Run any deletion protection rules for an object ahead of releasing the references to it, so that the rules see
+    it while it is still referenced. (They run again, as for any object, when its deletion is recorded.)
+    """
+    # TODO: Fix circular imports
+    from django.core.exceptions import ValidationError
+
+    from extras.utils import run_validators
+    from netbox.config import get_config
+    from utilities.data import get_config_value_ci
+    from utilities.exceptions import AbortRequest
+
+    validators = get_config_value_ci(get_config().PROTECTION_RULES, instance._meta.label_lower, default=[])
+    try:
+        run_validators(instance, validators)
+    except ValidationError as e:
+        raise AbortRequest(
+            _("Deletion is prevented by a protection rule: {message}").format(message=e)
+        )
+
+
+def release_update_fields(instance, field_names):
+    """
+    Return the update_fields for saving an object whose references were released. custom_field_data is included
+    when save() will populate a default, which the change log records.
+    """
+    from extras.models import CustomField
+
+    update_fields = [*field_names, 'last_updated']
+    if CustomField.objects.get_defaults_for_model(instance).keys() - instance.custom_field_data.keys():
+        update_fields.append('custom_field_data')
+    return update_fields
+
+
 class CountOnly:
     """
     A stand-in for a list of dependent instances that reports a count without holding any
@@ -126,18 +163,59 @@ class CustomCollector(Collector):
                         # Add the model that the generic relation points to as a dependency
                         self.add_dependency(field.related_model, instance, reverse_dependency=True)
 
+    def update_collected(self, obj, field_names):
+        """
+        Copy the given fields from a saved copy of an object onto the instance collected for deletion (if any), so
+        that the change recorded for its deletion reflects them.
+        """
+        if (collected := self._collected_by_pk.get(type(obj))) is None:
+            collected = self._collected_by_pk[type(obj)] = {
+                instance.pk: instance for instance in self.data.get(type(obj), ())
+            }
+        if (instance := collected.get(obj.pk)) is None:
+            return
+        # Deletion protection rules must see the object as it was before its references were released
+        if not hasattr(instance, '_pre_release_state'):
+            instance._pre_release_state = copy.copy(instance)
+        # The save which released the fields may also have set these
+        for field_name in (*field_names, 'last_updated', 'custom_field_data'):
+            try:
+                attname = obj._meta.get_field(field_name).attname
+            except FieldDoesNotExist:
+                continue
+            setattr(instance, attname, getattr(obj, attname))
+        if hasattr(instance, '_prechange_snapshot'):
+            instance.snapshot()
+
     def delete(self):
         # Clear any cached references to the objects being deleted first, so that each clear is
         # recorded and precedes the DELETE. Django nulls a SET_NULL column with a bulk UPDATE,
         # which emits no post_save and so is never change-logged. Models opt in by defining
         # clear_cached_references(); it covers cascaded objects as well as directly deleted ones,
         # but only on this collector -- a queryset delete uses Django's and bypasses it.
+        self._collected_by_pk = {}
         with transaction.atomic(using=self.using, savepoint=False):
-            for model, instances in self.data.items():
-                if clear_references := getattr(model, 'clear_cached_references', None):
-                    clear_references(instances, self)
-
-            return super().delete()
+            try:
+                for model, instances in self.data.items():
+                    if clear_references := getattr(model, 'clear_cached_references', None):
+                        for instance in instances:
+                            run_protection_rules(instance)
+                        clear_references(instances, self)
+
+                result = super().delete()
+            except Exception:
+                # The releases were rolled back, so the collected instances hold their references again
+                for collected in self._collected_by_pk.values():
+                    for instance in collected.values():
+                        if (state := instance.__dict__.pop('_pre_release_state', None)) is not None:
+                            instance.__dict__.update({k: v for k, v in state.__dict__.items() if k != '_state'})
+                raise
+
+        # The copies described the deleted objects, and must not outlive them on instances which are reused
+        for collected in self._collected_by_pk.values():
+            for instance in collected.values():
+                instance.__dict__.pop('_pre_release_state', None)
+        return result
 
 
 class DeleteMixin:

+ 4 - 2
netbox/utilities/testing/api.py

@@ -822,7 +822,8 @@ class APIViewTestCases:
             if hasattr(self.model, 'to_objectchange'):
                 objectchange = ObjectChange.objects.get(
                     changed_object_type=ContentType.objects.get_for_model(instance),
-                    changed_object_id=instance.pk
+                    changed_object_id=instance.pk,
+                    action=ObjectChangeActionChoices.ACTION_DELETE,
                 )
                 self.assertObjectChange(objectchange, action=ObjectChangeActionChoices.ACTION_DELETE,
                     message=data['changelog_message'])
@@ -861,7 +862,8 @@ class APIViewTestCases:
             if issubclass(self.model, ChangeLoggingMixin):
                 objectchanges = ObjectChange.objects.filter(
                     changed_object_type=ContentType.objects.get_for_model(self.model),
-                    changed_object_id__in=id_list
+                    changed_object_id__in=id_list,
+                    action=ObjectChangeActionChoices.ACTION_DELETE,
                 )
                 self.assertEqual(len(objectchanges), len(data))
                 for oc in objectchanges:

+ 4 - 2
netbox/utilities/testing/views.py

@@ -392,7 +392,8 @@ class ViewTestCases:
             if issubclass(self.model, ChangeLoggingMixin):
                 objectchanges = ObjectChange.objects.filter(
                     changed_object_type=ContentType.objects.get_for_model(instance),
-                    changed_object_id=instance.pk
+                    changed_object_id=instance.pk,
+                    action=ObjectChangeActionChoices.ACTION_DELETE,
                 )
                 self.assertEqual(len(objectchanges), 1)
                 self.assertObjectChange(objectchanges[0], action=ObjectChangeActionChoices.ACTION_DELETE,
@@ -1080,7 +1081,8 @@ class ViewTestCases:
             if issubclass(self.model, ChangeLoggingMixin):
                 objectchanges = ObjectChange.objects.filter(
                     changed_object_type=ContentType.objects.get_for_model(self.model),
-                    changed_object_id__in=pk_list
+                    changed_object_id__in=pk_list,
+                    action=ObjectChangeActionChoices.ACTION_DELETE,
                 )
                 self.assertEqual(len(objectchanges), len(pk_list))
                 for oc in objectchanges: