Skip to content

feat: archive deletion-locked object tags instead of deleting them - #3

Open
tbain wants to merge 10 commits into
tbain/777_deletion_lock_apifrom
tbain/779_archive_locked_object_tag_deletes
Open

tbain wants to merge 10 commits into
tbain/777_deletion_lock_apifrom
tbain/779_archive_locked_object_tag_deletes

Conversation

@tbain

@tbain tbain commented Oct 21, 2026 •

Copy link
Copy Markdown
Owner

Description

An object tag is one ObjectTag row: it links one object to one tag, or to a free-text value. This PR makes every delete of an object tag that is locked against deletion (deletion_locked=True) archive the row instead of removing it, so learner mastery recorded against it still has a row to point at. An object tag that is not locked is deleted exactly as before. Nothing sets the lock until openedx#782, so there is no visible change yet.

What changed

Deleting. The archive-or-delete decision lives in ObjectTagQuerySet.delete() and ObjectTag.delete() (src/openedx_tagging/models/base.py), so every caller follows it without changes: tag_object(), delete_object_tags(), copy_tags(), and any other ORM delete.

  • The queryset delete locks the rows (SELECT ... FOR UPDATE), archives the deletion-locked ones, and deletes the rest with Django's own delete. The row lock is needed because CompetencyCriterion cascades from ObjectTag, so Django reads the rows and then deletes them by primary key; a deletion_locked=False filter would only be checked at read time. With the lock, a concurrent lock_object_tags_for_deletion() call waits, then finds an unlocked row gone and raises DoesNotExist.
  • Archived rows are counted as deleted in the (count, {label: count}) result, and REST responses are unchanged, so a caller can't tell which happened.
  • The lock, archive, and delete run on the write database.
  • tag_object() removes omitted object tags with one queryset delete instead of one delete() per row.

Applying a tag again. When tag_object() or copy_tags() applies a tag whose object tag is archived, the same row is restored (un-archived) instead of a second row being created. Its deletion_locked stays set, so the learner history attached to it comes back with it.

  • A tag from the taxonomy finds its existing row by tag_id. A free-text value, or a value with no matching tag, finds its row by value, and the database decides equality with the _value column's collation, so the result always agrees with the unique constraint.
  • A row restored by tag_object() stops being marked as copied (is_copied=False). Otherwise Studio could not delete it and the next library sync would archive it again.
  • A restored row takes the newly applied spelling of the value, in both tag_object() and copy_tags().
  • Existing rows are saved with only the columns that changed, so a deletion lock committed after the row was read is not overwritten.

Other.

  • The tag limit (OBJECT_MAX_TAGS) counts only object tags that are not archived.
  • lock_object_tags_for_deletion() documents that it must be called before writing rows that reference the object tag, so a concurrent delete and the lock cannot deadlock.
  • The ObjectTag class docstring records that delete() on this model can archive.

Choices that differ from the ticket

The ticket suggests This PR Why
Read the lock through openedx#777's query function Read deletion_locked directly openedx#777 only answers per tag and per taxonomy. The decision is also in models/base.py, which can't import api.py.
Use openedx#778's opt-out to see archived rows No opt-out needed openedx#778 kept archived rows in the default manager and made hiding them opt-in, through .unarchived().
A test that the unique constraint is unchanged Not added Changing the constraint would need a new migration, which would be visible in review.
Check resync_object_tags() No change here It saves every column of a resynced row, including archived. openedx#780 changes it to save only the columns it changed.

Who is affected

Supporting information

Testing instructions

Automated:

  1. The tests for this change (26 cases):

    pytest --no-cov \
      tests/openedx_tagging/test_api.py::TestArchiveLockedObjectTags \
      tests/openedx_tagging/test_models.py::TestObjectTagDelete \
      tests/openedx_tagging/test_views.py::TestObjectTagViewSet::test_tag_object_clear_locked_tag_looks_the_same \
      tests/openedx_learning/applets/cbe/test_criterion_object_tag_archive.py
  2. The full tagging and learning suites: pytest --no-cov tests/openedx_tagging tests/openedx_learning.

  3. pylint, mypy --show-traceback, pycodestyle, pydocstyle src, isort --check-only, and lint-imports.

Manual, in a Django shell (python manage.py shell). Nothing in the product sets deletion_locked yet, so these steps lock an object tag directly. They create rows in your dev database.

from openedx_tagging import api
from openedx_tagging.models import ObjectTag

taxonomy = api.create_taxonomy("Archive demo", allow_multiple=True)
api.add_tag_to_taxonomy(taxonomy, "Kept")
api.add_tag_to_taxonomy(taxonomy, "Dropped")
api.tag_object("demo-block", taxonomy, ["Kept", "Dropped"])
kept = ObjectTag.objects.get(object_id="demo-block", _value="Kept")
api.lock_object_tags_for_deletion(kept.pk)

api.tag_object("demo-block", taxonomy, [])
ObjectTag.objects.filter(object_id="demo-block").values_list("_value", "archived")
# <ObjectTagQuerySet [('Kept', True)]>: the locked row is archived, the other is gone
list(api.get_object_tags("demo-block"))   # []

api.tag_object("demo-block", taxonomy, ["Kept"])
ObjectTag.objects.get(object_id="demo-block").pk == kept.pk   # True, and archived is False again

api.delete_object_tags("demo-block")
ObjectTag.objects.get(pk=kept.pk).archived   # True

Deadline

None.

Other information

  • No model field changes, no migrations, and no new dependencies.
  • Known gaps:
    • Raw SQL bypasses the archiving.
    • The Django admin's delete confirmation page is built before any delete runs, so it doesn't know about archiving. It refuses to delete a deletion-locked object tag whose criterion has a learner status, and for a locked one without a status it lists the criteria as deleted although they are kept.
    • No test runs two transactions at once, and SQLite ignores row locks, so the lock ordering is verified by reasoning only. CI is set up to run the suite on MySQL 8, where the FOR UPDATE queries execute, but it has not run on this PR yet.
    • ObjectTagQuerySet.delete() no longer mirrors Django's refusal to delete a sliced, values(), distinct(*fields), or combined queryset. No caller deletes through one.
    • A deletion-locked, archived object tag whose Tag was deleted and then created again without a resync cannot have that tag applied again: the archived row still holds the value in the unique constraint. [BE] Branch tag and taxonomy deletes between archiving and hard delete openedx/openedx-core#780 closes this, because it archives a Tag that has a deletion-locked object tag instead of deleting it.
  • Suggested reading order: ObjectTagQuerySet.delete() and ObjectTag.delete() in models/base.py, then in api.py tag_object() with _find_existing_object_tag(), _restore_existing_object_tag(), and _save_object_tags(), then copy_tags().
  • AI usage: this PR was developed with Claude (Anthropic) in Cowork. Claude Opus 5.5 and Claude Fable 5.2 planned and reviewed the change, and Sonnet sub-agents wrote the code. I reviewed the change and ran the tests and checks locally.

🤖 Generated with Claude Code

@tbain
tbain force-pushed the tbain/777_deletion_lock_api branch from 143afa4 to 3f92aee Compare October 26, 2026 18:32
@tbain
tbain force-pushed the tbain/779_archive_locked_object_tag_deletes branch from c2eed53 to 0631d97 Compare October 26, 2026 19:50
@tbain
tbain force-pushed the tbain/777_deletion_lock_api branch from 3f92aee to 7c3441b Compare October 26, 2026 22:34
@tbain
tbain force-pushed the tbain/779_archive_locked_object_tag_deletes branch from 0631d97 to e3701f2 Compare October 26, 2026 22:34
@jesperhodge

jesperhodge commented Nov 4, 2026 •

Copy link
Copy Markdown

Pretty AI Code Review

Hi @tbain , this is the AI-generated Code Review.
I have not reviewed this yet, which means that some of the points in here may be inaccurate pending human review.
In order to implement fixes for this code review, I recommend triaging each item and verifying that it is a real issue and that the recommended way to fix it makes sense.

Taking action on this is optional for now. You can just wait for me to do the triaging and add my human testing and review before doing anything, but if you want to skip the queue a bit and do a round of triaging and fixing before I do a human review, that is also fine.

@jesperhodge jesperhodge 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.

Hi Tyler, I've spent several hours parsing this code. It's really hard to understand, and a lot of that is just due to the inherent complexity of overwriting for example the queryset delete function.

The _pop_current_tag function on the other hand has some abbreviations, vague variable naming and unclear docstrings. I definitely see some ways to improve this here.

From reading the code, I am satisfied with the delete functionality, even though it is hard to understand. But I haven't fully understood the code in api.py yet.

Could you please go through all of the code and make it as readable as possible? Try to get it to a point where it's all super clear and the code is self-explanatory. I put some comments in api.py to showcase examples of how naming can help, but in base.py we just have to see if we can get this to be readable with refactoring or AI. I'd recommend just finding all common maintainability best practices, going through them and applying them, which hopefully AI can be helpful with.

Then, AI code review found two must fix items that seem important. Please go over the AI code review and address its findings.

I'm posting the AI code review in a comment right below.

Comment thread src/openedx_tagging/models/base.py Outdated
locking_qs = locking_qs.select_for_update(of=("self",))
manager = self.model.objects.using(db)
with transaction.atomic(using=db):
# Lock every row before reading its flag, so that a concurrent lock_object_tags_for_deletion() call waits

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

According to AI:
"The lock comment is wrong
The comment at base.py:122-123 says the concurrent lock call "sees the row archived, rather than racing us and leaving it live." That doesn't match the code. My reading, which I'm fairly confident of but haven't tested against a real database:

The waiting caller sees the row gone, not archived. lock_object_tags_for_deletion() only touches rows that are still unlocked. This method deletes those rows rather than archiving them, so the waiting call finds nothing and raises DoesNotExist.
The race deletes a row rather than leaving one live. Without the lock, the bad outcome is a locked row being deleted.
The comment doesn't justify the lock. It never says why a conditional filter can't do the job, which AGENTS.md requires for any select_for_update()."
AI recommends comment:
" # A model with a cascading foreign key to ObjectTag makes Django read the rows and then delete them
# by primary key, so a deletion_locked=False filter would only be checked at read time. Locking the
# rows first makes a concurrent lock_object_tags_for_deletion() call wait, find the row gone, and
# raise DoesNotExist, instead of locking a row that this transaction then deletes."

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Updated the comment to match what you recommended with the in-situ justification

Comment thread src/openedx_tagging/models/base.py Outdated
Comment on lines +102 to +110
if self.query.combinator:
raise NotSupportedError(f"Calling QuerySet.delete() after {self.query.combinator}() is not supported.")
if self.query.is_sliced:
raise TypeError("Cannot use 'limit' or 'offset' with delete().")
if self.query.distinct_fields:
raise TypeError("Cannot call delete() after .distinct(*fields).")
# django-stubs doesn't declare _fields, which Django's own delete() checks to reject values() and values_list().
if getattr(self, "_fields", None) is not None:
raise TypeError("Cannot call delete() after .values() or .values_list()")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I think this is unnecessary. This code is there to make the delete function throw errors exactly in the same case that the django queryset delete throws - which is if the queryset is in specific states, like being sliced, or something similar.
The only downside to removing this is that in the unlikely case that this were called with one of these querysets, it would archive the locked items and delete the unlocked ones using a fresh queryset, and would not throw an error. And this would deviate from the usual queryset delete behavior. But I don't see any problem with that.
So to simplify, I would recommend deleting this part, but it's up to you.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Yep, removed - thank you for catching that superfluousness

Comment thread src/openedx_tagging/api.py Outdated
:return: ``True`` if an existing association matched, ``False`` if the caller needs to create one.
"""
if tag_id is not None:
matches = [t for t in current_tags if t.tag_id == tag_id]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

What matches what? The naming here is unclear

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Revamped this so this code is broken out into a better self-documenting function with better naming conventions so we're favoring clarity rather than brevity

Comment thread src/openedx_tagging/api.py Outdated
tag_id: int | None = None,
) -> bool:
"""
Find the existing association for a re-applied tag, so it can be reused instead of recreated.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The docstring is unclear. It's pretty low-level but doesn't clearly explain the overall intention and purpose of the function.
For example: association of what to what?
What's a re-applied tag?
What does reusing mean?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Addressed this; made the comment clearer

Comment thread src/openedx_tagging/api.py Outdated
if tag_id is not None:
matches = [t for t in current_tags if t.tag_id == tag_id]
else:
candidates = [t for t in current_tags if t.tag_id is None]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

candidates for what? More naming problems.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Revamped this so this code is broken out into a better self-documenting function with better naming conventions so we're favoring clarity rather than brevity

Comment thread src/openedx_tagging/api.py Outdated
return False
# Only value matches can be ambiguous, and they have no tag, so .value doesn't query for one.
object_tag = matches[0] if tag_id is not None else min(
matches, key=lambda t: (t.value != value, not t.deletion_locked, t.pk)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

avoid lambda functions in code that is already hard to understand.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Removed the lambda

@jesperhodge jesperhodge 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.

Requesting changes: see my comments above.

Also, it's weird that the CI pipeline doesn't run in this PR. Could you please look at https://docs.github.com/en/actions/how-tos/manage-workflow-runs/approve-runs-from-forks and make sure that workflows are allowed and that the CI runs in this PR?

review-for-author.html

@tbain
tbain force-pushed the tbain/777_deletion_lock_api branch from 1228ba8 to ae18010 Compare November 16, 2026 18:38
@tbain
tbain force-pushed the tbain/779_archive_locked_object_tag_deletes branch from dc364e1 to c51d3bf Compare November 16, 2026 18:38
@tbain

tbain commented Nov 17, 2026 •

Copy link
Copy Markdown
Owner Author

@jesperhodge I've pushed changes that address your review and the AI review. You were definitely right on the readability side of things, this was implemented more with a concern and eye towards brevity rather than maintainability and understanding, and it went way too far.

AI Generated Summary below;

Readability

  • api.py: _pop_current_tag() is split into small functions named for what they do:
    • _find_existing_object_tag() finds the row the object already has for a tag or value.
    • _object_tags_with_equal_value() asks the database which stored values are equal.
    • _choose_object_tag_to_keep() picks one row when several have an equal value. This replaces the lambda.
    • _restore_existing_object_tag() un-archives the row and updates its stored spelling.
    • _keep_existing_object_tag() ties these together for the four call sites in tag_object().
  • Vocabulary: the docstrings now use one set of terms. An "object tag" is one ObjectTag row, "existing object tags" are the rows tag_object() loaded for the object, and "restore" means un-archiving a row when its tag is applied again.
  • base.py: ObjectTagQuerySet.delete() uses descriptive names (row_locking_queryset, ids_to_archive, ids_to_delete), and the docstrings are shorter.

Your inline comments

  • Lock comment: replaced. It now says why the row lock is needed (CompetencyCriterion cascades from ObjectTag, so Django reads the rows and deletes them by primary key, and a deletion_locked=False filter would only be checked at read time), and that a waiting lock_object_tags_for_deletion() call finds an unlocked row gone and raises DoesNotExist.
  • Django-parity guards: removed, along with their test. Deleting through a sliced, values(), distinct(*fields) or combined queryset no longer raises. No caller does that.

AI review: must-fix items

Both are fixed, each with a test that fails on the old code.

  1. A row restored by tag_object() is no longer marked as copied, so Studio can delete it and the next library sync leaves it alone.
  2. Existing rows are saved with only the columns that changed, so a deletion lock committed after the row was read is not overwritten.

AI review: "decide" items

Item Outcome
Lock order for openedx#782 lock_object_tags_for_deletion()'s docstring now says to call it before writing rows that reference the object tag.
Archived row whose Tag was deleted and re-created No code change. It is listed as a known limitation in the PR description. openedx#780 closes it by archiving such a Tag instead of deleting it.
Django admin No code change. The confirmation page is built before any delete runs, so it refuses to delete a deletion-locked object tag that has a learner status. The PR description now says this.
Recording that delete() can archive Added a paragraph to the ObjectTag class docstring. A proposed ADR will follow in its own PR.
Spelling on restore copy_tags() now stores the source's spelling, the same as tag_object().

AI review: tests and small items

  • Added tests for instance delete on the write database, the no-taxonomy tag limit, and the lowest-id tie-break.
  • The CBE test now creates a StudentCompetencyCriterionStatus and checks it after archive and after restore.
  • The tie-break's "exact spelling first" term was dead code and is removed.
  • The collation test no longer has the per-vendor expectations.
  • The comments the review flagged are corrected, and the helper call in the no-taxonomy branch is on its own line.
  • The PR description is rewritten in the new vocabulary, with the test counts, the Closes reference and the AI statement corrected.

Not done

Verification

  • pytest tests/openedx_tagging tests/openedx_learning passes locally on SQLite (1389 passed, 10 skipped).
  • pylint, mypy, pycodestyle, pydocstyle, isort and lint-imports are clean.
  • CI Checks: Unable to find any option to enable this, perhaps I don't have the correct permission set? :/

@tbain

tbain commented Nov 17, 2026

Copy link
Copy Markdown
Owner Author

Also, it's weird that the CI pipeline doesn't run in this PR. Could you please look at https://docs.github.com/en/actions/how-tos/manage-workflow-runs/approve-runs-from-forks and make sure that workflows are allowed and that the CI runs in this PR?

review-for-author.html

I'm not seeing an option to enable this, it might be because I don't have full write/merge permissions to the repo to enable it in my fork? The instructions you provided refer to a "Approve workflows to run" option I don't seem to have.

Comment on lines +105 to +109
database_alias = row_locking_queryset.db
if connections[database_alias].features.has_select_for_update_of:
# of=("self",) keeps MySQL and PostgreSQL from also locking the joined Tag and Taxonomy rows, and
# MariaDB doesn't support it.
row_locking_queryset = row_locking_queryset.select_for_update(of=("self",))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Is this multi-db support really desired? We use MySQL in openedx-platform.
Might be a question for @ormsbee

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

There is a plugin that runs the platform in PostgreSQL, and MIT runs their production instances on MariaDB. So consideration should be given to not break those platforms, and any potential breakage is something we should escalate for discussion.

write_database_object_tags = self.model.objects.using(database_alias)

with transaction.atomic(using=database_alias):
deletion_locked_by_id = dict(row_locking_queryset.values_list("pk", "deletion_locked"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Maybe a comment or naming change to explain that deletion_locked is not a db lock but instead a marker that something should be archived

Comment on lines +965 to +966
database_alias = using or router.db_for_write(type(self), instance=self)
this_object_tag = type(self).objects.using(database_alias).filter(pk=self.pk)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Same. I'm not sure if we want the database alias

Comment on lines +955 to +957
A deletion-locked object tag is kept in the database, and ``self.archived`` is set to match. Archiving
is counted as a deletion in the result, so a caller can't tell which of the two happened.

@jesperhodge jesperhodge Nov 18, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggested change
A deletion-locked object tag is kept in the database, and ``self.archived`` is set to match. Archiving
is counted as a deletion in the result, so a caller can't tell which of the two happened.
Archiving is counted as a deletion in the result.

tbain and others added 4 commits November 20, 2026 16:27
Every ObjectTag delete path now archives an association that is locked
against deletion instead of removing it, so learner mastery recorded
against it stays resolvable. Unlocked associations are deleted exactly
as before.

ObjectTagQuerySet.delete() and ObjectTag.delete() carry the branch, so
tag_object(), delete_object_tags(), copy_tags() and direct ORM deletes
all follow it. The queryset delete locks the rows with
select_for_update() before splitting them, so a concurrent lock waits
and then sees the row archived. Archived rows are counted as deleted in
the return value.

Re-applying a tag through tag_object() or copy_tags() un-archives the
same row and leaves deletion_locked unchanged.

Closes openedx#779

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RvKuzWKYPVGRThGKydF2Wf
@tbain
tbain force-pushed the tbain/779_archive_locked_object_tag_deletes branch from 901cbf0 to dcf535a Compare November 20, 2026 16:30
@tbain
tbain force-pushed the tbain/779_archive_locked_object_tag_deletes branch from dcf535a to ee0e973 Compare November 20, 2026 16:34
tbain and others added 3 commits November 20, 2026 20:00
resync_object_tags() saved every column of object tags it had read earlier,
so a deletion lock committed after the read was overwritten with the stale
unlocked value. The save now names only the columns a resync can change.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_016L3xxaptS5fxeFVSSkaUtT
@tbain

tbain commented Nov 20, 2026

Copy link
Copy Markdown
Owner Author

This push adds one fix from the AI review of the stacked PR for openedx#782 (#4, finding G5), with its tests. It is here because the code is in openedx_tagging, next to the matching fix already in _save_object_tags().

Problem. resync_object_tags() saved the full row of instances it had read earlier, so a deletion_locked committed between the read and the save was overwritten with the stale False, with no error. With no argument it loops over every object tag, and it runs after a tag rename and a taxonomy import, so the window is realistic. I reproduced it before the fix.

Fix. The save names only the four columns ObjectTag.resync() can change: src/openedx_tagging/api.py:220-222.

Tests, in tests/openedx_tagging/test_api.py:

Test Fails when
test_resync_object_tags_keeps_a_lock_set_after_the_read The save writes the full row again. It failed before the fix.
test_resync_object_tags_saves_a_renamed_tag_value _value is dropped from the saved columns.
test_resync_object_tags_saves_a_changed_taxonomy_export_id _export_id is dropped from the saved columns.

The last two close a gap the column list opens. Removing each column in turn, the existing suite caught a missing taxonomy or tag but not _value or _export_id; now all four are covered.

Checks. pytest tests/openedx_tagging: 736 pass. Linters are clean. No model, migration or signature change.

Known limit. If ObjectTag.resync() later changes a fifth column, it must be added to this list too; only the tests above guard that.

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.

3 participants