prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Race condition between API & Worker containers that updates fixtures on start
  ## Expected Behavior
  
  Containers should start without any issues.
  
  ## Actual Behavior
  
  Any of these two containers may fail to start due to unexpected exceptions while applying fixtures.
  
  ## Steps to Reproduce the Problem
  
    1. Run `docker-compose up`.
    2. Be lucky.
  
  ## Additional comment
  
  Both of these containers start script for applying fixtures. Maybe only one should do it (preferrably API)? Maybe this script should be better protected for errors?
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `backend/medtagger/database/fixtures.py`
  Content:
  ```
  1 """Insert all database fixtures."""
  2 import logging.config
  3 
  4 from sqlalchemy import exists
  5 
  6 from medtagger.database import db_session
  7 from medtagger.database.models import ScanCategory, Role
  8 
  9 logging.config.fileConfig('logging.conf')
  10 logger = logging.getLogger(__name__)
  11 
  12 CATEGORIES = [{
  13     'key': 'KIDNEYS',
  14     'name': 'Kidneys',
  15     'image_path': '../../../assets/icon/kidneys_category_icon.svg',
  16 }, {
  17     'key': 'LIVER',
  18     'name': 'Liver',
  19     'image_path': '../../../assets/icon/liver_category_icon.svg',
  20 }, {
  21     'key': 'HEART',
  22     'name': 'Hearth',
  23     'image_path': '../../../assets/icon/heart_category_icon.svg',
  24 }, {
  25     'key': 'LUNGS',
  26     'name': 'Lungs',
  27     'image_path': '../../../assets/icon/lungs_category_icon.svg',
  28 }]
  29 
  30 ROLES = [
  31     {
  32         'name': 'admin',
  33     },
  34     {
  35         'name': 'doctor',
  36     },
  37     {
  38         'name': 'volunteer',
  39     },
  40 ]
  41 
  42 
  43 def insert_scan_categories() -> None:
  44     """Insert all default Scan Categories if don't exist."""
  45     with db_session() as session:
  46         for row in CATEGORIES:
  47             category_key = row.get('key', '')
  48             category_exists = session.query(exists().where(ScanCategory.key == category_key)).scalar()
  49             if category_exists:
  50                 logger.info('Scan Category exists with key "%s"', category_key)
  51                 continue
  52 
  53             category = ScanCategory(**row)
  54             session.add(category)
  55             logger.info('Scan Category added for key "%s"', category_key)
  56 
  57 
  58 def insert_user_roles() -> None:
  59     """Insert default user Roles."""
  60     with db_session() as session:
  61         for row in ROLES:
  62             role_name = row.get('name', '')
  63             role_exists = session.query(exists().where(Role.name == role_name)).scalar()
  64             if role_exists:
  65                 logger.info('Role exists with name "%s"', role_name)
  66                 continue
  67 
  68             role = Role(**row)
  69             session.add(role)
  70             logger.info('Role added for name "%s"', role_name)
  71 
  72 
  73 def apply_all_fixtures() -> None:
  74     """Apply all available fixtures."""
  75     logger.info('Applying fixtures for Scan Categories...')
  76     insert_scan_categories()
  77     logger.info('Applying fixtures for user Roles...')
  78     insert_user_roles()
  79 
  80 
  81 if __name__ == '__main__':
  82     apply_all_fixtures()
  83
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/backend/medtagger/database/fixtures.py b/backend/medtagger/database/fixtures.py
  --- a/backend/medtagger/database/fixtures.py
  +++ b/backend/medtagger/database/fixtures.py
  @@ -2,6 +2,7 @@
   import logging.config
   
   from sqlalchemy import exists
  +from sqlalchemy.exc import IntegrityError
   
   from medtagger.database import db_session
   from medtagger.database.models import ScanCategory, Role
  @@ -79,4 +80,8 @@
   
   
   if __name__ == '__main__':
  -    apply_all_fixtures()
  +    try:
  +        apply_all_fixtures()
  +    except IntegrityError:
  +        logger.error('An error occurred while applying fixtures! It is highly possible that there was'
  +                     'a race condition between multiple processes applying fixtures at the same time.')
  
verification_info: {"golden_diff": "diff --git a/backend/medtagger/database/fixtures.py b/backend/medtagger/database/fixtures.py\n--- a/backend/medtagger/database/fixtures.py\n+++ b/backend/medtagger/database/fixtures.py\n@@ -2,6 +2,7 @@\n import logging.config\n \n from sqlalchemy import exists\n+from sqlalchemy.exc import IntegrityError\n \n from medtagger.database import db_session\n from medtagger.database.models import ScanCategory, Role\n@@ -79,4 +80,8 @@\n \n \n if __name__ == '__main__':\n-    apply_all_fixtures()\n+    try:\n+        apply_all_fixtures()\n+    except IntegrityError:\n+        logger.error('An error occurred while applying fixtures! It is highly possible that there was'\n+                     'a race condition between multiple processes applying fixtures at the same time.')\n", "issue": "Race condition between API & Worker containers that updates fixtures on start\n## Expected Behavior\r\n\r\nContainers should start without any issues.\r\n\r\n## Actual Behavior\r\n\r\nAny of these two containers may fail to start due to unexpected exceptions while applying fixtures.\r\n\r\n## Steps to Reproduce the Problem\r\n\r\n  1. Run `docker-compose up`.\r\n  2. Be lucky.\r\n\r\n## Additional comment\r\n\r\nBoth of these containers start script for applying fixtures. Maybe only one should do it (preferrably API)? Maybe this script should be better protected for errors?\r\n\n", "before_files": [{"content": "\"\"\"Insert all database fixtures.\"\"\"\nimport logging.config\n\nfrom sqlalchemy import exists\n\nfrom medtagger.database import db_session\nfrom medtagger.database.models import ScanCategory, Role\n\nlogging.config.fileConfig('logging.conf')\nlogger = logging.getLogger(__name__)\n\nCATEGORIES = [{\n    'key': 'KIDNEYS',\n    'name': 'Kidneys',\n    'image_path': '../../../assets/icon/kidneys_category_icon.svg',\n}, {\n    'key': 'LIVER',\n    'name': 'Liver',\n    'image_path': '../../../assets/icon/liver_category_icon.svg',\n}, {\n    'key': 'HEART',\n    'name': 'Hearth',\n    'image_path': '../../../assets/icon/heart_category_icon.svg',\n}, {\n    'key': 'LUNGS',\n    'name': 'Lungs',\n    'image_path': '../../../assets/icon/lungs_category_icon.svg',\n}]\n\nROLES = [\n    {\n        'name': 'admin',\n    },\n    {\n        'name': 'doctor',\n    },\n    {\n        'name': 'volunteer',\n    },\n]\n\n\ndef insert_scan_categories() -> None:\n    \"\"\"Insert all default Scan Categories if don't exist.\"\"\"\n    with db_session() as session:\n        for row in CATEGORIES:\n            category_key = row.get('key', '')\n            category_exists = session.query(exists().where(ScanCategory.key == category_key)).scalar()\n            if category_exists:\n                logger.info('Scan Category exists with key \"%s\"', category_key)\n                continue\n\n            category = ScanCategory(**row)\n            session.add(category)\n            logger.info('Scan Category added for key \"%s\"', category_key)\n\n\ndef insert_user_roles() -> None:\n    \"\"\"Insert default user Roles.\"\"\"\n    with db_session() as session:\n        for row in ROLES:\n            role_name = row.get('name', '')\n            role_exists = session.query(exists().where(Role.name == role_name)).scalar()\n            if role_exists:\n                logger.info('Role exists with name \"%s\"', role_name)\n                continue\n\n            role = Role(**row)\n            session.add(role)\n            logger.info('Role added for name \"%s\"', role_name)\n\n\ndef apply_all_fixtures() -> None:\n    \"\"\"Apply all available fixtures.\"\"\"\n    logger.info('Applying fixtures for Scan Categories...')\n    insert_scan_categories()\n    logger.info('Applying fixtures for user Roles...')\n    insert_user_roles()\n\n\nif __name__ == '__main__':\n    apply_all_fixtures()\n", "path": "backend/medtagger/database/fixtures.py"}], "after_files": [{"content": "\"\"\"Insert all database fixtures.\"\"\"\nimport logging.config\n\nfrom sqlalchemy import exists\nfrom sqlalchemy.exc import IntegrityError\n\nfrom medtagger.database import db_session\nfrom medtagger.database.models import ScanCategory, Role\n\nlogging.config.fileConfig('logging.conf')\nlogger = logging.getLogger(__name__)\n\nCATEGORIES = [{\n    'key': 'KIDNEYS',\n    'name': 'Kidneys',\n    'image_path': '../../../assets/icon/kidneys_category_icon.svg',\n}, {\n    'key': 'LIVER',\n    'name': 'Liver',\n    'image_path': '../../../assets/icon/liver_category_icon.svg',\n}, {\n    'key': 'HEART',\n    'name': 'Hearth',\n    'image_path': '../../../assets/icon/heart_category_icon.svg',\n}, {\n    'key': 'LUNGS',\n    'name': 'Lungs',\n    'image_path': '../../../assets/icon/lungs_category_icon.svg',\n}]\n\nROLES = [\n    {\n        'name': 'admin',\n    },\n    {\n        'name': 'doctor',\n    },\n    {\n        'name': 'volunteer',\n    },\n]\n\n\ndef insert_scan_categories() -> None:\n    \"\"\"Insert all default Scan Categories if don't exist.\"\"\"\n    with db_session() as session:\n        for row in CATEGORIES:\n            category_key = row.get('key', '')\n            category_exists = session.query(exists().where(ScanCategory.key == category_key)).scalar()\n            if category_exists:\n                logger.info('Scan Category exists with key \"%s\"', category_key)\n                continue\n\n            category = ScanCategory(**row)\n            session.add(category)\n            logger.info('Scan Category added for key \"%s\"', category_key)\n\n\ndef insert_user_roles() -> None:\n    \"\"\"Insert default user Roles.\"\"\"\n    with db_session() as session:\n        for row in ROLES:\n            role_name = row.get('name', '')\n            role_exists = session.query(exists().where(Role.name == role_name)).scalar()\n            if role_exists:\n                logger.info('Role exists with name \"%s\"', role_name)\n                continue\n\n            role = Role(**row)\n            session.add(role)\n            logger.info('Role added for name \"%s\"', role_name)\n\n\ndef apply_all_fixtures() -> None:\n    \"\"\"Apply all available fixtures.\"\"\"\n    logger.info('Applying fixtures for Scan Categories...')\n    insert_scan_categories()\n    logger.info('Applying fixtures for user Roles...')\n    insert_user_roles()\n\n\nif __name__ == '__main__':\n    try:\n        apply_all_fixtures()\n    except IntegrityError:\n        logger.error('An error occurred while applying fixtures! It is highly possible that there was'\n                     'a race condition between multiple processes applying fixtures at the same time.')\n", "path": "backend/medtagger/database/fixtures.py"}]}