Skip to content

feat: archive deletion-locked tags and taxonomies on delete - #6

Open
tbain wants to merge 15 commits into
tbain/779_archive_locked_object_tag_deletesfrom
tbain/780_archive_locked_tag_and_taxonomy_deletes
Open

tbain wants to merge 15 commits into
tbain/779_archive_locked_object_tag_deletesfrom
tbain/780_archive_locked_tag_and_taxonomy_deletes

Conversation

@tbain

@tbain tbain commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Description

Deleting a tag or a taxonomy now archives it (archived=True) when a tag association that is locked against deletion (ObjectTag.deletion_locked=True) depends on it, so learner mastery recorded against that association keeps a tag and a taxonomy to resolve through. Everything else is deleted as before, with the same response. Nothing in production sets the lock until openedx#782 lands, so ordinary deletes behave as they do today.

What changed

  • Tag deletes: Taxonomy.delete_tags(). A tag is archived if it, or any tag beneath it, has a deletion-locked association. Every other requested tag is deleted. Sub-tags are found by parent_id, the relation the cascade follows.
  • Taxonomy deletes: a new api.delete_taxonomy(), called by TaxonomyView.perform_destroy(). The taxonomy is archived if any of its associations is deletion-locked, and deleted otherwise. The archived values of its tags are not changed.
  • Concurrent writes, without select_for_update(). Each delete writes first, then checks inside the same transaction for a concurrent write, and rolls back and tries again, up to three times. A tag delete checks that it deleted as many tags as it read and that no deletion-locked association lost its tag, or, when it only archived, that the same tags are still beneath the ones requested. A taxonomy delete checks that no deletion-locked association lost its taxonomy. If the third attempt still fails its check, delete_tags_from_taxonomy() or delete_taxonomy() raises the new ConcurrentDeleteError (exported from openedx_tagging.api), and both endpoints return it as 409 Conflict. A database refusal is also retried, and is raised unchanged after the third attempt, which either endpoint returns as a 500.
  • lock_object_tags_for_deletion() re-reads the associations it has just locked and raises ObjectTag.DoesNotExist if a tag or taxonomy that was set is gone.
  • Stale saves. resync_object_tags(), tag_object() and Taxonomy.update_tag() now pass update_fields, so saving a row read earlier cannot write a stale deletion_locked=False or archived=False back. resync_object_tags() writes only the columns it changed. update_tag() writes value, lineage, depth, parent, and external_id, then checks archived again and rolls the rename back with a ValueError if the tag was archived meanwhile. All three raise DatabaseError if the row they save was deleted meanwhile, where they used to re-create it; the tag update endpoint returns that as a 500.

Choices that differ from the ticket

The ticket says This PR Why
Nothing about concurrent requests Deletes check after writing and retry A status write can lock an association between a delete's read and its write.
The taxonomy branch goes in perform_destroy() It is in api.delete_taxonomy() AGENTS.md routes all mutation through api.py.
Find sub-tags by lineage Found by parent_id A sub-tag with an out-of-date lineage would be missed and then cascaded.
The "parent with children" refusal is unchanged It counts only unarchived sub-tags, at any depth Archived sub-tags are hidden, so such a parent looks like a leaf. Needs the ticket owner's confirmation.

Supporting information

Testing instructions

  1. The new tests (45 tests, 51 cases):

    pytest --no-cov \
      tests/openedx_tagging/test_models.py::TestTaxonomyDeleteTags \
      tests/openedx_tagging/test_api.py::TestDeleteTaxonomy \
      tests/openedx_learning/applets/cbe/test_tag_and_taxonomy_archive.py
    pytest --no-cov tests/openedx_tagging/test_api.py -k "lock_refuses or lock_accepts or keeps_a_lock or resync_saves or resync_does_not_clear"
    pytest --no-cov tests/openedx_tagging/test_views.py -k "delete_locked or delete_mixed_tags or is_a_conflict"
  2. pytest --no-cov tests/openedx_tagging tests/openedx_learning (1434 pass and 10 are skipped), then pylint, mypy, pycodestyle, isort --check-only, lint-imports, and python manage.py makemigrations --check --dry-run.

Manual, in python manage.py shell (creates rows in your dev database):

from openedx_tagging import api
from openedx_tagging.models import ObjectTag, Tag, Taxonomy

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

api.delete_tags_from_taxonomy(taxonomy, ["Parent"], with_subtags=True)
sorted(Tag.objects.filter(taxonomy=taxonomy).values_list("value", "archived"))
# [('Kept', True), ('Parent', True)]

api.delete_taxonomy(taxonomy)
Taxonomy.objects.get(pk=taxonomy.pk).archived   # True

Other information

  • No model field changes, no migrations, and no new dependencies.
  • Known gaps:
    • Tag.delete(), taxonomy.delete() called directly, the tag import's delete action, and the Django admin still hard-delete. The import's own Tag saves still write full rows.
    • A tag or taxonomy that a learner status points at, but whose association was never locked, still returns a 500 (ProtectedError) from both endpoints. Open question for the ticket owner.
    • An archived tag keeps its value, and an archived taxonomy its export id, so re-creating either fails with "already exists". Open question for the ticket owner.
    • No test runs two transactions at once. The retry paths are tested by making a write appear just before a delete within one connection.
    • The checks after a delete compare the deletion-locked associations that have no tag (or no taxonomy) before and after. They miss an association that was already in that state and was relinked meanwhile, and an unrelated one appearing meanwhile causes a needless retry. The taxonomy check reads every association without a taxonomy in the table, twice per attempt. A check constraint that a deletion-locked association has a taxonomy would replace it, and needs a migration and a decision on whether an association with no taxonomy may be deletion-locked.
    • A database deadlock raises OperationalError, which is not retried. Inside a caller's transaction it rolls that whole transaction back.
    • On PostgreSQL, Django defers foreign key checks to commit. When the caller already holds a transaction, a refused delete then fails at the caller's commit, where nothing retries. PostgreSQL was not run.
  • For the branch of issue 782: one more ObjectTag query when a call newly locks an association, and a new ObjectTag.DoesNotExist case to document.
  • AI usage: developed with Claude (Anthropic), test-first, with independent review passes by Claude and a second model. I reviewed the change and ran the tests locally.

🤖 Generated with Claude Code

tbain and others added 12 commits November 16, 2026 15:15
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 dc364e1 to c51d3bf Compare November 16, 2026 18:38
@tbain
tbain force-pushed the tbain/780_archive_locked_tag_and_taxonomy_deletes branch from feb36b1 to dcaec9a Compare November 16, 2026 20:21
@tbain

tbain commented Nov 16, 2026

Copy link
Copy Markdown
Owner Author

This PR had an extensive self-code review session using our backend-code-review skill with multiple rounds of back and forth. Below is a summary of those rounds over a course of days. If need be I can provide the step-by-step findings and results, but since the review ended up taking so long and being so verbose as a result, a summary seemed more prudent than posting a few days worth of back and forth discourse between two agents and myself.

Summary of self-code review process:

Code review summary

This pull request went through three full AI-assisted code reviews and three shorter re-reviews between 2026-11-13 and 2026-11-16, against the acceptance criteria of openedx#780. The final head, 0fd3a85, is ready to merge from the review's side. Four questions for the ticket owner stay open, and two items are deferred to follow-up issues.

How each review was run

Each full review pinned the head commit, diffed it against the base branch of #3, and read the ticket's acceptance criteria. Six reviewers then ran in parallel: a code locator, a context and prose reviewer, a mechanical checker (lint, types, import contracts, migrations, the description's commands and counts), a test reviewer that broke each guarded line and confirmed a test fails, an architecture reviewer, and an independent reviewer on a model from a different vendor (GPT). Concurrency claims were tested on a throwaway MySQL server at READ COMMITTED with two connections, one paused mid-operation while the other committed a conflicting write, because SQLite cannot show these races. Each written review passed an independent accuracy check before delivery. The re-reviews checked only whether the previous findings were fixed and whether the new commit broke anything.

What each round found and what changed

Round Head Concurrency design at that head Findings that had to be fixed How the next commit answered them
Review 1 6df068e select_for_update() row locks The test file for "the learner's mastery status still resolves" was never committed. A comment called the deletion lock permanent, but resync_object_tags() and tag_object() saved full rows and could overwrite a lock set meanwhile. Two concurrency guards could be removed without a test failing. The file was committed, the two saves pass update_fields, the comment was reworded, and the guards got tests. The row locks were replaced by a write-then-check retry (_retry_on_concurrent_write(), three attempts, ConcurrentDeleteError, HTTP 409 on the tags endpoint).
Review 2 80cb879 Write, check, retry Two races in the taxonomy delete, both reproduced on MySQL: an association created and locked during the delete lost its tag and taxonomy, and an unlocked association added during the delete made the taxonomy archive instead of delete. ConcurrentDeleteError was not importable from openedx_tagging.api. Two guards were untested, two test docstrings were stale, and Taxonomy.update_tag() saved the full row and could un-archive a tag. The taxonomy delete compares the deletion-locked associations that have no taxonomy before and after the delete and retries if a new one appears. The exception is re-exported. Tests and docstrings were added. update_tag() was given update_fields=["value", "lineage"].
Review 3 feb36b1 Same, with the before-and-after orphan check Both races were confirmed fixed. The update_fields list from review 2 was too narrow: a rename racing a tag move wrote a lineage that disagreed with the parent, or failed with MySQL error 3819 (reproduced on MySQL). delete_taxonomy() could raise ConcurrentDeleteError, which was undocumented and reached the client as a 500. Two new lines had no failing test. At this point the review scope was narrowed to these three items only, to stop each round from opening new fronts. update_tag() writes every column except archived. The taxonomy endpoint maps the error to 409, the docstrings and comments were corrected, and the two tests were added.
Re-review 1 dcaec9a Unchanged All three fixed; each fix has a test that fails when it is reverted. The rename fix was re-run on MySQL and the tree stayed consistent. No new findings. The author then chose to fix the deferred nits as well.
Re-review 2 abfccf0 Same mechanism, with three more post-write checks Six of eight deferred nits fixed: a delete that only archives re-collects its subtrees and retries if a sub-tag appeared; resync_object_tags() writes only the columns it changed; update_tag() saves in a transaction and re-checks archived afterwards, rolling the rename back with ValueError; docstrings, tests, and the description were corrected. Each of the three concurrency changes was probed on MySQL with the fix present and removed, and each closed its race. One regression: test_protected_tag_is_not_retried lost delete.assert_called_once(), so retrying a ProtectedError no longer failed any test. The assertion was restored with a comment explaining why the call count is what distinguishes one attempt from three.
Re-review 3 0fd3a85 Unchanged The regression is fixed and the restored assertion fails when ProtectedError is retried. Nothing else changed. Ready to merge.

Closing independent pass

Because the three post-write checks added in abfccf0 had been verified by one reviewer only, an independent reviewer on a different vendor's model ran a final pass on 0fd3a85, limited to those three checks and the invariants the pull request claims. It ran fifteen two-connection probes on MySQL at READ COMMITTED, each with the check under test present and removed. All three checks prevented the failure they target and removing each one reproduced it. The five broader cases (locking, adding, or relinking an association during a tag or taxonomy delete) all kept the locked association's tag and taxonomy. It found no new defect in the pull request. It did show that two overlapping renames, one of a parent tag and one of its child, can commit inconsistent lineage values; the same probe fails with the pre-PR update_tag(), and Tag.save() is unchanged by this pull request, so that is an existing race in the tag tree rather than a regression, and it is recorded below as a follow-up.

Verification at the final head

  • SQLite: pytest tests/openedx_tagging tests/openedx_learning gives 1434 passed and 10 skipped, matching the description.
  • MySQL at READ COMMITTED: the tagging suite passes (770 tests, at abfccf0; the last commit changed only a test file).
  • Every concurrency check added in this pull request has a test that fails when the check is removed, and the three test commands in the description select the 51 cases it says.
  • pylint, pycodestyle, isort, mypy, and lint-imports are clean, makemigrations --check finds nothing, and the branch merges into openedx/main without conflicts.
  • PostgreSQL was never run. The description records the known PostgreSQL difference in deferred foreign key checks.

Still open after the review

Questions that need the ticket owner, not code:

  1. Should a new tag or taxonomy be allowed to reuse the value or export id of one that a delete archived? Today re-creating either fails with "already exists".
  2. What should a delete return when a learner status depends on the tag or taxonomy but no association was ever deletion-locked? Today both endpoints return a 500 from ProtectedError.
  3. Is the narrower "parent with children" refusal acceptable? A parent whose sub-tags are all archived can now be deleted without with_subtags.
  4. Is an architecture decision record for the archiving and retry rules planned?

Deferred to follow-up issues, and listed under "Known gaps" in the description:

  • A database check constraint that a deletion-locked association has a taxonomy, which would replace the table-wide before-and-after check in the taxonomy delete. It needs a migration and a decision on whether an association with no taxonomy may be deletion-locked.
  • A test that runs two transactions at once. The retry paths are currently tested by making a write appear just before a delete within one connection.
  • An existing race in Tag.save(), outside this pull request: when a parent tag and its child are renamed at the same moment, the child can commit a lineage computed from the parent's old name, and the grandchild's lineage keeps the old prefix, while parent and depth stay correct. The database constraints do not catch it because each row's suffix and tab count are still valid. Fixing it needs a revision check on tree writes, not another post-save query.

What the process showed

The reviews converged only after the scope was pinned. The concurrency mechanism was replaced once and tightened twice, and every change to it opened a window that the next MySQL probe found, including one caused by a review recommendation (the narrow update_fields in review 2). Limiting the fourth round to three named fixes, then letting the author address the nits in a separate commit that was probed the same way, is what ended the cycle.

tbain and others added 3 commits November 17, 2026 13:56
…fixing two found implementation issues and various nits
Deleting a tag or a taxonomy archives it when a deletion-locked tag
association depends on it, and deletes it otherwise.

Squashes the seven commits of this branch onto the updated
tbain/779_archive_locked_object_tag_deletes.

Closes openedx#780

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

Copy link
Copy Markdown

Claude and I have not done a full review of this PR yet. This is one note from reviewing openedx#927, left here so it is not lost.

Taxonomy.add_tag does not check archived again after it writes, and update_tag now does. In this PR, update_tag saves the rename inside a transaction, checks in the database whether the tag or its taxonomy was archived meanwhile, and rolls back if so. add_tag is unchanged: it tests self.archived and parent.archived on the objects it already has in memory, then creates the tag. If another request archives the taxonomy or the parent tag between those checks and the create, the new tag is created inside an archived taxonomy or under an archived tag.

This PR is where that becomes possible, because delete_taxonomy() and delete_tags() are the first code that sets archived on a taxonomy or a tag. Please give add_tag the same check after the write that update_tag has, so both behave the same way.

The impact is smaller than it could be, since the new tag is hidden along with the archived taxonomy or parent. CodeRabbit raised it first, as an unverified finding on the code that openedx#940 added: openedx#927 (review)

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