@@ -233,6 +233,25 @@ async def delete_automation(
233233 if not automation :
234234 return False
235235
236+ # Delete child tables in a consistent order to prevent deadlocks
237+ # when multiple automations are deleted concurrently
238+ await session .execute (
239+ sa .delete (db .AutomationBucket ).where (
240+ db .AutomationBucket .automation_id == automation_id ,
241+ )
242+ )
243+ await session .execute (
244+ sa .delete (db .AutomationRelatedResource ).where (
245+ db .AutomationRelatedResource .automation_id == automation_id ,
246+ )
247+ )
248+ await session .execute (
249+ sa .delete (db .CompositeTriggerChildFiring ).where (
250+ db .CompositeTriggerChildFiring .automation_id == automation_id ,
251+ )
252+ )
253+
254+ # Now delete the parent automation
236255 await session .execute (
237256 sa .delete (db .Automation ).where (
238257 db .Automation .id == automation_id ,
@@ -252,6 +271,14 @@ async def delete_automations_for_workspace(
252271 automations = await read_automations_for_workspace (
253272 session ,
254273 )
274+
275+ # Delete child tables in a consistent order to prevent deadlocks
276+ # when multiple workspace deletions occur concurrently
277+ await session .execute (sa .delete (db .AutomationBucket ))
278+ await session .execute (sa .delete (db .AutomationRelatedResource ))
279+ await session .execute (sa .delete (db .CompositeTriggerChildFiring ))
280+
281+ # Now delete all automations
255282 result = await session .execute (sa .delete (db .Automation ))
256283 for automation in automations :
257284 await _notify (session , automation , "deleted" )
0 commit comments