@@ -404,6 +404,9 @@ async def update_chat_by_id(self, id: str, chat: dict, db: AsyncSession | None =
404404
405405 await db .commit ()
406406
407+ new_messages = (chat .get ('history' , {}) or {}).get ('messages' , {}) or {}
408+ await self .reconcile_messages_by_chat_id (id , chat_item .user_id , new_messages )
409+
407410 return ChatModel .model_validate (chat_item )
408411 except Exception :
409412 return None
@@ -501,20 +504,13 @@ async def backfill_messages_by_chat_id(self, chat_id: str, user_id: str, message
501504 async def reconcile_messages_by_chat_id (
502505 self , chat_id : str , user_id : str , messages : dict [str , dict ]
503506 ) -> None :
504- """Sync ``chat_message`` rows with the committed JSON blob .
507+ """Upsert ``chat_message`` rows from the blob; never delete .
505508
506- Upserts current messages via ``backfill_messages_by_chat_id``
507- and deletes orphaned rows whose message_id no longer appears
508- in the blob. Best-effort: errors are logged but never raised.
509+ Diff-based pruning (table − blob) is unsafe: a lost blob write
510+ from a read-modify-write race would drop a still-valid row.
509511 """
510512 try :
511513 await self .backfill_messages_by_chat_id (chat_id , user_id , messages )
512-
513- existing_map = await ChatMessages .get_messages_map_by_chat_id (chat_id )
514- if existing_map is not None :
515- orphaned_ids = set (existing_map .keys ()) - set (messages .keys ())
516- if orphaned_ids :
517- await ChatMessages .delete_message_ids_by_chat_id (chat_id , orphaned_ids )
518514 except Exception as e :
519515 log .warning ('Failed to reconcile chat_message rows for chat %s: %s' , chat_id , e )
520516
0 commit comments