# Buggy code
async def get_profile(self, user_id: str) -> JsonDict:
    target_user = UserID.from_string(user_id)

    if self.hs.is_mine(target_user):
        try:
            displayname = await self.store.get_profile_displayname(
                target_user.localpart
            )
            avatar_url = await self.store.get_profile_avatar_url(target_user.localpart)
        except StoreError as e:
            if e.code == 404:
                raise SynapseError(404, "Profile was not found", Codes.NOT_FOUND)
            raise

        return {"displayname": displayname, "avatar_url": avatar_url}
    else:
        try:
            result = await self.federation.make_query(
                destination=target_user.domain,
                query_type="profile",
                args={"user_id": user_id},
                ignore_backoff=True,
            )
            return result
        except RequestSendFailed as e:
            raise SynapseError(502, "Failed to fetch profile") from e
        except HttpResponseException as e:
            raise e.to_synapse_error()


# Traceback (synapse.api.errors.HttpResponseException)
2020-10-11 14:17:11,057 - synapse.crypto.keyring - 624 - INFO - PUT-394911 - Requesting keys dict_items([('conduit.rs', {'ed25519:vNlc2BKa': 1602425831054})]) from notary server matrix.org
2020-10-11 14:17:11,109 - synapse.http.matrixfederationclient - 204 - INFO - PUT-394911 - {POST-O-111774} [matrix.org] Completed request: 200 OK in 0.05 secs - POST matrix://matrix.org/_matrix/key/v2/query
2020-10-11 14:17:11,127 - synapse.federation.transport.server - 409 - INFO - PUT-394911 - Received txn zfdvFZtVGmJDVVAc from conduit.rs. (PDUs: 1, EDUs: 0)
2020-10-11 14:17:11,136 - synapse.handlers.federation - 185 - INFO - PUT-394911-$rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s - handling received PDU: <FrozenEventV3 event_id='$rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s', type='m.room.message', state_key='None'>
2020-10-11 14:17:11,150 - synapse.handlers.federation - 2383 - INFO - PUT-394911-$rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s - auth_events contains unknown events: {'$-_058VsrZyoyhf3gf2i0Vl-psP3vFV6FKFBhuIG9fGU'}
2020-10-11 14:17:15,041 - synapse.http.matrixfederationclient - 505 - INFO - PUT-394911-$rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s - {GET-O-111775} [conduit.rs] Got response headers: 404 Not Found
2020-10-11 14:17:15,042 - synapse.http.matrixfederationclient - 581 - WARNING - PUT-394911-$rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s - {GET-O-111775} [conduit.rs] Request failed: GET matrix://conduit.rs/_matrix/federation/v1/event_auth/%21xYvNcQPhnkrdUmYczI%3Amatrix.org/%24rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s: HttpResponseException('404: Not Found')
2020-10-11 14:17:15,042 - synapse.handlers.federation - 2426 - ERROR - PUT-394911-$rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s - Failed to get auth chain
Traceback (most recent call last):
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/handlers/federation.py", line 2387, in _update_auth_events_and_context_for_auth
    origin, event.room_id, event.event_id
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/federation/federation_client.py", line 420, in get_event_auth
    res = await self.transport_layer.get_event_auth(destination, room_id, event_id)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/federation/transport/client.py", line 403, in get_event_auth
    content = await self.client.get_json(destination=destination, path=path)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/http/matrixfederationclient.py", line 842, in get_json
    timeout=timeout,
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/http/matrixfederationclient.py", line 292, in _send_request_with_optional_trailing_slash
    response = await self._send_request(request, **send_request_args)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/http/matrixfederationclient.py", line 536, in _send_request
    raise e
synapse.api.errors.HttpResponseException: 404: Not Found
2020-10-11 14:17:15,051 - synapse.handlers.federation - 2447 - INFO - PUT-394911-$rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s - auth_events refers to events which are not in our calculated auth chain: {'$-_058VsrZyoyhf3gf2i0Vl-psP3vFV6FKFBhuIG9fGU'}
2020-10-11 14:17:15,057 - synapse.state - 444 - INFO - PUT-394911-$rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s - Resolving state for !xYvNcQPhnkrdUmYczI:matrix.org with 2 groups
2020-10-11 14:17:15,057 - synapse.handlers.federation - 2487 - INFO - PUT-394911-$rv-7dXW7o3VorMNosgraWlnctJ9qmNpgaw2a0kF9Q2s - After state res: updating auth_events with new state {}
2020-10-11 14:17:15,085 - synapse.state - 533 - INFO - persist_events-4654 - Resolving state for !xYvNcQPhnkrdUmYczI:matrix.org with 3 groups
2020-10-11 14:17:15,086 - synapse.state - 556 - INFO - persist_events-4654 - Resolving conflicted state for '!xYvNcQPhnkrdUmYczI:matrix.org'
2020-10-11 14:17:15,292 - synapse.access.http.8008 - 311 - INFO - PUT-394911 - 2001:16b8:632:1300:5c4b:f9ef:8bf1:a45d - 8008 - {conduit.rs} Processed request: 4.238sec/-0.000sec (0.029sec, 0.007sec) (0.011sec/0.038sec/13) 60B 200 "PUT /_matrix/federation/v1/send/zfdvFZtVGmJDVVAc HTTP/1.0" "-" [3 dbevts]
2020-10-11 14:17:15,705 - synapse.http.matrixfederationclient - 973 - INFO - GET-394937 - {GET-O-111776} [conduit.rs] Completed: 200 OK [169573 bytes] GET matrix://conduit.rs/_matrix/media/r0/download/conduit.rs/5X8noVQpyo70KZ1Cqbn3PuU4ApXC0ZcUn7fpdVNkujeTX5bVSPP9mM3gGFgNk4Qn43bU4DW3PT4mET8MmIHx5ji298sd7LXomd0qqYABwOpbhwCCW7U9Yqj7mhjgx8vZQyZZsZ7bV3E3F4e4m6l0of9tW94nvsAvBvJNFIF8YpsXvefkGFyYueNL5kFDWW8ImgmWIOzHSgxiFUQvL4JdDqqmhmQrI1AMVQFj7OkzidaoKVUSK2l7r0jQL0ADTQ6M?allow_remote=false
2020-10-11 14:17:15,706 - synapse.rest.media.v1.media_repository - 407 - INFO - GET-394937 - Stored remote media in file '/home/sous-synapse/install/media_store/remote_content/conduit.rs/mn/HY/wAvZjpxEADcUaGGLkeKV'
2020-10-11 14:17:15,715 - synapse.http.server - 85 - ERROR - GET-394937 - Failed handle request via 'ThumbnailResource': <XForwardedForRequest at 0x7f712a20a278 method='GET' uri='/_matrix/media/r0/thumbnail/conduit.rs/5X8noVQpyo70KZ1Cqbn3PuU4ApXC0ZcUn7fpdVNkujeTX5bVSPP9mM3gGFgNk4Qn43bU4DW3PT4mET8MmIHx5ji298sd7LXomd0qqYABwOpbhwCCW7U9Yqj7mhjgx8vZQyZZsZ7bV3E3F4e4m6l0of9tW94nvsAvBvJNFIF8YpsXvefkGFyYueNL5kFDWW8ImgmWIOzHSgxiFUQvL4JdDqqmhmQrI1AMVQFj7OkzidaoKVUSK2l7r0jQL0ADTQ6M?width=196&height=196&method=scale&allow_remote=true' clientproto='HTTP/1.0' site=8008>
Traceback (most recent call last):
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/http/server.py", line 230, in _async_render_wrapper
    callback_return = await self._async_render(request)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/http/server.py", line 258, in _async_render
    callback_return = await raw_callback_return
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/rest/media/v1/thumbnail_resource.py", line 70, in _async_render_GET
    request, server_name, media_id, width, height, method, m_type
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/rest/media/v1/thumbnail_resource.py", line 246, in _respond_remote_thumbnail
    media_info = await self.media_repo.get_remote_media_info(server_name, media_id)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/rest/media/v1/media_repository.py", line 278, in get_remote_media_info
    server_name, media_id
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/rest/media/v1/media_repository.py", line 326, in _get_remote_media_impl
    media_info = await self._download_remote_file(server_name, media_id, file_id)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/rest/media/v1/media_repository.py", line 416, in _download_remote_file
    filesystem_id=file_id,
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/storage/databases/main/media_repository.py", line 237, in store_cached_remote_media
    desc="store_cached_remote_media",
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/storage/database.py", line 670, in simple_insert
    await self.runInteraction(desc, self.simple_insert_txn, table, values)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/storage/database.py", line 541, in runInteraction
    **kwargs
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/storage/database.py", line 590, in runWithConnection
    self._db_pool.runWithConnection(inner_func, *args, **kwargs)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/twisted/python/threadpool.py", line 250, in inContext
    result = inContext.theWork()
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/twisted/python/threadpool.py", line 266, in <lambda>
    inContext.theWork = lambda: context.call(ctx, func, *args, **kw)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/twisted/python/context.py", line 122, in callWithContext
    return self.currentContext().callWithContext(ctx, func, *args, **kw)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/twisted/python/context.py", line 85, in callWithContext
    return func(*args,**kw)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/twisted/enterprise/adbapi.py", line 306, in _runWithConnection
    compat.reraise(excValue, excTraceback)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/twisted/python/compat.py", line 464, in reraise
    raise exception.with_traceback(traceback)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/twisted/enterprise/adbapi.py", line 297, in _runWithConnection
    result = func(conn, *args, **kw)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/storage/database.py", line 587, in inner_func
    return func(conn, *args, **kwargs)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/storage/database.py", line 429, in new_transaction
    r = func(cursor, *args, **kwargs)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/storage/database.py", line 691, in simple_insert_txn
    txn.execute(sql, vals)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/storage/database.py", line 212, in execute
    self._do_execute(self.txn.execute, sql, *args)
  File "/home/sous-synapse/install/env/lib/python3.7/site-packages/synapse/storage/database.py", line 238, in _do_execute
    return func(sql, *args)
psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "remote_media_cache_media_origin_media_id_key"
DETAIL:  Key (media_origin, media_id)=(conduit.rs, 5X8noVQpyo70KZ1Cqbn3PuU4ApXC0ZcUn7fpdVNkujeTX5bVSPP9mM3gGFgNk4Qn43bU4DW3PT4mET8MmIHx5ji298sd7LXomd0qqYABwOpbhwCCW7U9Yqj7mhjgx8vZQyZZsZ7bV3E3F4e4m6l0of9tW94nvsAvBvJNFIF8YpsXvefkGFyYueNL5kFDWW8ImgmWIOzHSgxiFUQvL4JdDqqmhmQrI1AMVQFj7OkzidaoKVUSK2l7r0jQL0ADTQ6M) already exists.

2020-10-11 14:17:15,725 - synapse.access.http.8008 - 311 - INFO - GET-394937 - Red.act.ed.IP4 - 8008 - {None} Processed request: 0.335sec/-0.000sec (0.010sec, 0.000sec) (0.002sec/0.010sec/2) 55B 500 "GET /_matrix/media/r0/thumbnail/conduit.rs/5X8noVQpyo70KZ1Cqbn3PuU4ApXC0ZcUn7fpdVNkujeTX5bVSPP9mM3gGFgNk4Qn43bU4DW3PT4mET8MmIHx5ji298sd7LXomd0qqYABwOpbhwCCW7U9Yqj7mhjgx8vZQyZZsZ7bV3E3F4e4m6l0of9tW94nvsAvBvJNFIF8YpsXvefkGFyYueNL5kFDWW8ImgmWIOzHSgxiFUQvL4JdDqqmhmQrI1AMVQFj7OkzidaoKVUSK2l7r0jQL0ADTQ6M?width=196&height=196&method=scale&allow_remote=true HTTP/1.0" "Python/3.8 aiohttp/3.6.2" [0 dbevts]
2020-10-11 14:17:15,770 - synapse.access.http.8008 - 311 - INFO - GET-394940 - Red.act.ed.IP4 - 8008 - {None} Processed request: 0.018sec/-0.000sec (0.002sec, 0.001sec) (0.001sec/0.014sec/2) 322B 404 "GET /_matrix/media/r0/thumbnail/conduit.rs/5X8noVQpyo70KZ1Cqbn3PuU4ApXC0ZcUn7fpdVNkujeTX5bVSPP9mM3gGFgNk4Qn43bU4DW3PT4mET8MmIHx5ji298sd7LXomd0qqYABwOpbhwCCW7U9Yqj7mhjgx8vZQyZZsZ7bV3E3F4e4m6l0of9tW94nvsAvBvJNFIF8YpsXvefkGFyYueNL5kFDWW8ImgmWIOzHSgxiFUQvL4JdDqqmhmQrI1AMVQFj7OkzidaoKVUSK2l7r0jQL0ADTQ6M?width=32&height=32&method=scale&allow_remote=true HTTP/1.0" "Python/3.8 aiohttp/3.6.2" [0 dbevts]
2020-10-11 14:17:15,840 - synapse.http.matrixfederationclient - 505 - INFO - GET-394941 - {GET-O-111777} [conduit.rs] Got response headers: 401 Unauthorized
2020-10-11 14:17:15,841 - synapse.http.matrixfederationclient - 581 - WARNING - GET-394941 - {GET-O-111777} [conduit.rs] Request failed: GET matrix://conduit.rs/_matrix/federation/v1/query/profile?user_id=%40timo%3Aconduit.rs&field=displayname: HttpResponseException('401: Unauthorized')
2020-10-11 14:17:15,841 - synapse.http.server - 76 - INFO - GET-394941 - <XForwardedForRequest at 0x7f7134cee7b8 method='GET' uri='/_matrix/client/r0/profile/@timo:conduit.rs' clientproto='HTTP/1.0' site=8008> SynapseError: 401 - Unauthorized
2020-10-11 14:17:15,842 - synapse.access.http.8008 - 311 - INFO - GET-394941 - Red.act.ed.IP4 - 8008 - {None} Processed request: 0.038sec/-0.000sec (0.010sec, 0.000sec) (0.000sec/0.000sec/0) 46B 401 "GET /_matrix/client/r0/profile/@timo:conduit.rs HTTP/1.0" "Python/3.8 aiohttp/3.6.2" [0 dbevts]
2020-10-11 14:17:15,848 - synapse.access.http.8008 - 311 - INFO - GET-394942 - Red.act.ed.IP4 - 8008 - {None} Processed request: 0.004sec/-0.000sec (0.002sec, 0.000sec) (0.001sec/0.002sec/2) 322B 404 "GET /_matrix/media/r0/thumbnail/conduit.rs/5X8noVQpyo70KZ1Cqbn3PuU4ApXC0ZcUn7fpdVNkujeTX5bVSPP9mM3gGFgNk4Qn43bU4DW3PT4mET8MmIHx5ji298sd7LXomd0qqYABwOpbhwCCW7U9Yqj7mhjgx8vZQyZZsZ7bV3E3F4e4m6l0of9tW94nvsAvBvJNFIF8YpsXvefkGFyYueNL5kFDWW8ImgmWIOzHSgxiFUQvL4JdDqqmhmQrI1AMVQFj7OkzidaoKVUSK2l7r0jQL0ADTQ6M?width=196&height=196&method=scale&allow_remote=true HTTP/1.0" "Python/3.8 aiohttp/3.6.2" [0 dbevts]
2020-10-11 14:17:15,899 - synapse.access.http.8008 - 311 - INFO - GET-394944 - Red.act.ed.IP4 - 8008 - {None} Processed request: 0.006sec/-0.000sec (0.002sec, 0.000sec) (0.001sec/0.003sec/2) 322B 404 "GET /_matrix/media/r0/thumbnail/conduit.rs/5X8noVQpyo70KZ1Cqbn3PuU4ApXC0ZcUn7fpdVNkujeTX5bVSPP9mM3gGFgNk4Qn43bU4DW3PT4mET8MmIHx5ji298sd7LXomd0qqYABwOpbhwCCW7U9Yqj7mhjgx8vZQyZZsZ7bV3E3F4e4m6l0of9tW94nvsAvBvJNFIF8YpsXvefkGFyYueNL5kFDWW8ImgmWIOzHSgxiFUQvL4JdDqqmhmQrI1AMVQFj7OkzidaoKVUSK2l7r0jQL0ADTQ6M?width=32&height=32&method=scale&allow_remote=true HTTP/1.0" "Python/3.8 aiohttp/3.6.2" [0 dbevts]
2020-10-11 14:17:16,042 - synapse.access.http.8008 - 311 - INFO - GET-394945 - Red.act.ed.IP4 - 8008 - {None} Processed request: 0.003sec/-0.000sec (0.002sec, 0.000sec) (0.000sec/0.001sec/2) 322B 404 "GET /_matrix/media/r0/thumbnail/conduit.rs/5X8noVQpyo70KZ1Cqbn3PuU4ApXC0ZcUn7fpdVNkujeTX5bVSPP9mM3gGFgNk4Qn43bU4DW3PT4mET8MmIHx5ji298sd7LXomd0qqYABwOpbhwCCW7U9Yqj7mhjgx8vZQyZZsZ7bV3E3F4e4m6l0of9tW94nvsAvBvJNFIF8YpsXvefkGFyYueNL5kFDWW8ImgmWIOzHSgxiFUQvL4JdDqqmhmQrI1AMVQFj7OkzidaoKVUSK2l7r0jQL0ADTQ6M?width=196&height=196&method=scale&allow_remote=true HTTP/1.0" "Python/3.8 aiohttp/3.6.2" [0 dbevts]
2020-10-11 14:17:16,089 - synapse.access.http.8008 - 311 - INFO - GET-394946 - Red.act.ed.IP4 - 8008 - {None} Processed request: 0.003sec/-0.000sec (0.001sec, 0.000sec) (0.001sec/0.001sec/2) 322B 404 "GET /_matrix/media/r0/thumbnail/conduit.rs/5X8noVQpyo70KZ1Cqbn3PuU4ApXC0ZcUn7fpdVNkujeTX5bVSPP9mM3gGFgNk4Qn43bU4DW3PT4mET8MmIHx5ji298sd7LXomd0qqYABwOpbhwCCW7U9Yqj7mhjgx8vZQyZZsZ7bV3E3F4e4m6l0of9tW94nvsAvBvJNFIF8YpsXvefkGFyYueNL5kFDWW8ImgmWIOzHSgxiFUQvL4JdDqqmhmQrI1AMVQFj7OkzidaoKVUSK2l7r0jQL0ADTQ6M?width=32&height=32&method=scale&allow_remote=true HTTP/1.0" "Python/3.8 aiohttp/3.6.2" [0 dbevts]



# Fixed code
async def get_profile(self, user_id: str) -> JsonDict:
    target_user = UserID.from_string(user_id)

    if self.hs.is_mine(target_user):
        try:
            displayname = await self.store.get_profile_displayname(
                target_user.localpart
            )
            avatar_url = await self.store.get_profile_avatar_url(target_user.localpart)
        except StoreError as e:
            if e.code == 404:
                raise SynapseError(404, "Profile was not found", Codes.NOT_FOUND)
            raise

        return {"displayname": displayname, "avatar_url": avatar_url}
    else:
        try:
            result = await self.federation.make_query(
                destination=target_user.domain,
                query_type="profile",
                args={"user_id": user_id},
                ignore_backoff=True,
            )
            return result
        except RequestSendFailed as e:
            raise SynapseError(502, "Failed to fetch profile") from e
        except HttpResponseException as e:
            if e.code < 500 and e.code != 404:
                # Other codes are not allowed in c2s API
                logger.info("Server replied with wrong response: %s %s", e.code, e.msg)

                raise SynapseError(502, "Failed to fetch profile")
            raise e.to_synapse_error()