diff --git a/src/openedx_learning/applets/cbe/statuses.py b/src/openedx_learning/applets/cbe/statuses.py index e30a05f34..3826968fa 100644 --- a/src/openedx_learning/applets/cbe/statuses.py +++ b/src/openedx_learning/applets/cbe/statuses.py @@ -7,7 +7,8 @@ from datetime import datetime from typing import TypeVar -from django.db import models +from django.db import models, transaction +from django.db.models.signals import post_save from .models import ( MasteryStatus, @@ -32,13 +33,36 @@ def raise_status( Create or raise the learner status row identified by ``lookup``; never lowers a stored status. Returns 1 if a row was created or raised, 0 if the stored status was already at least ``status``. + + ``post_save`` fires for a created row (from ``get_or_create``) and for a raised one (sent here, because the raise + is a bulk ``UPDATE``), so listeners such as analytics sinks see every change. It does not fire when nothing changed. + In both cases it is sent before the transaction around the write commits, so a receiver that queues a task should + do it from ``transaction.on_commit()``. + + Other code that changes a stored status, such as the staff override and recalculation planned in ADR-0004, must + send ``post_save`` too. """ row, created = manager.get_or_create(**lookup, defaults={"status_id": status, "created": now, "modified": now}) if created: log.info("Created %s %s: status %s -> %s", manager.model.__name__, lookup, None, status) return 1 - # A single conditional UPDATE, never read-then-write: a stale read can only compute a value that is too low. - changed = manager.filter(pk=row.pk, status_id__lt=status).update(status_id=status, modified=now) - if changed: - log.info("Raised %s %s: status %s -> %s", manager.model.__name__, lookup, row.status_id, status) + if row.status_id >= status: + # Automatic writes only raise a status, so even a stale read means there is nothing to raise. + return 0 + # Commit the raise with its post_save, so a failing receiver rolls it back and a retry resends. + with transaction.atomic(savepoint=False): + # A single conditional UPDATE, never read-then-write: a stale read can only compute a value that is too low. + raised = manager.filter(pk=row.pk, status_id__lt=status) + changed = raised.update(status_id=status, modified=now) + if changed: + log.info("Raised %s %s: status %s -> %s", manager.model.__name__, lookup, row.status_id, status) + row.status_id, row.modified = status, now + post_save.send( + sender=manager.model, + instance=row, + created=False, + update_fields=frozenset({"status_id", "modified"}), + raw=False, + using=raised.db, # The alias that update() wrote to; manager.db is the router's read alias. + ) return changed diff --git a/tests/openedx_learning/applets/cbe/test_statuses.py b/tests/openedx_learning/applets/cbe/test_statuses.py index 5542f4157..296f6ece1 100644 --- a/tests/openedx_learning/applets/cbe/test_statuses.py +++ b/tests/openedx_learning/applets/cbe/test_statuses.py @@ -5,10 +5,11 @@ from datetime import datetime, timezone import pytest +from django.db.models.signals import post_save from openedx_learning.applets.cbe import statuses from openedx_learning.applets.cbe.statuses import raise_status -from openedx_learning.models import MasteryStatus, StudentCompetencyStatus +from openedx_learning.models import MasteryStatus, StudentCompetencyCriteriaGroupStatus, StudentCompetencyStatus pytestmark = pytest.mark.django_db @@ -93,3 +94,107 @@ def test_an_unchanged_status_is_not_logged(user, tag, caplog: pytest.LogCaptureF _write(user, tag, MasteryStatus.DEMONSTRATED, SECOND) assert not caplog.records + + +@pytest.fixture(name="saves") +def fixture_saves(): + """Record every post_save sent for StudentCompetencyStatus as (created, status_id, modified).""" + received = [] + + def receiver(sender, instance, created, **kwargs): # pylint: disable=unused-argument + received.append((created, instance.status_id, instance.modified)) + + post_save.connect(receiver, sender=StudentCompetencyStatus, weak=False) + yield received + post_save.disconnect(receiver, sender=StudentCompetencyStatus) + + +def test_creating_a_row_sends_post_save(user, tag, saves) -> None: + """A created row sends post_save with created=True.""" + _write(user, tag, MasteryStatus.PARTIALLY_ATTEMPTED, FIRST) + + assert saves == [(True, MasteryStatus.PARTIALLY_ATTEMPTED, FIRST)] + + +def test_raising_a_status_sends_post_save(user, tag, saves) -> None: + """A raise is a bulk UPDATE, so raise_status sends post_save itself, with the raised values.""" + _write(user, tag, MasteryStatus.PARTIALLY_ATTEMPTED, FIRST) + + _write(user, tag, MasteryStatus.DEMONSTRATED, SECOND) + + assert saves[1:] == [(False, MasteryStatus.DEMONSTRATED, SECOND)] + + +def test_an_unchanged_status_sends_no_post_save(user, tag, saves) -> None: + """A write that leaves the stored status as it was sends nothing.""" + _write(user, tag, MasteryStatus.DEMONSTRATED, FIRST) + + _write(user, tag, MasteryStatus.PARTIALLY_ATTEMPTED, SECOND) + _write(user, tag, MasteryStatus.DEMONSTRATED, SECOND) + + assert len(saves) == 1 + + +def test_a_raise_that_loses_a_race_changes_nothing(user, tag, saves, monkeypatch) -> None: + """The conditional UPDATE decides, not the row that was read, so a raise behind a stale read is a no-op.""" + _write(user, tag, MasteryStatus.PARTIALLY_ATTEMPTED, FIRST) + stale = StudentCompetencyStatus.objects.get(user=user, tag=tag) + _write(user, tag, MasteryStatus.DEMONSTRATED, FIRST) + monkeypatch.setattr(StudentCompetencyStatus.objects, "get_or_create", lambda **kwargs: (stale, False)) + + assert _write(user, tag, MasteryStatus.DEMONSTRATED, SECOND) == 0 + + assert StudentCompetencyStatus.objects.get(user=user, tag=tag).modified == FIRST + assert len(saves) == 2 + + +@pytest.mark.django_db(transaction=True) +@pytest.mark.usefixtures("migration_seed_rows") +def test_a_failing_receiver_rolls_back_the_raise(user, tag) -> None: + """A receiver that raises rolls the raise back, so a retry sends post_save again.""" + _write(user, tag, MasteryStatus.PARTIALLY_ATTEMPTED, FIRST) + received = [] + + def failing_receiver(sender, instance, created, **kwargs): # pylint: disable=unused-argument + received.append(instance.status_id) + if len(received) == 1: + raise RuntimeError("receiver failed") + + post_save.connect(failing_receiver, sender=StudentCompetencyStatus, weak=False) + try: + with pytest.raises(RuntimeError): + _write(user, tag, MasteryStatus.DEMONSTRATED, SECOND) + assert StudentCompetencyStatus.objects.get(user=user, tag=tag).status_id == MasteryStatus.PARTIALLY_ATTEMPTED + + assert _write(user, tag, MasteryStatus.DEMONSTRATED, SECOND) == 1 + finally: + post_save.disconnect(failing_receiver, sender=StudentCompetencyStatus) + + assert received == [MasteryStatus.DEMONSTRATED, MasteryStatus.DEMONSTRATED] + assert StudentCompetencyStatus.objects.get(user=user, tag=tag).status_id == MasteryStatus.DEMONSTRATED + + +def test_raising_a_group_status_sends_post_save(user, group) -> None: + """Group status raises are bulk UPDATEs too, so they send post_save like competency status raises.""" + received = [] + + def receiver(sender, instance, created, **kwargs): # pylint: disable=unused-argument + received.append((created, instance.status_id, instance.modified)) + + post_save.connect(receiver, sender=StudentCompetencyCriteriaGroupStatus, weak=False) + try: + lookup = {"user_id": user.id, "group_id": group.id} + raise_status( + StudentCompetencyCriteriaGroupStatus.objects, lookup=lookup, + status=MasteryStatus.ATTEMPTED_NOT_DEMONSTRATED, now=FIRST, + ) + raise_status( + StudentCompetencyCriteriaGroupStatus.objects, lookup=lookup, status=MasteryStatus.DEMONSTRATED, now=SECOND, + ) + finally: + post_save.disconnect(receiver, sender=StudentCompetencyCriteriaGroupStatus) + + assert received == [ + (True, MasteryStatus.ATTEMPTED_NOT_DEMONSTRATED, FIRST), + (False, MasteryStatus.DEMONSTRATED, SECOND), + ] diff --git a/tests/openedx_learning/applets/cbe/test_tag_rollup.py b/tests/openedx_learning/applets/cbe/test_tag_rollup.py index 78e53965e..702a15134 100644 --- a/tests/openedx_learning/applets/cbe/test_tag_rollup.py +++ b/tests/openedx_learning/applets/cbe/test_tag_rollup.py @@ -497,10 +497,10 @@ def test_a_repeated_rollup_of_nested_groups_under_a_parent_competency_runs_a_fix user, competency_taxonomy, default_rule_profile, django_assert_num_queries, ) -> None: """ - The repeated rollup runs 1 query to find the starting group, 6 for the nested group's level, 9 for the root's level - (including the read of the root's stored status and the competency write), and 7 for the parent-competency walk. - Each status write is a read and a conditional UPDATE, and the four UPDATEs match no row because every stored - status is already DEMONSTRATED. + The repeated rollup runs 1 query to find the starting group, 5 for the nested group's level, 7 for the root's level + (including the read of the root's stored status and the competency write), and 6 for the parent-competency walk. + Each of the four status writes is a single read: every stored status is already DEMONSTRATED, so none of them + issues an UPDATE or opens a transaction. """ parent = _make_tag(competency_taxonomy, "Parent") child = _make_tag(competency_taxonomy, "Child", parent) @@ -508,7 +508,7 @@ def test_a_repeated_rollup_of_nested_groups_under_a_parent_competency_runs_a_fix _record(user, requirement, DEMONSTRATED) _roll_up(user, requirement.object_id) - with django_assert_num_queries(23): + with django_assert_num_queries(19): _roll_up(user, requirement.object_id)