From 66e3f754aa7bf39d0884cba6871aef917721bb15 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Simon=20K=C3=BCnzel?= <simonk@fsmpi.rwth-aachen.de>
Date: Tue, 29 Apr 2025 20:44:05 +0200
Subject: [PATCH] Improve transaction conflict handling

---
 common_py/src/videoag_common/database/database.py | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/common_py/src/videoag_common/database/database.py b/common_py/src/videoag_common/database/database.py
index 419c458..9b36249 100644
--- a/common_py/src/videoag_common/database/database.py
+++ b/common_py/src/videoag_common/database/database.py
@@ -1,5 +1,7 @@
 import os
+import random
 import sys
+import time
 from enum import StrEnum
 from typing import Callable, TypeVar, TypeVarTuple, Sequence
 
@@ -218,6 +220,9 @@ class Database:
                 if attempts >= (self._max_write_attempts if writeable else self._max_read_attempts):
                     self._on_transaction_aborted_after_repeated_conflict(writeable)
                     raise TransactionConflictError(e)
+                # Sleep a random time for up to 500ms to increase chance that next attempt succeeds (The randomness makes
+                # it more likely that we reattempt at a different time than the one with which we are in conflict right now)
+                time.sleep(random.random() / 2)
                 continue
                 
         raise AssertionError("This should be unreachable code")
-- 
GitLab