# Buggy code
def start(hs: "synapse.server.HomeServer", listeners: Iterable[ListenerConfig]):
    """
    Start a Synapse server or worker.

    Should be called once the reactor is running and (if we're using ACME) the
    TLS certificates are in place.

    Will start the main HTTP listeners and do some other startup tasks, and then
    notify systemd.

    Args:
        hs: homeserver instance
        listeners: Listener configuration ('listeners' in homeserver.yaml)
    """
    try:
        # Set up the SIGHUP machinery.
        if hasattr(signal, "SIGHUP"):

            def handle_sighup(*args, **kwargs):
                # Tell systemd our state, if we're using it. This will silently fail if
                # we're not using systemd.
                sdnotify(b"RELOADING=1")

                for i, args, kwargs in _sighup_callbacks:
                    i(*args, **kwargs)

                sdnotify(b"READY=1")

            signal.signal(signal.SIGHUP, handle_sighup)

            register_sighup(refresh_certificate, hs)

        # Load the certificate from disk.
        refresh_certificate(hs)

        # Start the tracer
        synapse.logging.opentracing.init_tracer(  # type: ignore[attr-defined] # noqa
            hs
        )

        # It is now safe to start your Synapse.
        hs.start_listening(listeners)
        hs.get_datastore().db_pool.start_profiling()
        hs.get_pusherpool().start()

        # Log when we start the shut down process.
        hs.get_reactor().addSystemEventTrigger(
            "before", "shutdown", logger.info, "Shutting down..."
        )

        setup_sentry(hs)
        setup_sdnotify(hs)

        # If background tasks are running on the main process, start collecting the
        # phone home stats.
        if hs.config.run_background_tasks:
            start_phone_stats_home(hs)

        # We now freeze all allocated objects in the hopes that (almost)
        # everything currently allocated are things that will be used for the
        # rest of time. Doing so means less work each GC (hopefully).
        #
        # This only works on Python 3.7
        if sys.version_info >= (3, 7):
            gc.collect()
            gc.freeze()
    except Exception:
        traceback.print_exc(file=sys.stderr)
        reactor = hs.get_reactor()
        if reactor.running:
            reactor.stop()
        sys.exit(1)


# Traceback (RuntimeError)
--- Logging error ---
Traceback (most recent call last):
File "/usr/local/lib/python3.7/logging/__init__.py", line 1038, in emit
self.flush()
File "/usr/local/lib/python3.7/logging/__init__.py", line 1018, in flush
self.stream.flush()
File "/home/synapse/src/synapse/app/_base.py", line 253, in handle_sighup
i(*args, **kwargs)
File "/home/synapse/src/synapse/config/logger.py", line 289, in _reload_logging_config
_load_logging_config(log_config_path)
File "/home/synapse/src/synapse/config/logger.py", line 278, in _load_logging_config
logging.config.dictConfig(log_config)
File "/usr/local/lib/python3.7/logging/config.py", line 799, in dictConfig
dictConfigClass(config).configure()
File "/usr/local/lib/python3.7/logging/config.py", line 535, in configure
_clearExistingHandlers()
File "/usr/local/lib/python3.7/logging/config.py", line 272, in _clearExistingHandlers
logging.shutdown(logging._handlerList[:])
File "/usr/local/lib/python3.7/logging/__init__.py", line 2038, in shutdown
h.flush()
File "/usr/local/lib/python3.7/logging/__init__.py", line 1018, in flush
self.stream.flush()
RuntimeError: reentrant call inside <_io.BufferedWriter name='XXX.log'>
Call stack:
File "/usr/local/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/synapse/src/synapse/app/federation_sender.py", line 24, in <module>
start(sys.argv[1:])
File "/home/synapse/src/synapse/app/generic_worker.py", line 988, in start
_base.start_worker_reactor("synapse-generic-worker", config)
File "/home/synapse/src/synapse/app/_base.py", line 79, in start_worker_reactor
run_command=run_command,
File "/home/synapse/src/synapse/app/_base.py", line 132, in start_reactor
run()
File "/home/synapse/src/synapse/app/_base.py", line 116, in run
run_command()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/base.py", line 1283, in run
self.mainLoop()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/base.py", line 1295, in mainLoop
self.doIteration(t)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/epollreactor.py", line 235, in doPoll
log.callWithLogger(selectable, _drdw, selectable, fd, event)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/python/log.py", line 103, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/python/log.py", line 86, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/python/context.py", line 122, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/python/context.py", line 85, in callWithContext
return func(*args,**kw)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/posixbase.py", line 614, in _doReadOrWrite
why = selectable.doRead()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/tcp.py", line 243, in doRead
return self._dataReceived(data)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/tcp.py", line 249, in _dataReceived
rval = self.protocol.dataReceived(data)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/endpoints.py", line 132, in dataReceived
return self._wrappedProtocol.dataReceived(data)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/protocols/tls.py", line 330, in dataReceived
self._flushReceiveBIO()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/protocols/tls.py", line 295, in _flushReceiveBIO
ProtocolWrapper.dataReceived(self, bytes)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/protocols/policies.py", line 120, in dataReceived
self.wrappedProtocol.dataReceived(data)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 1693, in dataReceived
self._parser.dataReceived(bytes)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 391, in dataReceived
HTTPParser.dataReceived(self, data)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/protocols/basic.py", line 579, in dataReceived
why = self.rawDataReceived(data)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 304, in rawDataReceived
self.bodyDecoder.dataReceived(data)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/http.py", line 1889, in dataReceived
data = getattr(self, '_dataReceived_%s' % (self.state,))(data)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/http.py", line 1857, in _dataReceived_TRAILER
self.finishCallback(data)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 456, in _finished
self.finisher(rest)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 1050, in dispatcher
return func(*args, **kwargs)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 1647, in _finishResponse_WAITING
self._disconnectParser(reason)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 1673, in _disconnectParser
parser.connectionLost(reason)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 567, in connectionLost
self.response._bodyDataFinished()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 1050, in dispatcher
return func(*args, **kwargs)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/web/_newclient.py", line 1306, in _bodyDataFinished_CONNECTED
self._bodyProtocol.connectionLost(reason)
File "/home/synapse/env-py37/lib/python3.7/site-packages/treq/content.py", line 39, in connectionLost
self.finished.callback(None)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 460, in callback
self._startRunCallbacks(result)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 568, in _startRunCallbacks
self._runCallbacks()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/home/synapse/src/synapse/util/async_helpers.py", line 517, in success_cb
new_d.callback(val)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 460, in callback
self._startRunCallbacks(result)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 568, in _startRunCallbacks
self._runCallbacks()
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 1475, in gotResult
_inlineCallbacks(r, g, status)
File "/home/synapse/env-py37/lib/python3.7/site-packages/twisted/internet/defer.py", line 1418, in _inlineCallbacks
result = g.send(result)
File "/home/synapse/src/synapse/metrics/background_process_metrics.py", line 212, in run
result = await result
File "/home/synapse/src/synapse/federation/sender/per_destination_queue.py", line 332, in _transaction_transmission_loop
self._destination, pending_pdus, pending_edus
File "/home/synapse/src/synapse/util/metrics.py", line 92, in measured_func
r = await func(self, *args, **kwargs)
File "/home/synapse/src/synapse/federation/sender/transaction_manager.py", line 163, in send_new_transaction
logger.info("TX [%s] {%s} got %d response", destination, txn_id, code)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1383, in info
self._log(INFO, msg, args, **kwargs)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1519, in _log
self.handle(record)
File "/usr/local/lib/python3.7/logging/__init__.py", line 1529, in handle
self.callHandlers(record)
File "/home/synapse/env-py37/lib/python3.7/site-packages/sentry_sdk/integrations/logging.py", line 77, in sentry_patched_callhandlers
return old_callhandlers(self, record)
Message: 'TX [%s] {%s} got %d response'

# Fixed code
def start(hs: "synapse.server.HomeServer", listeners: Iterable[ListenerConfig]):
    """
    Start a Synapse server or worker.

    Should be called once the reactor is running and (if we're using ACME) the
    TLS certificates are in place.

    Will start the main HTTP listeners and do some other startup tasks, and then
    notify systemd.

    Args:
        hs: homeserver instance
        listeners: Listener configuration ('listeners' in homeserver.yaml)
    """
    try:
        # Set up the SIGHUP machinery.
        if hasattr(signal, "SIGHUP"):

            @wrap_as_background_process("sighup")
            def handle_sighup(*args, **kwargs):
                # Tell systemd our state, if we're using it. This will silently fail if
                # we're not using systemd.
                sdnotify(b"RELOADING=1")

                for i, args, kwargs in _sighup_callbacks:
                    i(*args, **kwargs)

                sdnotify(b"READY=1")

            # We defer running the sighup handlers until next reactor tick. This
            # is so that we're in a sane state, e.g. flushing the logs may fail
            # if the sighup happens in the middle of writing a log entry.
            def run_sighup(*args, **kwargs):
                hs.get_clock().call_later(0, handle_sighup, *args, **kwargs)

            signal.signal(signal.SIGHUP, run_sighup)

            register_sighup(refresh_certificate, hs)

        # Load the certificate from disk.
        refresh_certificate(hs)

        # Start the tracer
        synapse.logging.opentracing.init_tracer(  # type: ignore[attr-defined] # noqa
            hs
        )

        # It is now safe to start your Synapse.
        hs.start_listening(listeners)
        hs.get_datastore().db_pool.start_profiling()
        hs.get_pusherpool().start()

        # Log when we start the shut down process.
        hs.get_reactor().addSystemEventTrigger(
            "before", "shutdown", logger.info, "Shutting down..."
        )

        setup_sentry(hs)
        setup_sdnotify(hs)

        # If background tasks are running on the main process, start collecting the
        # phone home stats.
        if hs.config.run_background_tasks:
            start_phone_stats_home(hs)

        # We now freeze all allocated objects in the hopes that (almost)
        # everything currently allocated are things that will be used for the
        # rest of time. Doing so means less work each GC (hopefully).
        #
        # This only works on Python 3.7
        if sys.version_info >= (3, 7):
            gc.collect()
            gc.freeze()
    except Exception:
        traceback.print_exc(file=sys.stderr)
        reactor = hs.get_reactor()
        if reactor.running:
            reactor.stop()
        sys.exit(1)