@@ -401,6 +401,9 @@ async def update_chat_by_id(
401401
402402 await session .commit ()
403403
404+ new_messages = (chat .get ('history' , {}) or {}).get ('messages' , {}) or {}
405+ await self .reconcile_messages_by_chat_id (id , chat_item .user_id , new_messages )
406+
404407 return ChatModel .model_validate (chat_item )
405408 except Exception :
406409 return
@@ -496,22 +499,25 @@ async def backfill_messages_by_chat_id(self, chat_id: str, user_id: str, message
496499 log .warning ('Backfill failed for message %s in chat %s: %s' , message_id , chat_id , e )
497500
498501 async def reconcile_messages_by_chat_id (
499- self , chat_id : str , user_id : str , messages : dict [str , dict ]
502+ self , chat_id : str , user_id : str , messages : dict [str , dict ],
503+ * , delete_orphans : bool = False ,
500504 ) -> None :
501505 """Sync ``chat_message`` rows with the committed JSON blob.
502506
503507 Upserts current messages via ``backfill_messages_by_chat_id``
504- and deletes orphaned rows whose message_id no longer appears
505- in the blob. Best-effort: errors are logged but never raised.
508+ and, when *delete_orphans* is True, deletes rows whose
509+ message_id no longer appears in the blob. Best-effort: errors
510+ are logged but never raised.
506511 """
507512 try :
508513 await self .backfill_messages_by_chat_id (chat_id , user_id , messages )
509514
510- existing_map = await ChatMessages .get_messages_map_by_chat_id (chat_id )
511- if existing_map is not None :
512- orphaned_ids = set (existing_map .keys ()) - set (messages .keys ())
513- if orphaned_ids :
514- await ChatMessages .delete_message_ids_by_chat_id (chat_id , orphaned_ids )
515+ if delete_orphans :
516+ existing_map = await ChatMessages .get_messages_map_by_chat_id (chat_id )
517+ if existing_map is not None :
518+ orphaned_ids = set (existing_map .keys ()) - set (messages .keys ())
519+ if orphaned_ids :
520+ await ChatMessages .delete_message_ids_by_chat_id (chat_id , orphaned_ids )
515521 except Exception as e :
516522 log .warning ('Failed to reconcile chat_message rows for chat %s: %s' , chat_id , e )
517523
0 commit comments