kolibri icon indicating copy to clipboard operation
kolibri copied to clipboard

Add PicturePasswordCollisionOperation that resolves conflicts by reassigning the local record

Open LianaHarris360 opened this issue 6 months ago • 1 comments

❌ This issue is not open for contribution. Visit Contributing guidelines to learn about the contributing process and how to find suitable issues.

Overview

When two devices independently assign the same picture_password sequence to different learners and then sync, the incoming learner's FacilityUser record fails Morango deserialization due to a unique_together constraint violation on ("dataset", "picture_password").

The record never appears in kolibriauth_facilityuser and the Morango Store is left in an inconsistent state. A new PicturePasswordCollisionOperation is needed that detects these failures, resolves the collision by reassigning the local pre-existing FacilityUser's picture password, and retries deserialization so the incoming record lands cleanly.

Complexity: Medium Target branch: develop

Context

Context

Picture login is enabled for a facility when FacilityDataset.picture_password_settings is not null.

How the collision happens: Picture passwords are stored as a dot-separated string on FacilityUser.picture_password with a unique_together constraint on ("dataset", "picture_password"). When two devices independently assign the same sequence to different learners and then sync, Morango deserialization attempts to write both records to kolibriauth_facilityuser. The second write violates the constraint. Without targeted handling, the FacilityUser record never appears in the app database, and the Morango Store record is left with dirty_bit=True, a deserialization_exception of django.db.utils.IntegrityError, and possibly spurious DeletedModels or HardDeletedModels entries as artifacts of the failure.

The correct approach (modify the local record): The operation should find the local FacilityUser already in the database that holds the conflicting picture password and reassign that user to a new picture password via local_user.save(). The incoming Store record's serialized data stays untouched. After the local user is moved out of the way, _deserialize_from_store retries the incoming record, which now deserializes cleanly because the unique constraint no longer conflicts. When the client later pushes its reassigned local user back to the remote, it receives a normal update with no collision. Resolution happens once, on one device.

Sync operation pattern: The operation must inherit from ReceiverDeserializeOperation in kolibri/core/auth/sync_operations.py and be registered at low priority in kolibri/core/auth/kolibri_plugin.py. It calls super().handle(context) to let normal deserialization run first, then inspects what failed and corrects those records. Read kolibri/core/auth/sync_operations.py and docs/backend_architecture/facility_syncing/index.rst in full before implementing. Read the exam and lesson operations in kolibri/core/exams/kolibri_plugin.py as a contrast: those return False because they do not handle deserialization themselves. This operation is different because it calls super().handle() and must return a transfer_statuses constant, never False.

The Change

Create a new class PicturePasswordCollisionOperation in kolibri/core/auth/sync_operations.py that inherits from ReceiverDeserializeOperation. Register it in kolibri/core/auth/kolibri_plugin.py and with low priority so that it runs last in the deserialization stage's operation list, so normal deserialization has already run before this operation executes.

The handle method should do the following in order:

  1. Apply context guards. Assert that context.sync_session, context.transfer_session, context.filter, and context.is_receiver are all present/truthy, in exactly the same way ReceiverDeserializeOperation does. Do not invent a different guard.
  2. Call super().handle(context) to run normal deserialization. Capture the result.
  3. If the result is not transfer_statuses.COMPLETED, return it immediately. Do not interfere with error or pending states from normal deserialization.
  4. Query the Morango Store for incoming records that failed deserialization due to the collision. Filter by:
    • partition__startswith=dataset_id (obtained via get_dataset_id(context) from kolibri/core/auth/sync_event_hook_utils.py)
    • model_name=FacilityUser.morango_model_name
    • dirty_bit=True
    • deserialization_exception=_INTEGRITY_ERROR_EXCEPTION (which is "django.db.utils.IntegrityError")
    • last_transfer_session_id=context.transfer_session.id
  5. If the query returns no records, return transfer_statuses.COMPLETED.
  6. Extract the conflicting picture passwords from the incoming records. Loop through the broken stores, deserialize each store's JSON with FacilityUser.deserialize(json.loads(store.serialized), sync_filter=context.filter), and collect the picture_password values into a set.
  7. Query FacilityUser for local records holding those passwords. Use FacilityUser.objects.filter(dataset_id=dataset_id, picture_password__in=conflicting_passwords). These are the pre-existing local users whose passwords conflict with the incoming records. Querying the app model directly is correct because these users are already deserialized into the database. Do not scan Store records for this.
  8. If no local users are found, return transfer_statuses.COMPLETED. This handles the edge case where the collision was not caused by a local user.
  9. Build the available sequences pool. Check are_picture_passwords_exhausted(dataset_id). If not exhausted, compute get_all_valid_sequences(PICTURE_PASSWORD_SET) - get_assigned_sequences(facility) and shuffle. These utilities are in kolibri/core/auth/utils/picture_passwords.py.
  10. Reassign each local user's picture password. For each FacilityUser in the query results:
    • Set picture_password to available_sequences.pop() if available, else None
    • Call local_user.save() to persist the change to the database immediately
  11. Clear deserialization errors on the incoming broken Store records. Update them to set deserialization_error=None and deserialization_exception=None. This allows _deserialize_from_store to retry them.
  12. Clean up DeletedModels and HardDeletedModels for the broken store IDs. These are artifacts of the failed deserialization.
  13. Call _deserialize_from_store(context.sync_session.profile, filter=context.filter) to retry deserialization. The incoming records still have dirty_bit=True, so they will be processed. The local users' passwords have been changed in the database, so the unique constraint will not conflict.
  14. Return transfer_statuses.COMPLETED. Important: do not modify the incoming Store records' serialized field. The incoming records keep their original picture passwords. The dirty_bit on incoming records stays True so _deserialize_from_store processes them. The local users' Store records will be updated through the normal Morango serialization flow triggered by local_user.save().

Create unit tests in kolibri/core/auth/test/test_picture_password_sync_operation.py and an integration test in kolibri/core/auth/test/test_morango_integration.py. See the Testing section for specifics.

How to Get There

To exercise the operation manually during development:

  1. Run two Kolibri instances configured for peer sync.
  2. On both devices, create learners in the same facility with picture login enabled, such that two learners on different devices are assigned the same picture_password sequence.
  3. Sync the two devices (Device A initiates).
  4. After sync completes, on Device A query FacilityUser and confirm:
    • Both learners exist in kolibriauth_facilityuser
    • Device A's original local learner has a new picture password (it was reassigned)
    • The learner that arrived from Device B has its original picture password
  5. On Device B, confirm:
    • Both learners exist
    • Device B's local learner still has its original picture password (no collision occurred on Device B because Device A resolved the conflict during the pull and pushed back the reassigned record)
  6. Query the Morango Store for the affected records on both devices and confirm dirty_bit=False, deleted=False, and no DeletedModels or HardDeletedModels entries. To run the relevant tests:
pytest kolibri/core/auth/test/test_sync_operations.py
pytest kolibri/core/auth/test/test_morango_integration.py::PicturePasswordCollisionIntegrationTestCase

Out of Scope

  • Changes to _deserialize_from_store in Morango (it does not need modification)
  • UI changes for surfacing collision resolution to the user
  • Handling collisions between two incoming records (both from the remote, neither local)
  • Learners who deserialized successfully but arrived with picture_password=None because picture login was not active on the sending device at the time of creation
  • Assignment during new learner creation
  • Triggering bulk assignment when the facility setting is first enabled
  • Any frontend changes

Acceptance Criteria

General

  • [ ] A new PicturePasswordCollisionOperation class exists in kolibri/core/auth/sync_operations.py, inheriting from ReceiverDeserializeOperation with priority = -1
  • [ ] The operation is registered at low priority in kolibri/core/auth/kolibri_plugin.py
  • [ ] The operation applies the same context guards as ReceiverDeserializeOperation (receiver only, correct stage)
  • [ ] super().handle(context) is called first; the operation returns immediately for any result other than COMPLETED
  • [ ] The Store query filters by partition, model_name, dirty_bit, deserialization_exception, and last_transfer_session_id
  • [ ] The operation does not modify the incoming Store records' serialized field
  • [ ] The operation queries FacilityUser (the app model) to find local users holding conflicting passwords
  • [ ] The operation reassigns the local FacilityUser's picture_password via local_user.save()
  • [ ] After reassignment, the operation clears deserialization_error and deserialization_exception on the incoming broken Store records
  • [ ] The operation cleans up DeletedModels and HardDeletedModels for the incoming store IDs
  • [ ] _deserialize_from_store is called after the local users are reassigned, successfully deserializing the incoming records with their original passwords
  • [ ] The operation returns transfer_statuses.COMPLETED
  • [ ] If no broken stores are found, the operation returns transfer_statuses.COMPLETED without modifying anything
  • [ ] If no local users match the conflicting passwords, the operation returns transfer_statuses.COMPLETED without modifying anything
  • [ ] are_picture_passwords_exhausted() is called once before the loop; if exhausted, the local user's picture_password is set to None
  • [ ] Colliding learners are never left absent from kolibriauth_facilityuser

Testing

  • [ ] Unit tests in kolibri/core/auth/test/test_picture_password_sync_operation.py:
    • Test that when a collision is detected, the local FacilityUser is reassigned a new picture_password (not None, not the original value). The incoming Store's serialized field remains unchanged. The incoming Store has deserialization_error=None and deserialization_exception=None.
    • Test that DeletedModels and HardDeletedModels entries for the incoming store are removed after correction.
    • Test that when are_picture_passwords_exhausted() returns True, the local FacilityUser's picture_password is set to None.
    • Test that when no available sequences remain (empty set from get_all_valid_sequences), the local FacilityUser's picture_password is set to None.
    • Test that when no broken stores are found, the operation returns COMPLETED without modifying anything.
    • Test that when super().handle() returns something other than COMPLETED, the operation returns that result immediately without modifying any records.
    • Test that Store records with a different deserialization_exception (not IntegrityError) are not touched.
    • Test that Store records with dirty_bit=False are not touched.
    • Test that when no local FacilityUser matches the conflicting password (edge case), the operation returns COMPLETED without modifying anything.
  • [ ] Integration test PicturePasswordCollisionIntegrationTestCase in kolibri/core/auth/test/test_morango_integration.py:
    • Create a facility, a local FacilityUser with picture_password="1.2.3", serialize into Store, then create a remote Store record for a different user also with picture_password="1.2.3".
    • Run _deserialize_from_store to trigger the collision, confirm the remote store has dirty_bit=True and deserialization_exception=_INTEGRITY_ERROR_EXCEPTION.
    • Run the operation and confirm:
      • The local user has a new picture_password (not "1.2.3", not None).
      • The remote user exists in FacilityUser with its original picture_password == "1.2.3".
      • The remote Store has dirty_bit=False, deserialization_exception=None, deserialization_error=None, and no DeletedModels/HardDeletedModels entries.
    • Use TransactionTestCase because Morango's _begin_transaction uses transaction isolation incompatible with TestCase's database wrapping.

References

  • kolibri/core/auth/sync_operations.py -- where PicturePasswordCollisionOperation should be created; contains ReceiverDeserializeOperation (the parent class)
  • docs/backend_architecture/facility_syncing/index.rst -- operations pattern, stage structure, and transfer_statuses contract
  • kolibri/core/auth/kolibri_plugin.py -- where the operation must be registered at low priority
  • kolibri/core/auth/sync_event_hook_utils.py -- get_dataset_id(context) for scoping the Store query to the correct dataset
  • kolibri/core/auth/utils/picture_passwords.py
  • kolibri/core/auth/models.py

AI usage

🤖 This issue was written with AI assistance (Claude), under supervision, review and final edits by @LianaHarris360. The bilateral resolution bug was identified through iterative debugging with real device logs in a two-device sync setup. The issue description, acceptance criteria, and test specifications were drafted by Claude based on the debugging session context, then reviewed for accuracy. 🤖

LianaHarris360 avatar May 12 '26 17:05 LianaHarris360

Plan: Add PicturePasswordCollisionOperation to resolve unique_together constraint violations on picture_password during Morango deserialization when two devices independently assign the same picture password to different learners.

  • [ ] Write the failing unit test file
  • [ ] Implement PicturePasswordCollisionOperation in sync_operations.py
  • [ ] Register the operation in kolibri_plugin.py
  • [ ] Write the integration test
  • [ ] Lint and final check

status


@rtibblesbot's comments are generated by an LLM, and should be evaluated accordingly

How was this generated?
  • Implemented code following the pre-approved plan using test-driven development (red-green-refactor)
  • Ran the project's full test suite and linter before committing
  • For UI changes: captured live screenshots to verify rendering
  • For backend changes: verified with example API/CLI output

rtibblesbot avatar May 12 '26 18:05 rtibblesbot