Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 29 additions & 5 deletions src/openedx_learning/applets/cbe/statuses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Comment thread
felipemontoya marked this conversation as resolved.
Resolved
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):
Comment thread
ormsbee marked this conversation as resolved.
Resolved
# 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add a test where the row that raise_status() read is stale? This is fallout from the early return I asked for last round: every test that used to reach this UPDATE with nothing to raise now returns before it, so nothing checks status_id__lt anymore. Claude removed it from this line and the CBE suite still passed, while the same edit on 2aac88f breaks 14 tests.

That filter is what keeps a writer from overwriting a raise that landed after its read (ADR-0004, Decision 4), so I'd like a test holding it in place. A stale read is the only way to get here with nothing to raise now, so the test has to fake one. Maybe something like this in test_statuses.py?

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

Claude ran this on the branch. It passes as-is and fails with status_id__lt removed.

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
107 changes: 106 additions & 1 deletion tests/openedx_learning/applets/cbe/test_statuses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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),
]
10 changes: 5 additions & 5 deletions tests/openedx_learning/applets/cbe/test_tag_rollup.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,18 +497,18 @@ 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)
requirement = _add_nested_requirement(child, _object_id("c"), default_rule_profile, levels=1)
_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)


Expand Down