Repository navigation
Conversation
143afa4 to
3f92aee
Compare
c2eed53 to
0631d97
Compare
3f92aee to
7c3441b
Compare
0631d97 to
e3701f2
Compare
|
Hi @tbain , this is the AI-generated Code Review. 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. |
e3701f2 to
dc364e1
Compare
572a5d4 to
1228ba8
Compare
jesperhodge
left a comment
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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."
There was a problem hiding this comment.
Updated the comment to match what you recommended with the in-situ justification
| 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()") |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Yep, removed - thank you for catching that superfluousness
| :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] |
There was a problem hiding this comment.
What matches what? The naming here is unclear
There was a problem hiding this comment.
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
| tag_id: int | None = None, | ||
| ) -> bool: | ||
| """ | ||
| Find the existing association for a re-applied tag, so it can be reused instead of recreated. |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Addressed this; made the comment clearer
| 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] |
There was a problem hiding this comment.
candidates for what? More naming problems.
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
avoid lambda functions in code that is already hard to understand.
jesperhodge
left a comment
There was a problem hiding this comment.
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?
1228ba8 to
ae18010
Compare
dc364e1 to
c51d3bf
Compare
|
@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
Your inline comments
AI review: must-fix itemsBoth are fixed, each with a test that fails on the old code.
AI review: "decide" items
AI review: tests and small items
Not done
Verification
|
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. |
| 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",)) |
There was a problem hiding this comment.
Is this multi-db support really desired? We use MySQL in openedx-platform.
Might be a question for @ormsbee
There was a problem hiding this comment.
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")) |
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
Same. I'm not sure if we want the database alias
| 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. | ||
|
|
There was a problem hiding this comment.
| 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. | |
ae18010 to
5dd2a25
Compare
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
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01RvKuzWKYPVGRThGKydF2Wf
901cbf0 to
dcf535a
Compare
dcf535a to
ee0e973
Compare
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
|
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 Problem. Fix. The save names only the four columns Tests, in
The last two close a gap the column list opens. Removing each column in turn, the existing suite caught a missing Checks. Known limit. If |
Description
An object tag is one
ObjectTagrow: 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()andObjectTag.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.SELECT ... FOR UPDATE), archives the deletion-locked ones, and deletes the rest with Django's own delete. The row lock is needed becauseCompetencyCriterioncascades fromObjectTag, so Django reads the rows and then deletes them by primary key; adeletion_locked=Falsefilter would only be checked at read time. With the lock, a concurrentlock_object_tags_for_deletion()call waits, then finds an unlocked row gone and raisesDoesNotExist.(count, {label: count})result, and REST responses are unchanged, so a caller can't tell which happened.tag_object()removes omitted object tags with one queryset delete instead of onedelete()per row.Applying a tag again. When
tag_object()orcopy_tags()applies a tag whose object tag is archived, the same row is restored (un-archived) instead of a second row being created. Itsdeletion_lockedstays set, so the learner history attached to it comes back with it.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_valuecolumn's collation, so the result always agrees with the unique constraint.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.tag_object()andcopy_tags().Other.
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.ObjectTagclass docstring records thatdelete()on this model can archive.Choices that differ from the ticket
deletion_lockeddirectlymodels/base.py, which can't importapi.py..unarchived().resync_object_tags()archived. openedx#780 changes it to save only the columns it changed.Who is affected
ObjectTagcan leave the row in place witharchived=True. Use.unarchived()([BE] Exclude archived tagging records from read paths and block edits to them openedx/openedx-core#778) wherever archived rows should be hidden.Supporting information
tbain/777_deletion_lock_api.Testing instructions
Automated:
The tests for this change (26 cases):
The full tagging and learning suites:
pytest --no-cov tests/openedx_tagging tests/openedx_learning.pylint,mypy --show-traceback,pycodestyle,pydocstyle src,isort --check-only, andlint-imports.Manual, in a Django shell (
python manage.py shell). Nothing in the product setsdeletion_lockedyet, so these steps lock an object tag directly. They create rows in your dev database.Deadline
None.
Other information
ObjectTagQuerySet.delete()no longer mirrors Django's refusal to delete a sliced,values(),distinct(*fields), or combined queryset. No caller deletes through one.Tagwas 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 aTagthat has a deletion-locked object tag instead of deleting it.ObjectTagQuerySet.delete()andObjectTag.delete()inmodels/base.py, then inapi.pytag_object()with_find_existing_object_tag(),_restore_existing_object_tag(), and_save_object_tags(), thencopy_tags().🤖 Generated with Claude Code