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
4 changes: 3 additions & 1 deletion .annotation_safe_list.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ waffle.Sample:
sites.Site:
".. no_pii:": "This model has no PII"
learner_pathway_progress.HistoricalLearnerPathwayProgress:
".. no_pii:": "This model has no PII"
".. pii:": "The user field inherited from LearnerPathwayProgress links the row to a learner. Deleted on learner retirement."
".. pii_types:": id
".. pii_retirement:": consumer_api
# Via edx-toggles https://github.com/openedx/edx-toggles
waffle.Switch:
".. no_pii:": "No PII"
17 changes: 17 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,23 @@ Change Log
Unreleased
~~~~~~~~~~

[2.2.0] - 2026-11-30
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Added a ``USER_RETIRE_LMS_CRITICAL`` receiver that deletes a retired learner's pathway progress, its history and
their pathway memberships (ENT-12476), and blanks the Django admin log entries for those rows (including those of
memberships deleted earlier, matched by the learner's username). It is behind the
``enterprise.retirement_receivers_v2`` waffle flag, the kill switch shared with edx-enterprise's learner retirement
receivers.
* Added the ``retire_pathway_data_backlog`` management command, which deletes the pathway data of learners whose
retirement finished before the receiver was turned on. Learners still in the cooling-off period are left alone.
Dry run unless ``--commit`` is passed.
* Retired learners are skipped when pathway data is created or updated (the enrollment receiver, grade updates, the
``update_all_pathways_progress`` backfill and ``update_existing_pathways_progress``), so retirement's deletes are
not undone. Updating a progress row is now an UPDATE only, so a row deleted while an update runs is not inserted
again.
* Pathway logs record the user id instead of the learner's email.
* PII annotations now mark the progress, history and membership tables as holding a learner id.

[2.1.0] - 2026-10-12
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Added support for Python 3.11 and Django 4.2 so the package can be installed in edxapp (LMS).
Expand Down
2 changes: 1 addition & 1 deletion learner_pathway_progress/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
A plugin to track learners progress in pathways..
"""

__version__ = '2.1.0'
__version__ = '2.2.0'
5 changes: 5 additions & 0 deletions learner_pathway_progress/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ class LearnerPathwayProgressConfig(AppConfig):
PluginSignals.SIGNAL_PATH: 'django.db.models.signals.post_save',
PluginSignals.RECEIVER_FUNC_NAME: 'create_learner_enterprise_pathway_membership_for_user',
},
{
PluginSignals.SIGNAL_PATH: 'openedx.core.djangoapps.user_api.accounts.signals'
'.USER_RETIRE_LMS_CRITICAL',
PluginSignals.RECEIVER_FUNC_NAME: 'handle_learner_retirement',
},
],
},
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""
Management command that deletes the pathway data of learners retired before the retirement receiver was turned on.
"""
import logging
import math
import time

from django.core.management import BaseCommand, CommandError

from learner_pathway_progress.models import LearnerEnterprisePathwayMembership, LearnerPathwayProgress
from learner_pathway_progress.signals import retire_learner_pathway_data
from learner_pathway_progress.utilities import completed_retirement_user_ids, cooling_off_user_ids, retired_user_ids

log = logging.getLogger(__name__)

LOG_PREFIX = '[Retire Pathway Data Backlog]'
SKIPPED = (
'; skipped %d learners with pathway data in the retirement cooling-off period (handled by the receiver) and %d '
'with another unfinished retirement (if above 0, run again once those retirements finish)'
)
DRY_RUN_MESSAGE = '%s Dry run: would remove the pathway data of %d retired learners: %s' + SKIPPED
DONE_MESSAGE = '%s Removed the pathway data of %d retired learners: %s' + SKIPPED


class Command(BaseCommand):
"""
Delete the pathway progress, its history and the pathway memberships of learners who were already retired.

The ``USER_RETIRE_LMS_CRITICAL`` receiver only handles retirements that happen after it is turned on. This command
handles the earlier ones (tech spec EE-9, Privacy Q2): it finds the users whose retirement has finished (see
``completed_retirement_user_ids``) who still have pathway data, and removes it with the same
``retire_learner_pathway_data`` as the receiver, one learner per transaction. Learners still in the cooling-off
period, who can cancel, are left alone; the receiver handles them when their retirement runs. A retirement that had
already passed the LMS step when the receiver was turned on, but has not finished yet (in progress, errored or
aborted), is skipped too, and the receiver will not see it again. Both groups of skipped learners with pathway data
are counted separately: only the second one is a reason to run the command again once those retirements finish.
The usernames of the learners removed here were already replaced, so admin log entries of memberships deleted
before are not matched by username; those of the rows deleted here are blanked as usual.

Dry run by default: it only reports how many learners and rows would be removed. Pass ``--commit`` to remove them.
Logs only counts.

Examples:

./manage.py lms retire_pathway_data_backlog
./manage.py lms retire_pathway_data_backlog --commit --batch-size 100 --sleep 1
"""
help = 'Deletes the pathway data of learners who were already retired.'

def add_arguments(self, parser):
parser.add_argument('--commit', action='store_true', help='Delete the data. Without it, dry run.')
parser.add_argument('--batch-size', type=int, default=100, help='Learners handled between sleeps.')
parser.add_argument('--sleep', type=float, default=1.0, help='Seconds to wait between batches.')

def handle(self, *args, **options):
batch_size = options['batch_size']
if batch_size < 1:
raise CommandError('--batch-size must be at least 1.')
sleep = options['sleep']
if not math.isfinite(sleep) or sleep < 0:
raise CommandError('--sleep must be a finite number of seconds, 0 or more.')
retired = completed_retirement_user_ids()
if retired is None: # pragma: no cover
raise CommandError('User retirement requests are not available; run this command in the LMS.')

tables = _pathway_tables(retired)
user_ids = _user_ids(tables)
unfinished = set(_user_ids(_pathway_tables(retired_user_ids().exclude(user_id__in=retired))))
cooling_off = len(unfinished & set(_user_ids(_pathway_tables(cooling_off_user_ids()))))
skipped = (cooling_off, len(unfinished) - cooling_off)

if not options['commit']:
counts = {name: rows.count() for name, rows in tables.items()}
log.info(DRY_RUN_MESSAGE, LOG_PREFIX, len(user_ids), counts, *skipped)
return

totals = {}
for start in range(0, len(user_ids), batch_size):
if start:
time.sleep(sleep)
for user_id in user_ids[start:start + batch_size]:
for name, count in retire_learner_pathway_data(user_id).items():
totals[name] = totals.get(name, 0) + count
log.info(DONE_MESSAGE, LOG_PREFIX, len(user_ids), totals, *skipped)


def _pathway_tables(user_ids):
"""
Return the querysets, by table name, of the pathway rows of the users in ``user_ids``.
"""
history_model = LearnerPathwayProgress.history.model # pylint: disable=no-member
return {
'pathway_progress': LearnerPathwayProgress.objects.filter(user_id__in=user_ids),
'pathway_progress_history': history_model.objects.filter(user_id__in=user_ids),
'pathway_memberships': LearnerEnterprisePathwayMembership.objects.filter(user_id__in=user_ids),
}


def _user_ids(tables):
"""
Return the sorted ids of the users who have rows in any of ``tables``.

Each table returns its distinct user ids from the database, so a learner's many history rows count once. The
default ordering is cleared, or the history table's ordering columns would be part of ``DISTINCT``.
"""
return sorted(set().union(*(
rows.order_by().values_list('user_id', flat=True).distinct() for rows in tables.values()
)))
14 changes: 11 additions & 3 deletions learner_pathway_progress/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ class LearnerPathwayProgress(TimeStampedModel):
"""
Learner pathway progress model.

.. no_pii:
.. pii: The user field links the row to a learner. Deleted with its history on learner retirement
(learner_pathway_progress.signals.handle_learner_retirement).
.. pii_types: id
.. pii_retirement: consumer_api
"""

user = models.ForeignKey(User, db_index=True, on_delete=models.CASCADE)
Expand Down Expand Up @@ -131,14 +134,19 @@ def update_pathway_progress(self):
completion_count += 1
step['status'] = completion_count / step_completion_requirement * 100
self.learner_pathway_progress = json.dumps(pathway_snapshot)
self.save()
# UPDATE only, never INSERT: if learner retirement deleted this row since it was loaded, a plain save() would
# insert it again with new history. With update_fields, Django raises DatabaseError instead.
self.save(update_fields=['learner_pathway_progress', 'modified'])


class LearnerEnterprisePathwayMembership(TimeStampedModel):
"""
Model to store pathway membership of an enterprise learner.

.. no_pii:
.. pii: The user field links the row to a learner. Deleted on learner retirement
(learner_pathway_progress.signals.handle_learner_retirement).
.. pii_types: id
.. pii_retirement: consumer_api
"""

user = models.ForeignKey(User, db_index=True, on_delete=models.CASCADE)
Expand Down
92 changes: 90 additions & 2 deletions learner_pathway_progress/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@
"""
from logging import getLogger

from django.contrib.admin.models import LogEntry
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from django.db.models import Q
from django.db.models.signals import post_save

from learner_pathway_progress import waffle
from learner_pathway_progress.models import LearnerEnterprisePathwayMembership
from learner_pathway_progress.models import LearnerEnterprisePathwayMembership, LearnerPathwayProgress
from learner_pathway_progress.utilities import (
get_learner_pathways_associated_with_course,
is_user_retired,
update_learner_pathway_progress,
)

Expand Down Expand Up @@ -51,6 +56,8 @@ def create_learner_enterprise_pathway_membership_for_user(
"""
if waffle.ENABLE_PATHWAY_PROGRESS_UPDATE_SWITCH.is_enabled() and created:
user_id = instance.enterprise_customer_user.user_id
if is_user_retired(user_id):
return
user = User.objects.filter(id=user_id).first()
learner_pathways = get_learner_pathways_associated_with_course(user, instance.course_id)
if learner_pathways:
Expand All @@ -65,11 +72,92 @@ def create_learner_enterprise_pathway_membership_for_user(
if newly_created:
membership_status = 'created'
log.info(
f"Membership for pathway:{pathway} {membership_status} for user:{user.email} and"
f"Membership for pathway:{pathway} {membership_status} for user_id:{user.id} and"
f" enterprise: {instance.enterprise_customer_user.enterprise_customer.uuid}"
f" with course: {instance.course_id}."
)


def _redact_admin_log(model, object_ids, repr_prefix=None):
"""
Blank the text the Django admin log keeps for the given objects of ``model``.

``object_repr`` holds the object's ``__str__``, which names the learner (a pathway membership shows the
username), and it stays in ``django_admin_log`` after the object is deleted (tech spec R3). The entries themselves
are kept for the audit trail. Entries whose ``object_repr`` starts with ``repr_prefix`` are blanked too, for objects
whose ids are no longer known.

Returns:
The number of admin log entries changed.
"""
condition = Q(object_id__in=[str(object_id) for object_id in object_ids])
if repr_prefix:
condition |= Q(object_repr__startswith=repr_prefix)
return LogEntry.objects.filter(
condition, content_type=ContentType.objects.get_for_model(model),
).update(object_repr=f'Retired {model._meta.object_name}', change_message='')


def membership_repr_prefix(username):
"""
Return how ``LearnerEnterprisePathwayMembership.__str__`` starts for ``username``.

Usernames cannot hold a comma, so the prefix matches only that learner's memberships.
"""
return f'User: {username}, Pathway UUID: '


def retire_learner_pathway_data(user_id, username=None):
"""
Delete all pathway data of a learner: their pathway progress with all its history, and their pathway memberships.

Privacy requires this data to be deleted rather than kept with a user id (tech spec EE-9, Privacy Q2). Django admin
log entries for the deleted rows are blanked (tech spec R3). Memberships keep no history, so the admin log entries
of memberships deleted earlier are found by the ``username`` their text starts with, when it is given. Safe to call
more than once: a second call finds nothing.

Returns:
A dict of the number of rows deleted or changed per table. It holds no personal data, so it can be logged.
"""
with transaction.atomic():
progress = LearnerPathwayProgress.objects.filter(user_id=user_id)
history = LearnerPathwayProgress.history.model.objects.filter(user_id=user_id) # pylint: disable=no-member
memberships = LearnerEnterprisePathwayMembership.objects.filter(user_id=user_id)
# The history also has the ids of progress rows that were already deleted (for example from the admin).
progress_ids = set(progress.values_list('id', flat=True)) | set(history.values_list('id', flat=True))
admin_log_entries = (
_redact_admin_log(LearnerPathwayProgress, progress_ids)
+ _redact_admin_log(
LearnerEnterprisePathwayMembership,
memberships.values_list('id', flat=True),
membership_repr_prefix(username) if username else None,
)
)
# Deleting the progress rows writes a final history row each, so the history is deleted afterwards.
progress_deleted = progress.delete()[1].get(LearnerPathwayProgress._meta.label, 0)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 6a29185.

history_deleted = history.delete()[0]
memberships_deleted = memberships.delete()[0]
return {
'pathway_progress': progress_deleted,
'pathway_progress_history': history_deleted,
'pathway_memberships': memberships_deleted,
'admin_log_entries': admin_log_entries,
}


def handle_learner_retirement(sender, user, **kwargs): # pylint: disable=unused-argument
"""
Handle USER_RETIRE_LMS_CRITICAL: delete the retiring learner's pathway data.

Behind the ``enterprise.retirement_receivers_v2`` flag, the kill switch shared with edx-enterprise's retirement
receivers. With the flag off, nothing changes. Logs only counts and the user id.
"""
if not waffle.RETIREMENT_RECEIVERS_V2_FLAG.is_enabled():
return
# The LMS replaces the username only after sending the signal, so this is still the learner's own.
counts = retire_learner_pathway_data(user.id, user.username)
log.info('[Learner Retirement] Deleted pathway data for lms_user_id=%s: %s', user.id, counts)


if EnterpriseCourseEnrollment is not None:
post_save.connect(create_learner_enterprise_pathway_membership_for_user, sender=EnterpriseCourseEnrollment)
Loading
Loading