@@ -602,18 +602,12 @@ export class AssistantService {
602602 }
603603
604604 /**
605- * Perform optimistic assistant update with rollback on failure
605+ * Perform assistant update with database-first approach
606+ *
607+ * Sequence: Database Transaction → Cache Update → Notify Subscribers
608+ * This prevents race conditions with dual database connections
606609 */
607610 private async performAssistantUpdate ( assistantId : string , updates : Partial < Omit < Assistant , 'id' > > ) : Promise < void > {
608- // Save old data for rollback
609- const oldSystemAssistant = this . systemAssistantsCache . get ( assistantId )
610- ? { ...this . systemAssistantsCache . get ( assistantId ) ! }
611- : null
612- const oldLRUAssistant = this . assistantCache . get ( assistantId ) ? { ...this . assistantCache . get ( assistantId ) ! } : null
613- const oldAllAssistant = this . allAssistantsCache . get ( assistantId )
614- ? { ...this . allAssistantsCache . get ( assistantId ) ! }
615- : null
616-
617611 try {
618612 // Fetch current assistant data
619613 let currentAssistantData : Assistant
@@ -639,44 +633,21 @@ export class AssistantService {
639633 id : assistantId
640634 }
641635
642- // Optimistic update: update all caches
636+ // Persist to database FIRST (before any cache updates or notifications)
637+ await assistantDatabase . upsertAssistants ( [ updatedAssistant ] )
638+
639+ // Update caches after successful database operation
643640 this . updateAssistantInCache ( assistantId , updatedAssistant )
644641
645- // Notify subscribers (UI updates immediately)
642+ // Notify subscribers after database and cache are in sync
646643 this . notifyAssistantSubscribers ( assistantId )
647-
648- // Persist to database
649- await assistantDatabase . upsertAssistants ( [ updatedAssistant ] )
650-
651- // Notify other subscribers
652644 this . notifyGlobalSubscribers ( )
653645 this . notifyAllAssistantsSubscribers ( )
654646
655647 logger . debug ( `Assistant updated successfully: ${ assistantId } ` )
656648 } catch ( error ) {
657- // Rollback on failure
658- logger . error ( 'Failed to update assistant, rolling back:' , error as Error )
659-
660- if ( oldSystemAssistant ) {
661- this . systemAssistantsCache . set ( assistantId , oldSystemAssistant )
662- } else {
663- this . systemAssistantsCache . delete ( assistantId )
664- }
665-
666- if ( oldLRUAssistant ) {
667- this . assistantCache . set ( assistantId , oldLRUAssistant )
668- } else {
669- this . assistantCache . delete ( assistantId )
670- }
671-
672- if ( oldAllAssistant ) {
673- this . allAssistantsCache . set ( assistantId , oldAllAssistant )
674- } else {
675- this . allAssistantsCache . delete ( assistantId )
676- }
677-
678- this . notifyAssistantSubscribers ( assistantId )
679-
649+ // No rollback needed since we didn't update caches before transaction
650+ logger . error ( 'Failed to update assistant:' , error as Error )
680651 throw error
681652 }
682653 }
0 commit comments