Add PicturePasswordCollisionOperation that resolves conflicts by reassigning the local record
❌ 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:
- Apply context guards. Assert that
context.sync_session,context.transfer_session,context.filter, andcontext.is_receiverare all present/truthy, in exactly the same wayReceiverDeserializeOperationdoes. Do not invent a different guard. - Call
super().handle(context)to run normal deserialization. Capture the result. - If the result is not
transfer_statuses.COMPLETED, return it immediately. Do not interfere with error or pending states from normal deserialization. - Query the Morango Store for incoming records that failed deserialization due to the collision. Filter by:
partition__startswith=dataset_id(obtained viaget_dataset_id(context)fromkolibri/core/auth/sync_event_hook_utils.py)model_name=FacilityUser.morango_model_namedirty_bit=Truedeserialization_exception=_INTEGRITY_ERROR_EXCEPTION(which is"django.db.utils.IntegrityError")last_transfer_session_id=context.transfer_session.id
- If the query returns no records, return
transfer_statuses.COMPLETED. - 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 thepicture_passwordvalues into a set. - Query
FacilityUserfor local records holding those passwords. UseFacilityUser.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. - 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. - Build the available sequences pool. Check
are_picture_passwords_exhausted(dataset_id). If not exhausted, computeget_all_valid_sequences(PICTURE_PASSWORD_SET) - get_assigned_sequences(facility)and shuffle. These utilities are inkolibri/core/auth/utils/picture_passwords.py. - Reassign each local user's picture password. For each
FacilityUserin the query results:- Set
picture_passwordtoavailable_sequences.pop()if available, elseNone - Call
local_user.save()to persist the change to the database immediately
- Set
- Clear deserialization errors on the incoming broken Store records. Update them to set
deserialization_error=Noneanddeserialization_exception=None. This allows_deserialize_from_storeto retry them. - Clean up DeletedModels and HardDeletedModels for the broken store IDs. These are artifacts of the failed deserialization.
- Call
_deserialize_from_store(context.sync_session.profile, filter=context.filter)to retry deserialization. The incoming records still havedirty_bit=True, so they will be processed. The local users' passwords have been changed in the database, so the unique constraint will not conflict. - Return
transfer_statuses.COMPLETED. Important: do not modify the incoming Store records'serializedfield. The incoming records keep their original picture passwords. Thedirty_biton incoming records staysTrueso_deserialize_from_storeprocesses them. The local users' Store records will be updated through the normal Morango serialization flow triggered bylocal_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:
- Run two Kolibri instances configured for peer sync.
- 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_passwordsequence. - Sync the two devices (Device A initiates).
- After sync completes, on Device A query
FacilityUserand 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
- Both learners exist in
- 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)
- Query the Morango
Storefor the affected records on both devices and confirmdirty_bit=False,deleted=False, and noDeletedModelsorHardDeletedModelsentries. 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_storein 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=Nonebecause 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
PicturePasswordCollisionOperationclass exists inkolibri/core/auth/sync_operations.py, inheriting fromReceiverDeserializeOperationwithpriority = -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 thanCOMPLETED - [ ] The Store query filters by
partition,model_name,dirty_bit,deserialization_exception, andlast_transfer_session_id - [ ] The operation does not modify the incoming Store records'
serializedfield - [ ] The operation queries
FacilityUser(the app model) to find local users holding conflicting passwords - [ ] The operation reassigns the local
FacilityUser'spicture_passwordvialocal_user.save() - [ ] After reassignment, the operation clears
deserialization_erroranddeserialization_exceptionon the incoming broken Store records - [ ] The operation cleans up
DeletedModelsandHardDeletedModelsfor the incoming store IDs - [ ]
_deserialize_from_storeis 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.COMPLETEDwithout modifying anything - [ ] If no local users match the conflicting passwords, the operation returns
transfer_statuses.COMPLETEDwithout modifying anything - [ ]
are_picture_passwords_exhausted()is called once before the loop; if exhausted, the local user'spicture_passwordis set toNone - [ ] 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
FacilityUseris reassigned a newpicture_password(notNone, not the original value). The incoming Store'sserializedfield remains unchanged. The incoming Store hasdeserialization_error=Noneanddeserialization_exception=None. - Test that
DeletedModelsandHardDeletedModelsentries for the incoming store are removed after correction. - Test that when
are_picture_passwords_exhausted()returnsTrue, the localFacilityUser'spicture_passwordis set toNone. - Test that when no available sequences remain (empty set from
get_all_valid_sequences), the localFacilityUser'spicture_passwordis set toNone. - Test that when no broken stores are found, the operation returns
COMPLETEDwithout modifying anything. - Test that when
super().handle()returns something other thanCOMPLETED, the operation returns that result immediately without modifying any records. - Test that Store records with a different
deserialization_exception(notIntegrityError) are not touched. - Test that Store records with
dirty_bit=Falseare not touched. - Test that when no local
FacilityUsermatches the conflicting password (edge case), the operation returnsCOMPLETEDwithout modifying anything.
- Test that when a collision is detected, the local
- [ ] Integration test
PicturePasswordCollisionIntegrationTestCaseinkolibri/core/auth/test/test_morango_integration.py:- Create a facility, a local
FacilityUserwithpicture_password="1.2.3", serialize into Store, then create a remote Store record for a different user also withpicture_password="1.2.3". - Run
_deserialize_from_storeto trigger the collision, confirm the remote store hasdirty_bit=Trueanddeserialization_exception=_INTEGRITY_ERROR_EXCEPTION. - Run the operation and confirm:
- The local user has a new
picture_password(not"1.2.3", notNone). - The remote user exists in
FacilityUserwith its originalpicture_password == "1.2.3". - The remote Store has
dirty_bit=False,deserialization_exception=None,deserialization_error=None, and noDeletedModels/HardDeletedModelsentries.
- The local user has a new
- Use
TransactionTestCasebecause Morango's_begin_transactionuses transaction isolation incompatible withTestCase's database wrapping.
- Create a facility, a local
References
kolibri/core/auth/sync_operations.py-- wherePicturePasswordCollisionOperationshould be created; containsReceiverDeserializeOperation(the parent class)docs/backend_architecture/facility_syncing/index.rst-- operations pattern, stage structure, andtransfer_statusescontractkolibri/core/auth/kolibri_plugin.py-- where the operation must be registered at low prioritykolibri/core/auth/sync_event_hook_utils.py--get_dataset_id(context)for scoping the Store query to the correct datasetkolibri/core/auth/utils/picture_passwords.pykolibri/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. 🤖
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
PicturePasswordCollisionOperationinsync_operations.py - [ ] Register the operation in
kolibri_plugin.py - [ ] Write the integration test
- [ ] Lint and final check
@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