Skip to content

feat: delete pathway data on learner retirement (ENT-12476) - #28

Open
sjasti-sonata-svg wants to merge 1 commit into
masterfrom
sjasti/ENT-12476-retire-pathway-progress
Open

sjasti-sonata-svg wants to merge 1 commit into
masterfrom
sjasti/ENT-12476-retire-pathway-progress

Conversation

@sjasti-sonata-svg

@sjasti-sonata-svg sjasti-sonata-svg commented Nov 30, 2026 •

Copy link
Copy Markdown

Description

Jira: ENT-12476 (epic ENT-12470, GDPR learner retirement on the enterprise stack)

When a learner is retired, nothing removed their pathway progress or pathway memberships. Privacy requires this data to be deleted, not kept with a user id (tech spec gap EE-9, Privacy Q2). The on_delete=CASCADE on user doesn't help, because the LMS never deletes the retired auth_user row.

Changes

  • New USER_RETIRE_LMS_CRITICAL receiver handle_learner_retirement, registered through the plugin config like the existing receivers. In one transaction it deletes the learner's:
    • LearnerPathwayProgress rows,
    • then all their history rows (deleting a row writes a final history row, so history goes last),
    • and their LearnerEnterprisePathwayMembership rows.
    • It also blanks the Django admin log entries for those rows (object_repr and change_message; tech spec R3). A membership's object_repr shows the learner's username and would otherwise stay in django_admin_log after the row is deleted. Progress ids come from the history as well, so entries for progress rows already deleted in the admin are covered too. Memberships keep no history, so entries of memberships deleted earlier are matched by the exact start of their text, User: <username>, Pathway UUID: (the LMS replaces the username only after sending the signal, and usernames can't hold a comma, so another learner can't match). The log entries themselves are kept for the audit trail.
    • It matches on user.id, which the signal already sends, so it doesn't depend on any LMS change. It logs only counts and the user id, and a second run finds nothing.
    • Aggregate counts (AC2): this package stores no aggregate or counter. Each progress row's step and pathway status is computed from that learner's own snapshot and course data (LearnerPathwayProgress.update_pathway_progress), and no row refers to another learner's row, so deleting a retired learner's rows doesn't change anyone else's progress (the tests check other learners' rows are untouched). Counts computed elsewhere from these tables (for example reports) drop by that learner, as intended.
  • Retired learners are skipped when pathway data is created. Retirement keeps the auth_user row and the learner's enterprise enrollments, so four paths could add the deleted rows back: the update_all_pathways_progress backfill, the EnterpriseCourseEnrollment post_save receiver, grade updates, and update_existing_pathways_progress. All four now skip users with a UserRetirementRequest (edx-platform keeps those rows after the retirement completes; UserRetirementStatus rows are deleted by the cleanup step). The tests use small stand-ins for the LMS models UserRetirementRequest, RetirementState and UserRetirementStatus in mock_apps. This check is not behind the flag: skipping retired users is always correct, and it costs one indexed lookup. It includes learners in the cooling-off period, which is fine for not creating data. If the LMS retirement models can't be imported, a warning is logged at startup.
  • An update in flight can't bring deleted progress back. update_existing_pathways_progress loads all progress rows, then updates them one by one; a learner retired meanwhile still had their row saved from the stale copy, and a plain save() falls back to INSERT, recreating the row and its history. update_pathway_progress now saves with update_fields, which is an UPDATE only: on a deleted row Django raises DatabaseError instead of inserting. The updater runs each row in its own savepoint, skips (and logs) a row deleted this way, and re-raises any other database error. No lock is needed: the UPDATE either commits before the retirement deletes the row, or finds no row.
  • New management command retire_pathway_data_backlog for learners retired before the receiver is turned on (the receiver only sees new retirements; ENT-12489's backlog command covers only the enterprise services). It finds learners whose retirement has finished (they have a UserRetirementRequest, and their UserRetirementStatus is gone or COMPLETE) who still have pathway progress, history or memberships, and removes them with the same retire_learner_pathway_data as the receiver, one learner per transaction. Learners still in the cooling-off period (PENDING, which can be cancelled) and unfinished retirements are left out; the receiver handles them when their retirement runs. This relies on edx-platform's remove_pending_retirement_request receiver (present on release-ulmo): cancelling a PENDING retirement deletes the status row and, through that receiver, the UserRetirementRequest, so a cancelled learner never looks finished. A retirement that had already passed the LMS step before the flag went on but hasn't finished yet (in progress, errored or aborted) is skipped too. The command logs the skipped learners with pathway data as two counts: those in the cooling-off period (handled by the receiver; in prod this is rarely 0) and those with another unfinished retirement (the only reason to run it again). It reads distinct user ids in the database (default ordering cleared, so a learner's many history rows count once). Dry run by default (logs the number of learners and rows per table); --commit removes; --batch-size (default 100 learners) and --sleep are validated before anything is removed. Logs only counts. Their usernames 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.
  • Kill switch: the receiver is behind the enterprise.retirement_receivers_v2 waffle flag (default off). That is the same flag edx-enterprise defines for its retirement receivers (feat: retire pending invites on learner retirement (ENT-12474) openedx/edx-enterprise#2749), so one flag turns all the enterprise retirement changes on or off. With the flag off, nothing changes.
  • Logs: three existing log lines wrote the learner's email (pathway membership and progress creation); they now write the user id (Privacy Q8 puts logs in scope).
  • PII annotations: LearnerPathwayProgress, its history and LearnerEnterprisePathwayMembership were marked no_pii; they now record that user links the row to a learner and that it is deleted on retirement.
  • Version 2.2.0 and changelog.

No row holds free text or an email, so there is nothing to blank before deleting. Copies already in the data warehouse are handled by Data Engineering's warehouse work in the same epic (ENT-12490).

Testing

  • The existing tests for the enrollment receiver (test_signals.py) and a grade update (test_utilities.py) now also run for a retired learner (ddt), who gets no membership or progress and no pathway lookup.
  • New tests/test_retirement.py: the backfill creates nothing for a retired learner (it still does for an active learner); with the flag on, the learner's progress, all its history and their memberships are deleted, and the log holds the user id but not the email; other learners' rows, history and admin log entries are untouched; the admin log entries for the learner's rows (including a progress row already deleted in the admin) are blanked; the plugin config registers the receiver for USER_RETIRE_LMS_CRITICAL with a function name that exists; a membership deleted earlier has its admin log entry blanked through the username, and a learner whose username starts with this one's is untouched; with the flag off nothing changes (rows, history and admin log); a second run deletes nothing.
  • In-flight updates: saving a stale copy of a deleted progress row raises and inserts nothing (no row, no history); update_existing_pathways_progress skips a row deleted after it loaded it (other learners still updated) and a retired learner's rows, and re-raises other database errors. Both race tests fail with the old plain save().
  • New tests/test_retire_pathway_data_backlog.py: the dry run reports per-table counts and the skipped learners as two counts (cooling-off, other unfinished), and removes nothing; --commit removes only the data of learners whose retirement finished (status row gone or COMPLETE), and keeps that of a learner in the cooling-off period (PENDING), an errored retirement and an active learner; a second run finds nothing; sleeps between batches; invalid --batch-size / --sleep (-1, nan, inf) are rejected before anything is removed.
  • All 46 tests pass (24 existing, 2 of them now also run for a retired learner, + 20 new); the new code is fully covered.
  • pylint, pycodestyle, pydocstyle, isort and the PII annotation check pass.

Rollout

  1. Merge and release 2.2.0, then bump learner-pathway-progress in edx/edx-internal (argocd/applications/edxapp-lms/requirements/private_requirements.txt).
  2. Turn on enterprise.retirement_receivers_v2 with Everyone: Yes on stage, retire a test learner, then prod. To roll back, turn the flag off. Use Everyone: Yes, not staff-only or a percentage: the same flag also switches edx-enterprise's scheduled remove_expired_pending_group_memberships job, which has no request and so sees the flag as on only when it is on for everyone.
  3. After the flag is on in prod, run the backlog command:
    1. Run ./manage.py lms retire_pathway_data_backlog (dry run) on stage, check the counts, then run it with --commit there.
    2. Before --commit in prod, check that every retired learner has a UserRetirementRequest (learners retired before that model existed, or through a path that didn't create one, would be missed). First check that prod's RETIRED_EMAIL_FMT is still retired__user_{}@retired.invalid. Then run this on a read replica:
      SELECT COUNT(*) AS retired_style_users,
             SUM(r.user_id IS NOT NULL) AS with_retirement_request,
             SUM(r.user_id IS NULL AND (p.user_id IS NOT NULL OR h.user_id IS NOT NULL OR m.user_id IS NOT NULL))
                 AS missed_with_pathway_data
      FROM auth_user u
      LEFT JOIN user_api_userretirementrequest r ON r.user_id = u.id
      LEFT JOIN (SELECT DISTINCT user_id FROM learner_pathway_progress_learnerpathwayprogress) p ON p.user_id = u.id
      LEFT JOIN (SELECT DISTINCT user_id FROM learner_pathway_progress_historicallearnerpathwayprogress) h ON h.user_id = u.id
      LEFT JOIN (SELECT DISTINCT user_id FROM learner_pathway_progress_learnerenterprisepathwaymembership) m ON m.user_id = u.id
      WHERE u.email LIKE 'retired\_\_user\_%@retired.invalid';
      If missed_with_pathway_data is above 0, those learners are a known gap, to be noted here.
    3. Run the dry run in prod, check the counts, then run it with --commit. It is safe to run again.
    4. The log ends with two skipped counts. The cooling-off count is handled by the receiver and will rarely be 0; ignore it. If the count of other unfinished retirements is above 0, run the command again once those retirements finish. Errored or aborted retirements stay in that count until someone retries or closes them; aborted ones may never finish.

@sjasti-sonata-svg
sjasti-sonata-svg force-pushed the sjasti/ENT-12476-retire-pathway-progress branch 6 times, most recently from 515141e to 0e9cdce Compare November 30, 2026 07:32
@sjasti-sonata-svg
sjasti-sonata-svg requested a balanced review from Copilot November 30, 2026 12:52

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

An unguarded in-flight progress update can recreate retired learner data and history after cleanup, while the backlog command caches every matching row’s user ID before batching.

2 open issues
What changed in this PR

This PR adds pathway-data cleanup to the LMS learner-retirement process, supporting enterprise privacy requirements and cleanup of previously retired learners.

Changes:

  • Adds a flag-controlled retirement receiver to delete progress, history and memberships, and redact related admin logs.
  • Adds a dry-run-first backlog command and retirement checks in enrollment, grade-update and backfill paths.
  • Adds retirement tests, removes emails from creation logs, updates privacy annotations and releases version 2.2.0.
File Description
tests/​test_retirement.py Tests cleanup, redaction, receiver wiring and retired-user checks.
tests/​test_retire_pathway_data_backlog.py Tests backlog selection, dry runs, deletion and options.
test_settings.py Enables mock retirement models in tests.
mock_apps/​openedx/​core/​djangoapps/​user_api/​models.py Defines mock retirement models.
mock_apps/​openedx/​core/​djangoapps/​user_api/​migrations/​0001_initial.py Creates mock retirement tables.
mock_apps/​openedx/​core/​djangoapps/​user_api/​migrations/​__init__.py Initializes the mock migrations package.
mock_apps/​openedx/​core/​djangoapps/​user_api/​__init__.py Initializes the mock user API package.
learner_pathway_progress/​waffle.py Defines the shared retirement kill switch.
learner_pathway_progress/​utilities.py Adds retirement queries and guards; removes email logging.
learner_pathway_progress/​signals.py Implements cleanup, admin-log redaction and the receiver.
learner_pathway_progress/​models.py Corrects model privacy annotations.
learner_pathway_progress/​management/​commands/​retire_pathway_data_backlog.py Adds batched cleanup for completed retirements.
learner_pathway_progress/​apps.py Registers the LMS retirement receiver.
learner_pathway_progress/​__init__.py Bumps the version to 2.2.0.
CHANGELOG.rst Documents the release changes.
.annotation_safe_list.yml Corrects the history model’s privacy annotations.

Review effort: Balanced

)
)
# 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.

"""
Return the sorted ids of the users who have rows in any of ``tables``.
"""
return sorted(set().union(*(rows.values_list('user_id', flat=True) for rows in tables.values())))

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.

Privacy requires a retired learner's pathway progress to be deleted,
not kept with a user id (ENT-12470 tech spec EE-9, Privacy Q2). Nothing
removed it on retirement.

Add a USER_RETIRE_LMS_CRITICAL receiver, registered through the plugin
config, that deletes the learner's LearnerPathwayProgress rows, then
all their history (the delete writes a final history row), and their
LearnerEnterprisePathwayMembership rows, in one transaction. It also
blanks the Django admin log entries for those rows (tech spec R3),
because a membership's object_repr shows the username; entries of
memberships deleted earlier are matched by the exact start of that
text. It is behind the enterprise.retirement_receivers_v2 waffle flag,
the kill switch shared with edx-enterprise's retirement receivers, and
logs only counts and the user id.

Add the retire_pathway_data_backlog management command for learners
whose retirement finished before the receiver is turned on (status row
gone or COMPLETE). Learners still in the cooling-off period, who can
cancel, are left alone. It removes the data through the same function
and is a dry run unless --commit is passed.

Retirement keeps the user row and their enterprise enrollments, so the
backfill, the enrollment receiver, grade updates and the existing
progress updater now skip users with a UserRetirementRequest, or they
would add the deleted rows back. Progress updates save with
update_fields, an UPDATE only, so an update that loaded a row before
retirement deleted it cannot insert it again.

Also log the user id instead of the learner's email in the pathway
membership and progress logs, and annotate the progress, history and
membership tables as holding a learner id. Bump to 2.2.0.
@sjasti-sonata-svg
sjasti-sonata-svg force-pushed the sjasti/ENT-12476-retire-pathway-progress branch from 6a29185 to 76c3076 Compare December 4, 2026 14:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants