kolibri icon indicating copy to clipboard operation
kolibri copied to clipboard

Bulk Coach Assignment: Optimize creation w/ bulk_create if possible

Open nucleogenesis opened this issue 1 year ago • 4 comments

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

Observed behavior

In #13614 the RoleListSerializer class iterates over it's validated data and saves them individually w/ a get_or_create() method call. There is a bulk_create() method available, but it did not work out of the box for our case.

Errors and logs

@ozer550 had this code:

class RoleListSerializer(serializers.ListSerializer):
    def create(self, validated_data):
        ModelClass = self.child.Meta.model
        objects_to_create = []
        for model_data in validated_data:
            self.child.changes = []
            object_to_create = self.child.create(model_data)
            objects_to_create.append(object_to_create)
            self.changes.extend(self.child.changes)
        try:
            created_objects = ModelClass._default_manager.bulk_create(
                objects_to_create, ignore_conflicts=True
            )
        except TypeError:
            tb = traceback.format_exc()
            msg = (
                "Got a `TypeError` when calling `%s.%s.create()`. "
                "This may be because you have a writable field on the "
                "serializer class that is not a valid argument to "
                "`%s.%s.create()`. You may need to make the field "
                "read-only, or override the %s.create() method to handle "
                "this correctly.\nOriginal exception was:\n %s"
                % (
                    ModelClass.__name__,
                    ModelClass._default_manager.name,
                    ModelClass.__name__,
                    ModelClass._default_manager.name,
                    self.__class__.__name__,
                    tb,
                )
            )
            raise TypeError(msg)
        return created_objects

and ran into this error (gist to save space here)

Expected behavior

See the thread here and take note of the "caveats" section in the docs for bulk_create.

Also bear this in mind:

@rtibbles: I agree that this may be something specific for morango models. My guess is that the id is not being set properly during bulk create. Ideally we would be able to use bulk_create with ignore_conflicts=True here to optimize the querying.

Steps to reproduce

  1. Apply the code snippet above to the kolibri.core.auth.serializers.RoleListSerializer class
  2. In Facility -> Users select several coaches and assign them to classes
  3. Investigate whether the errors seen here can be overcome so that we can leverage the optimized bulk creation method.

nucleogenesis avatar Aug 19 '25 21:08 nucleogenesis

Implementation Plan Summary

Branch: issue-13657-af5a49 (target: develop)

Goal

Optimize RoleListSerializer.create() and MembershipListSerializer.create() to use bulk_create() with ignore_conflicts=True instead of per-item get_or_create(), while preserving morango sync compatibility and model-level side effects.

Approach

  • Pre-compute morango fields (id, _morango_partition, _morango_source_id, _morango_dirty_bit) on each model instance before calling bulk_create(), following the existing pattern in kolibri/core/auth/utils/migrate.py
  • For Role: classroom coach roles are handled individually (because Role.save() conditionally creates an ASSIGNABLE_COACH role at the facility level). Non-classroom roles use bulk_create()
  • For Membership: validations (no facility memberships, learnergroup parent check) run before bulk insert, then bulk_create() inserts all at once
  • Deterministic morango UUIDs allow pre-filtering existing records to return only genuinely new objects

Phases

  1. Add helper - _prepare_for_bulk_create() function that sets morango fields (pre_save(), calculate_uuid(), _morango_dirty_bit)
  2. Optimize RoleListSerializer - Bulk create for facility-level roles; individual create for classroom coaches (preserves ASSIGNABLE_COACH side effect)
  3. Optimize MembershipListSerializer - Validate then bulk create all memberships
  4. Final verification - Full test suite, lint, review

Key Design Decisions

  • Classroom coach roles stay individual: Role.save() at line 1527-1541 conditionally creates ASSIGNABLE_COACH roles. Replicating this in bulk would be fragile
  • Validations run before insert: Membership validation (no facility memberships, learnergroup parent check) runs before bulk_create(), matching current fail-fast behavior
  • Pre-filter by morango UUID: Since morango UUIDs are deterministic (computed from partition + source_id + model_name), we can identify existing records without inserting

Environment Status

  • 153/154 auth API tests pass (1 pre-existing CSRF failure unrelated to this issue)
  • Linter passes

rtibblesbot avatar Mar 07 '26 02:03 rtibblesbot

Implementation Progress: bulk_create for Role and Membership serializers

Branch: issue-13657-af5a49 Status: All 4 phases complete

Changes (2 files, +379/-9 lines)

kolibri/core/auth/serializers.py:

  • Added _prepare_for_bulk_create() helper that sets morango fields (id, partition, source_id, dirty_bit) on model instances for bulk_create()
  • RoleListSerializer.create(): Facility-level roles use bulk_create() with ignore_conflicts=True; classroom coach roles remain individual (preserves ASSIGNABLE_COACH side effect in Role.save())
  • MembershipListSerializer.create(): All memberships use bulk_create() after explicit validation (facility rejection, learnergroup parent check). This also fixes a bug where invalid bulk membership creation returned 500 instead of 400.

kolibri/core/auth/test/test_api.py:

  • 3 unit tests for _prepare_for_bulk_create helper (Role, Membership, deterministic UUID)
  • 6 tests for Role bulk creation (multiple roles, duplicates, ASSIGNABLE_COACH side effect, facility admin roles, morango fields)
  • 5 tests for Membership bulk creation (multiple memberships, duplicates, morango fields, validation errors)

Test Results

  • Full auth test directory: 614 passed, 12 skipped, 0 failures
  • Auth model tests: 71 passed, 0 failures
  • Only pre-existing failure: CSRFProtectedAuthTestCase::test_csrf_protected_signup_list (unrelated)
  • Lint: black and flake8 pass

rtibblesbot avatar Mar 07 '26 02:03 rtibblesbot

Self-Review Progress — Branch issue-13657-af5a49

Findings and Fixes

1. [blocking] Missing learnergroup/adhocgroup validation in RoleListSerializer bulk path — FIXED Role.save() validates that roles cannot be assigned to learnergroups/adhocgroups, but the bulk create path bypassed save() entirely. Added explicit validation before bulk creation, with a new test (test_bulk_create_learnergroup_role_rejected).

2. [suggestion] Missing SQLite batch_size in bulk_create calls — FIXED Neither bulk_create call specified batch_size, risking SQLite variable limit errors on large batches. Added _get_batch_size() helper following the established pattern from kolibri.core.auth.utils.migrate._batch_save.

3. [suggestion] MembershipListSerializer.create() lacked transaction.atomic() — FIXED Validation queries and bulk_create weren't atomic, unlike RoleListSerializer.create(). Wrapped in transaction.atomic() for consistency.

4. [praise] Clean separation of classroom coach roles for individual save preserves ASSIGNABLE_COACH side effect.

5. [praise] Deterministic UUID deduplication via _prepare_for_bulk_create + existing ID filtering is elegant.

Acceptance Criteria Status

# Criterion Status
1 RoleListSerializer uses bulk_create MET (with validation fix)
2 MembershipListSerializer uses bulk_create MET
3 Role-specific side effects preserved MET
4 Membership validation preserved MET
5 Tests pass MET (15/15 passing)
6 SQLite compatibility (batch_size) MET (added _get_batch_size)
7 No morango sync regression MET

All tests pass. Changes limited to kolibri/core/auth/serializers.py and kolibri/core/auth/test/test_api.py.

rtibblesbot avatar Mar 07 '26 02:03 rtibblesbot

Fixed in #14341

rtibbles avatar Mar 31 '26 23:03 rtibbles