Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/application/serializers/application_chat_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,7 @@ def delete(self, request=None, scope="WORKSPACE", with_valid=True):
row for row in chat_record.improve_paragraph_id_list if str(row) != paragraph_id
]
chat_record.save()
ChatCountSerializer(data={"chat_id": chat_record.chat_id}).update_chat()
o = ParagraphSerializers.Operate(
data={
"workspace_id": workspace_id,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

  1. No is_valid() before use. ChatCountSerializer(data=...) is only deserialization-ready; DRF guarantees validated_data only after is_valid(). If update_chat() reads self.data/validated_data, it will raise AssertionError or 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()
  2. Not atomic with the preceding save(). If update_chat() throws, chat_record is already saved but the count is stale → permanently inconsistent data. Wrap the whole block in transaction.atomic().

  3. Ordering vs. the ParagraphSerializers.Operate call. The counter is refreshed before the actual paragraph deletion. If Operate fails/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).

  4. Races on concurrent deletes. Two concurrent requests can read the same list and produce a lost update / wrong count. Use select_for_update() on the ChatRecord row, and/or compute the count with an aggregate (ChatRecord.objects.filter(...).count() / F() expressions) instead of incremental mutation.

  5. Unconditional update. If paragraph_id was not in improve_paragraph_id_list, save() and update_chat() are both wasted work. Compare before/after (or use if paragraph_id in list) and skip.

  6. save() without update_fields. Writes every column, may clobber concurrent changes and is slower:

    chat_record.save(update_fields=["improve_paragraph_id_list"])

🟠 Design / code smell

  1. 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 a ChatCount model/manager method, e.g. ChatCountService.recalculate(chat_id=...).

  2. 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.

  3. 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 hit DoesNotExist or write a 0 count for an object that's about to be deleted. Confirm the intended semantics.

  4. Stale count semantics. If update_chat() recomputes from the Paragraph table, it may run before Operate deleted the paragraph → off-by-one. If it recomputes from improve_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_id implies mixed str/UUID types in improve_paragraph_id_list — worth normalizing that field's type to avoid repeated str() casts.
  • Add a test asserting the counter equals the number of paragraphs after a partial/failed delete, to catch ordering bugs.

Expand Down
Loading