# Buggy code
async def on_torrents_health(self, _, payload):
    self.logger.info(
        "Received torrent health information for %d random torrents and %d checked torrents",
        len(payload.random_torrents),
        len(payload.torrents_checked),
    )

    all_torrents = payload.random_torrents + payload.torrents_checked

    def _put_health_entries_in_db():
        with db_session:
            for infohash, seeders, leechers, last_check in all_torrents:
                torrent_state = self.metadata_store.TorrentState.get(infohash=infohash)
                if torrent_state and last_check > torrent_state.last_check:
                    # Replace current information
                    torrent_state.seeders = seeders
                    torrent_state.leechers = leechers
                    torrent_state.last_check = last_check
                elif not torrent_state:
                    _ = self.metadata_store.TorrentState(
                        infohash=infohash,
                        seeders=seeders,
                        leechers=leechers,
                        last_check=last_check,
                    )

        self.metadata_store.disconnect_thread()

    await get_event_loop().run_in_executor(None, _put_health_entries_in_db)


# Traceback (pony.orm.core.TransactionIntegrityError)
[PID:9376] 2020-07-21 05:31:34,949 - ERROR <taskmanager:135> PopularityCommunity.done_cb(): Task resulted in error: Object TorrentState[new:9635] cannot be stored in the database. IntegrityError: UNIQUE constraint failed: TorrentState.infohash

Traceback (most recent call last):

File "ipv8\taskmanager.py", line 131, in done_cb

File "src\tribler-core\tribler_core\modules\popularity\popularity_community.py", line 84, in on_torrents_health

File "lib\concurrent\futures\thread.py", line 57, in run

File "src\tribler-core\tribler_core\modules\popularity\popularity_community.py", line 73, in _put_health_entries_in_db

File "lib\site-packages\pony\orm\core.py", line 4001, in get

File "lib\site-packages\pony\orm\core.py", line 4104, in _find_one_

File "lib\site-packages\pony\orm\core.py", line 4163, in _find_in_db_

File "lib\site-packages\pony\orm\core.py", line 942, in _exec_sql

File "lib\site-packages\pony\orm\core.py", line 1810, in prepare_connection_for_query_execution

File "lib\site-packages\pony\orm\core.py", line 1896, in flush

File "lib\site-packages\pony\orm\core.py", line 5420, in _save_

File "lib\site-packages\pony\orm\core.py", line 5262, in _save_created_

File "lib\site-packages\pony\utils\utils.py", line 106, in throw

pony.orm.core.TransactionIntegrityError: Object TorrentState[new:9635] cannot be stored in the database. IntegrityError: UNIQUE constraint failed: TorrentState.infohash

# Fixed code
async def on_torrents_health(self, _, payload):
    self.logger.info(
        "Received torrent health information for %d random torrents and %d checked torrents",
        len(payload.random_torrents),
        len(payload.torrents_checked),
    )

    all_torrents = payload.random_torrents + payload.torrents_checked

    def _put_health_entries_in_db():
        with db_session(immediate=True):
            for infohash, seeders, leechers, last_check in all_torrents:
                torrent_state = self.metadata_store.TorrentState.get(infohash=infohash)
                if torrent_state and last_check > torrent_state.last_check:
                    # Replace current information
                    torrent_state.seeders = seeders
                    torrent_state.leechers = leechers
                    torrent_state.last_check = last_check
                elif not torrent_state:
                    _ = self.metadata_store.TorrentState(
                        infohash=infohash,
                        seeders=seeders,
                        leechers=leechers,
                        last_check=last_check,
                    )

        self.metadata_store.disconnect_thread()

    await get_event_loop().run_in_executor(None, _put_health_entries_in_db)