[bug] Repeated device_group_changed signal on subsequent saves of the same device instance

Abierto Apto para principiantes
#1,563 2 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

  • #1564 de @RK-NerdyBirdy — cerrado sin fusionar
  • #1568 de @biggdawg320 — cerrado sin fusionar

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
72/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
django, python
Área
backend

Línea de trabajo

Empieza en openwisp_controller/config/base/device.py en _check_group_id_changed(), que emite la señal de cambio de grupo pero nunca actualiza _initial_group_id, y compáralo con _check_management_ip_changed(), que sí actualiza su línea base. Añade una prueba de regresión que mantenga una única instancia de dispositivo a través de A a B, un guardado sin cambios y luego B a C, y verifica el número de señales y old_group_id. Está terminado cuando solo las transiciones reales emiten una vez y cada una informa del grupo inmediatamente anterior.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug

Describe the bug

The device_group_changed signal is emitted repeatedly when saving the same device model instance, even when its group has not changed since the previous save.

The issue originates in AbstractDevice._check_group_id_changed(). The method compares the current group_id against _initial_group_id and emits the signal when they differ, but does not update _initial_group_id after detecting the change.

Consequently, the original group ID remains the comparison baseline for subsequent saves of the same Python model instance. This results in duplicate signal emissions and an incorrect old_group_id being passed to signal receivers during subsequent genuine group changes.

This is particularly relevant because the signal is used by the configuration application to trigger downstream operations, including device-template reconciliation. Repeated emissions for a single group transition may therefore schedule unnecessary downstream work.

Steps to Reproduce

  1. Retrieve an existing device belonging to Group A from the database.
  2. Keep the retrieved device instance in memory throughout the following operations. Do not refresh or reload it.
  3. Change its group from Group A to Group B and save the instance.
  4. Save the same instance again without making any additional changes to its group.
  5. Change its group from Group B to Group C and save the same instance again.
  6. Observe the number of device_group_changed signal emissions and inspect the old_group_id and group_id arguments received by the signal handlers.

Actual Behavior

The signal is emitted on every subsequent save because _initial_group_id continues to hold the original Group A ID.

The reproduced results were:

Save operation Signals emitted by this save Cumulative signal count Expected cumulative count
Group A → Group B 1 1 1
Save unchanged Group B 1 2 1
Group B → Group C 1 3 2

Additionally, during the final Group B → Group C transition, the signal incorrectly reports Group A as old_group_id, instead of the immediately preceding group, Group B.

Expected Behavior

The device_group_changed signal should be emitted only when the device's group actually changes.

For the reproduction sequence above, the expected behavior is:

Save operation Expected signal emissions Expected old_group_id Expected group_id
Group A → Group B 1 Group A Group B
Save unchanged Group B 0 — —
Group B → Group C 1 Group B Group C

Specifically:

  • Saving an unchanged device instance should not emit device_group_changed.
  • Each genuine group transition should emit the signal exactly once.
  • The signal should report the immediately previous group as old_group_id.
  • Existing behavior for device creation and legitimate group changes should remain unaffected.

Technical Investigation

The behavior appears to originate in:

openwisp_controller/config/base/device.py

The relevant methods are:

  • AbstractDevice.__init__()
  • _set_initial_values_for_changed_checked_fields()
  • _check_changed_fields()
  • _check_group_id_changed()
  • _check_management_ip_changed()

During initialization, _initial_group_id is populated through _set_initial_values_for_changed_checked_fields().

On subsequent saves, _check_changed_fields() invokes _check_group_id_changed(). When the current group_id differs from _initial_group_id, the method calls _send_device_group_changed_signal().

However, the tracked baseline is not advanced after the signal is emitted.

A comparable implementation exists in _check_management_ip_changed(), which updates _initial_management_ip after detecting a change. The group-change implementation does not currently perform the equivalent baseline update.

Deferred-field handling was also examined and does not appear to explain the behavior for an ordinarily loaded device with a non-deferred group baseline.

Reproduction and Test Results

The issue was reproduced using executable Django tests against commit 87585e4, with:

  • Python 3.14.4
  • Django 6.1.3
  • TransactionTestCase
  • Actual signal receivers
  • Committed database saves

The regression test retained the same Python model instance throughout the sequence and verified the persisted group after each operation without refreshing or replacing the instance.

Additional verification:

  • 62 existing targeted tests passed, covering device, device-group, and related admin tests.
  • 47 existing sample-model tests passed with SAMPLE_APP=1.
  • The new group-change regression failed in both configurations, reproducing the duplicate signal emissions and stale old_group_id.
  • A management-IP control test passed in both configurations, confirming the expected cumulative signal counts of 1, 1, 2 for the equivalent change/save sequence.

The existing group-signal tests cover individual group changes and device creation, but do not appear to cover repeated saves of the same model instance after a group transition.

Suggested Resolution

The group-change tracking logic should maintain an accurate baseline after a genuine group change, so subsequent saves compare against the most recently recorded group rather than the original group.

Regression coverage should verify that:

  1. A genuine group change emits device_group_changed exactly once.
  2. Saving the same instance again without changing its group does not emit another signal.
  3. A second genuine group change on the same instance emits exactly one additional signal.
  4. The old_group_id and group_id arguments correctly represent each individual transition.
  5. Existing device creation and group-change behavior remains unaffected.

The implementation approach can be determined based on the project's existing model lifecycle and change-tracking conventions.

Additional Information

This issue has been reproduced locally and investigated against the current implementation. No production source changes have been made as part of the investigation.

I would be happy to work on a focused fix and the associated regression tests if the maintainers agree that this is an appropriate issue to address.

Thank you for your time and for maintaining OpenWISP.

Lenguaje dominante
Python
Estrellas
800
Forks
354
Merge medio
1 d 8 h
PR fusionados (30 d)
15

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de openwisp/openwisp-controller

Todos los issues de openwisp/openwisp-controller

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.