Repository navigation
fix: the count in the application's annotation list is not updated after deletion - #8228
Conversation
| ChatCountSerializer(data={"chat_id": chat_record.chat_id}).update_chat() | ||
| o = ParagraphSerializers.Operate( | ||
| data={ | ||
| "workspace_id": workspace_id, |
There was a problem hiding this comment.
Review of the diff
chat_record.save()
+ ChatCountSerializer(data={"chat_id": chat_record.chat_id}).update_chat()
o = ParagraphSerializers.Operate(data={...})🔴 Correctness / data-consistency issues
-
No
is_valid()before use.ChatCountSerializer(data=...)is only deserialization-ready; DRF guaranteesvalidated_dataonly afteris_valid(). Ifupdate_chat()readsself.data/validated_data, it will raiseAssertionErroror silently use empty data. Either validate explicitly, or (better) don't use a serializer for a side effect:s = ChatCountSerializer(data={"chat_id": chat_record.chat_id}) s.is_valid(raise_exception=True) s.update_chat()
-
Not atomic with the preceding
save(). Ifupdate_chat()throws,chat_recordis already saved but the count is stale → permanently inconsistent data. Wrap the whole block intransaction.atomic(). -
Ordering vs. the
ParagraphSerializers.Operatecall. The counter is refreshed before the actual paragraph deletion. IfOperatefails/raises, the count reflects a state that never happened. Move the count update after the successful delete (or keep both inside the same atomic block). -
Races on concurrent deletes. Two concurrent requests can read the same list and produce a lost update / wrong count. Use
select_for_update()on theChatRecordrow, and/or compute the count with an aggregate (ChatRecord.objects.filter(...).count()/F()expressions) instead of incremental mutation. -
Unconditional update. If
paragraph_idwas not inimprove_paragraph_id_list,save()andupdate_chat()are both wasted work. Compare before/after (or useif paragraph_id in list) and skip. -
save()withoutupdate_fields. Writes every column, may clobber concurrent changes and is slower:chat_record.save(update_fields=["improve_paragraph_id_list"])
🟠 Design / code smell
-
Serializer used as a service.
ChatCountSerializer(...).update_chat()bypasses the serializer contract (validate → create/update). A one-field "data" serializer whose method mutates the DB is surprising for maintainers. Prefer a service/domain function or aChatCountmodel/manager method, e.g.ChatCountService.recalculate(chat_id=...). -
Chained call hides errors.
ChatCountSerializer(...).update_chat()in one line gives no place to log or handle a failure; the caller sees a 500 while the DB is half-updated. -
Edge case — missing chat. If this is the last reference to the chat (e.g. the chat/record is being cleaned up),
update_chat()may hitDoesNotExistor write a0count for an object that's about to be deleted. Confirm the intended semantics. -
Stale count semantics. If
update_chat()recomputes from theParagraphtable, it may run beforeOperatedeleted the paragraph → off-by-one. If it recomputes fromimprove_paragraph_id_list, make that explicit.
🟢 Suggested shape
from django.db import transaction
with transaction.atomic():
chat_record = ChatRecord.objects.select_for_update().get(id=chat_record.id)
old_ids = list(chat_record.improve_paragraph_id_list or [])
new_ids = [r for r in old_ids if str(r) != paragraph_id]
if new_ids != old_ids:
chat_record.improve_paragraph_id_list = new_ids
chat_record.save(update_fields=["improve_paragraph_id_list"])
# Perform the actual paragraph operation first...
o = ParagraphSerializers.Operate(data={...})
o.is_valid(raise_exception=True)
o.delete()
# ...then refresh the counter, only if something really changed.
ChatCountService.recalculate(chat_id=chat_record.chat_id)⚪ Minor
- List comprehension is fine, but
if str(row) != paragraph_idimplies mixedstr/UUIDtypes inimprove_paragraph_id_list— worth normalizing that field's type to avoid repeatedstr()casts. - Add a test asserting the counter equals the number of paragraphs after a partial/failed delete, to catch ordering bugs.
fix: the count in the application's annotation list is not updated after deletion