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
2 changes: 2 additions & 0 deletions src/openedx_learning/applets/cbe/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from .learner_status import (
CompetencyMasteryStatus,
MasteryStatus,
StudentCompetencyCriteriaGroupStatus,
StudentCompetencyCriteriaStatus,
StudentCompetencyStatus,
)
Expand All @@ -21,6 +22,7 @@
"LogicOperator",
"MasteryStatus",
"RuleType",
"StudentCompetencyCriteriaGroupStatus",
"StudentCompetencyCriteriaStatus",
"StudentCompetencyStatus",
]
60 changes: 50 additions & 10 deletions src/openedx_learning/applets/cbe/models/learner_status.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,31 @@
"""
Models tracking a learner's mastery status at each level of a criteria tree.

:class:`StudentCompetencyCriteriaStatus` covers one leaf :class:`~openedx_learning.models.CompetencyCriterion`
and :class:`StudentCompetencyStatus` covers one :class:`~openedx_tagging.models.Tag`. Each holds one row per
learner per node, updated in place (ADR-0003 Decision 5). Which writes may raise or lower a status is decided
in the API layer, not here (ADR-0004 Decisions 4 and 6). ``created`` and ``modified`` are caller-supplied
because ``auto_now`` does not fire on ``QuerySet.update()``, which is how conditional raises are written.
``user`` is ``CASCADE`` so that this library never vetoes ``User.delete()`` platform-wide. The node foreign
keys are ``PROTECT`` because every foreign key above them in the criteria tree is ``CASCADE``: without
``PROTECT``, deleting a tag, taxonomy, group or ``ObjectTag`` would silently delete the learner status beneath
it (ADR-0002 Decision 7).
:class:`StudentCompetencyCriteriaStatus` covers one leaf :class:`~openedx_learning.models.CompetencyCriterion`,
:class:`StudentCompetencyCriteriaGroupStatus` covers one
:class:`~openedx_learning.models.CompetencyCriteriaGroup`, and :class:`StudentCompetencyStatus` covers one
:class:`~openedx_tagging.models.Tag`. Each holds one row per learner per node, updated in place (ADR-0003
Decision 5). Which writes may raise or lower a status is decided in the API layer, not here (ADR-0004
Decisions 4 and 6). ``created`` and ``modified`` are caller-supplied because ``auto_now`` does not fire on
``QuerySet.update()``, which is how conditional raises are written. ``user`` is ``CASCADE`` so that this
library never vetoes ``User.delete()`` platform-wide. The node foreign keys are ``PROTECT`` because every
foreign key above them in the criteria tree is ``CASCADE``: without ``PROTECT``, deleting a tag, taxonomy,
group or ``ObjectTag`` would silently delete the learner status beneath it (ADR-0002 Decision 7).
"""
from django.conf import settings
from django.db import models

from openedx_django_lib.fields import manual_date_time_field
from openedx_tagging.models import Tag

from .criteria import CompetencyCriterion
from .criteria import CompetencyCriteriaGroup, CompetencyCriterion

__all__ = [
"MasteryStatus",
"CompetencyMasteryStatus",
"StudentCompetencyStatus",
"StudentCompetencyCriteriaStatus",
"StudentCompetencyCriteriaGroupStatus",
]


Expand Down Expand Up @@ -139,3 +141,41 @@ class Meta:
name="oex_learning_studentcriteriastatus_user_criterion_uniq",
),
]


class StudentCompetencyCriteriaGroupStatus(models.Model):
"""
A learner's current mastery status for one ``CompetencyCriteriaGroup``.

One row per learner per group, updated in place (ADR-0003 Decision 5).

.. no_pii:
"""

user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="+",
)
group = models.ForeignKey(
CompetencyCriteriaGroup,
db_column="competency_criteria_group_id",
on_delete=models.PROTECT,
related_name="+",
)
status = models.ForeignKey(
CompetencyMasteryStatus,
on_delete=models.PROTECT,
related_name="+",
)
created = manual_date_time_field()
modified = manual_date_time_field()

class Meta:
constraints = [
# ADR-0002 Decision 5 index 7.
models.UniqueConstraint(
fields=("user", "group"),
name="oex_learning_studentcriteriagroupstatus_user_group_uniq",
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Generated by Django 5.2.16 on 2026-09-28 16:26

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models

import openedx_django_lib.validators


class Migration(migrations.Migration):

dependencies = [
('openedx_learning', '0011_studentcompetencycriteriastatus'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='StudentCompetencyCriteriaGroupStatus',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(validators=[openedx_django_lib.validators.validate_utc_datetime])),
('modified', models.DateTimeField(validators=[openedx_django_lib.validators.validate_utc_datetime])),
('group', models.ForeignKey(db_column='competency_criteria_group_id', on_delete=django.db.models.deletion.PROTECT, related_name='+', to='openedx_learning.competencycriteriagroup')),
('status', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='openedx_learning.competencymasterystatus')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)),
],
options={
'constraints': [models.UniqueConstraint(fields=('user', 'group'), name='oex_learning_studentcriteriagroupstatus_user_group_uniq')],
},
),
]
58 changes: 58 additions & 0 deletions tests/openedx_learning/applets/cbe/test_adr_0002_indexes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""ADR-0002 Decision 5's ten indexes exist in the migrated schema, on every database backend."""
import pytest
from django.db import connection

pytestmark = pytest.mark.django_db

# (table, columns, unique), in ADR-0002 Decision 5's order. Indexes 2, 4 and 5 are Django's
# automatic foreign key indexes, so no Meta.indexes entry declares them.
ADR_0002_INDEXES = [
("openedx_learning_competencycriteriagroup", ["oel_tagging_tag_id", "course_id"], False),
("openedx_learning_competencycriteriagroup", ["parent_id"], False),
("oel_tagging_objecttag", ["object_id"], False),
("openedx_learning_competencycriterion", ["oel_tagging_objecttag_id"], False),
("openedx_learning_competencycriterion", ["competency_criteria_group_id"], False),
("openedx_learning_studentcompetencycriteriastatus", ["user_id", "competency_criteria_id"], True),
("openedx_learning_studentcompetencycriteriagroupstatus", ["user_id", "competency_criteria_group_id"], True),
("openedx_learning_studentcompetencystatus", ["user_id", "oel_tagging_tag_id"], True),
("openedx_learning_competencyruleprofile", ["scope_code"], True),
("openedx_learning_competencymasterystatus", ["status"], True),
]
Comment on lines +7 to +20

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Please either remove this module as a whole, or put some kind of disclaimer in the docstring that this is unusual. I do not want to encourage the practice of putting so much schema detail in an ADR and then testing against it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Removed the module (openedx#854).



def _indexes(table: str) -> list[tuple[list[str], bool]]:
"""Return (columns, unique) for every index on `table`."""
with connection.cursor() as cursor:
if connection.vendor == "sqlite":
# Django's SQLite introspection cannot parse a table whose CHECK constraint contains a
# comma, such as StudentCompetencyStatus's `status_id IN (2, 3)`, so read SQLite's own
# index list instead. It includes the automatic indexes behind inline UNIQUE constraints.
cursor.execute(f"PRAGMA index_list({connection.ops.quote_name(table)})")
indexes = []
for _seq, name, unique, *_rest in cursor.fetchall():
cursor.execute(f"PRAGMA index_info({connection.ops.quote_name(name)})")
indexes.append(([column for _rank, _cid, column in cursor.fetchall()], bool(unique)))
return indexes
constraints = connection.introspection.get_constraints(cursor, table)
return [
(list(constraint["columns"]), bool(constraint["unique"]))
for constraint in constraints.values()
if constraint["index"] or constraint["unique"]
]


@pytest.mark.parametrize(
"table, columns, unique",
ADR_0002_INDEXES,
ids=[f"index-{number}" for number in range(1, len(ADR_0002_INDEXES) + 1)],
)
def test_adr_0002_index_exists(table: str, columns: list[str], unique: bool) -> None:
"""
Every index from ADR-0002 Decision 5 is present, and the unique ones are unique: indexes 6, 7 and 8 are
unique on `(user_id, node_id)`, index 9 is unique on `scope_code`, and index 10 is unique on the status value.
"""
matches = [
index_columns for index_columns, index_unique in _indexes(table)
if index_columns == columns and (index_unique or not unique)
]
assert matches, f"no {'unique ' if unique else ''}index on {table}({', '.join(columns)})"
157 changes: 157 additions & 0 deletions tests/openedx_learning/applets/cbe/test_criteria_group_status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
"""Tests for StudentCompetencyCriteriaGroupStatus, a learner's status for one criteria group."""
from datetime import datetime

import pytest
from django.contrib.auth import get_user_model
from django.db import IntegrityError, transaction
from django.db.models import ProtectedError

from openedx_learning.models import (
CompetencyCriteriaGroup,
CompetencyCriterion,
CompetencyMasteryStatus,
CompetencyRuleProfile,
MasteryStatus,
StudentCompetencyCriteriaGroupStatus,
StudentCompetencyCriteriaStatus,
StudentCompetencyStatus,
)
from openedx_tagging.models import ObjectTag, Tag

pytestmark = pytest.mark.django_db


def test_second_row_for_the_same_user_and_group_is_rejected(
user, group: CompetencyCriteriaGroup, now: datetime
) -> None:
"""
Learner status rows are updated in place, one row per learner and node under a unique constraint:
a second row for the same learner and group is rejected.
"""
StudentCompetencyCriteriaGroupStatus.objects.create(
user=user, group=group, status_id=MasteryStatus.PARTIALLY_ATTEMPTED, created=now, modified=now,
)

with pytest.raises(IntegrityError), transaction.atomic():
StudentCompetencyCriteriaGroupStatus.objects.create(
user=user, group=group, status_id=MasteryStatus.DEMONSTRATED, created=now, modified=now,
)


def test_attempted_not_demonstrated_is_accepted(user, group: CompetencyCriteriaGroup, now: datetime) -> None:
"""
The models accept any status value the caller writes, including `AttemptedNotDemonstrated`, which
only `StudentCompetencyStatus` rejects.
"""
row = StudentCompetencyCriteriaGroupStatus.objects.create(
user=user, group=group, status_id=MasteryStatus.ATTEMPTED_NOT_DEMONSTRATED, created=now, modified=now,
)

row.refresh_from_db()
assert row.status_id == MasteryStatus.ATTEMPTED_NOT_DEMONSTRATED


def test_group_delete_is_protected_by_its_status(user, group: CompetencyCriteriaGroup, now: datetime) -> None:
"""
The foreign key from `StudentCompetencyCriteriaGroupStatus` to its definition row,
`CompetencyCriteriaGroup`, is `PROTECT`: deleting a group that holds a learner status raises `ProtectedError`.
"""
StudentCompetencyCriteriaGroupStatus.objects.create(
user=user, group=group, status_id=MasteryStatus.DEMONSTRATED, created=now, modified=now,
)

with pytest.raises(ProtectedError), transaction.atomic():
group.delete()

assert CompetencyCriteriaGroup.objects.filter(pk=group.pk).exists()


def test_root_group_delete_is_protected_by_a_descendant_group_status(
user, group: CompetencyCriteriaGroup, now: datetime
) -> None:
"""
The transitive cases are tested, not only the direct ones: deleting a root `CompetencyCriteriaGroup`
above a descendant group that holds a learner status row raises `ProtectedError`.
"""
child_group = CompetencyCriteriaGroup.objects.create(tag=group.tag, parent=group)
StudentCompetencyCriteriaGroupStatus.objects.create(
user=user, group=child_group, status_id=MasteryStatus.DEMONSTRATED, created=now, modified=now,
)

with pytest.raises(ProtectedError), transaction.atomic():
group.delete()

assert CompetencyCriteriaGroup.objects.filter(pk__in=[group.pk, child_group.pk]).count() == 2


def test_tag_delete_is_protected_by_a_group_status_with_no_criterion_status_beneath(
user, tag: Tag, group: CompetencyCriteriaGroup, now: datetime
) -> None:
"""
Deleting an `oel_tagging_tag` with a learner status row anywhere beneath it raises `ProtectedError`,
even when that row is a group status with no criterion status beneath it.
"""
# #642 wants the database to fail closed here, although ADR-0002 Decision 7's predicate reads only
# the criterion table.
StudentCompetencyCriteriaGroupStatus.objects.create(
user=user, group=group, status_id=MasteryStatus.DEMONSTRATED, created=now, modified=now,
)
assert not StudentCompetencyCriteriaStatus.objects.exists()

with pytest.raises(ProtectedError), transaction.atomic():
tag.delete()

assert Tag.objects.filter(pk=tag.pk).exists()


def test_mastery_status_row_delete_is_protected_by_a_group_status(
user, group: CompetencyCriteriaGroup, now: datetime
) -> None:
"""
The `status_id` foreign key to `CompetencyMasteryStatuses` is `PROTECT`.
"""
StudentCompetencyCriteriaGroupStatus.objects.create(
user=user, group=group, status_id=MasteryStatus.DEMONSTRATED, created=now, modified=now,
)

with pytest.raises(ProtectedError), transaction.atomic():
CompetencyMasteryStatus.objects.get(pk=MasteryStatus.DEMONSTRATED).delete()

assert CompetencyMasteryStatus.objects.filter(pk=MasteryStatus.DEMONSTRATED).exists()


def test_user_delete_removes_only_that_users_rows_from_all_three_status_tables(
user,
group: CompetencyCriteriaGroup,
object_tag: ObjectTag,
default_rule_profile: CompetencyRuleProfile,
now: datetime,
) -> None:
"""
Deleting a user row removes that user's status rows across all three `Student*Status` models, and
leaves other users' rows in place.
"""
other_user = get_user_model().objects.create(username="other_learner")
criterion = CompetencyCriterion.objects.create(
group=group, object_tag=object_tag, rule_profile=default_rule_profile
)
StudentCompetencyCriteriaStatus.objects.create(
user=user, criterion=criterion, status_id=MasteryStatus.DEMONSTRATED, created=now, modified=now,
)
StudentCompetencyCriteriaGroupStatus.objects.create(
user=user, group=group, status_id=MasteryStatus.DEMONSTRATED, created=now, modified=now,
)
StudentCompetencyStatus.objects.create(
user=user, tag=group.tag, status_id=MasteryStatus.DEMONSTRATED, created=now, modified=now,
)
StudentCompetencyCriteriaGroupStatus.objects.create(
user=other_user, group=group, status_id=MasteryStatus.DEMONSTRATED, created=now, modified=now,
)
user_id = user.pk

user.delete()

assert not StudentCompetencyCriteriaStatus.objects.filter(user_id=user_id).exists()
assert not StudentCompetencyCriteriaGroupStatus.objects.filter(user_id=user_id).exists()
assert not StudentCompetencyStatus.objects.filter(user_id=user_id).exists()
assert StudentCompetencyCriteriaGroupStatus.objects.filter(user=other_user).exists()
Loading
Loading