Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
0480911
First pass: be able to shutdown homeserver that hasn't `setup`
MadLittleMods Nov 14, 2025
a0e7698
Add test
MadLittleMods Nov 14, 2025
df0a5d1
Add some better debugging info when the test fails
MadLittleMods Nov 14, 2025
d046476
Fix up lints
MadLittleMods Nov 14, 2025
d55f86d
Add changelog
MadLittleMods Nov 14, 2025
fa83d65
Merge branch 'develop' into madlittlemods/shutdown-homeserver-that-wa…
MadLittleMods Nov 21, 2025
ea1757e
Avoid partially initialized `Keyring` which can hold references to `hs`
MadLittleMods Nov 22, 2025
fce7ada
Better comment
MadLittleMods Nov 22, 2025
b99246b
Merge branch 'develop' into madlittlemods/shutdown-homeserver-that-wa…
MadLittleMods Nov 22, 2025
b3aab27
Merge branch 'develop' into madlittlemods/shutdown-homeserver-that-wa…
MadLittleMods Nov 24, 2025
72ca424
Merge branch 'develop' into madlittlemods/shutdown-homeserver-that-wa…
MadLittleMods Nov 25, 2025
f51e1fe
Fix Synapse unable to shutdown after failing to bind ports during `st…
MadLittleMods Nov 26, 2025
c69397b
Try and figure out why it works on successful case but not error case
MadLittleMods Nov 26, 2025
f2af1d7
Revert "Try and figure out why it works on successful case but not er…
MadLittleMods Nov 26, 2025
cc26fd1
Iterate on test
MadLittleMods Nov 26, 2025
34b1878
Try to start with real invalid ports
MadLittleMods Nov 26, 2025
270aaba
Add changelog
MadLittleMods Nov 26, 2025
e121d66
Use `site.stopFactory()`
MadLittleMods Nov 26, 2025
e49fed1
Remove debug logs
MadLittleMods Nov 26, 2025
d8f4a00
Explain more why
MadLittleMods Nov 26, 2025
422f36d
Remove test as its not effective
MadLittleMods Nov 26, 2025
5729c13
Better language, only
MadLittleMods Nov 26, 2025
2551c24
Better errors
MadLittleMods Nov 26, 2025
ebf3c6e
Remove unused `MemoryReactor` changes now that we don't have a test t…
MadLittleMods Nov 26, 2025
591d920
Merge branch 'develop' into madlittlemods/shutdown-homeserver-that-wa…
MadLittleMods Dec 1, 2025
235b684
Use `ExitStack` for nice clean-up during `__init__`
MadLittleMods Dec 1, 2025
25015f7
`self._key_fetchers.clear()`
MadLittleMods Dec 1, 2025
858c2ba
Remove irrelevant comment
MadLittleMods Dec 1, 2025
fe3a84a
Fix `which` typo
MadLittleMods Dec 1, 2025
df97f11
Explain `ExitStack` a little
MadLittleMods Dec 1, 2025
b430e81
Merge branch 'madlittlemods/shutdown-homeserver-that-was-never-setup'…
MadLittleMods Dec 1, 2025
238c936
Merge branch 'develop' into madlittlemods/shutdown-homeserver-that-wa…
MadLittleMods Dec 2, 2025
382bbcd
Merge branch 'madlittlemods/shutdown-homeserver-that-was-never-setup'…
MadLittleMods Dec 2, 2025
d0d2802
Merge branch 'develop' into madlittlemods/shutdown-homeserver-that-fa…
MadLittleMods Dec 2, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/19232.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix `HomeServer.shutdown()` failing if the homeserver failed to `start`.
114 changes: 83 additions & 31 deletions synapse/app/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
from wsgiref.simple_server import WSGIServer

from cryptography.utils import CryptographyDeprecationWarning
from typing_extensions import ParamSpec
from typing_extensions import ParamSpec, assert_never

import twisted
from twisted.internet import defer, error, reactor as _reactor
Expand All @@ -64,7 +64,12 @@
from synapse.config import ConfigError
from synapse.config._base import format_config_error
from synapse.config.homeserver import HomeServerConfig
from synapse.config.server import ListenerConfig, ManholeConfig, TCPListenerConfig
from synapse.config.server import (
ListenerConfig,
ManholeConfig,
TCPListenerConfig,
UnixListenerConfig,
)
from synapse.crypto import context_factory
from synapse.events.auto_accept_invites import InviteAutoAccepter
from synapse.events.presence_router import load_legacy_presence_router
Expand Down Expand Up @@ -413,6 +418,37 @@ def listen_unix(
]


class ListenerException(RuntimeError):
"""
An exception raised when we fail to listen with the given `ListenerConfig`.

Attributes:
listener_config: The listener config that caused the exception.
"""

def __init__(
self,
listener_config: ListenerConfig,
):
listener_human_name = ""
port = ""
if isinstance(listener_config, TCPListenerConfig):
listener_human_name = "TCP port"
port = str(listener_config.port)
elif isinstance(listener_config, UnixListenerConfig):
listener_human_name = "unix socket"
port = listener_config.path
else:
assert_never(listener_config)

super().__init__(
"Failed to listen on %s (%s) with the given listener config: %s"
% (listener_human_name, port, listener_config)
)

self.listener_config = listener_config


def listen_http(
hs: "HomeServer",
listener_config: ListenerConfig,
Expand Down Expand Up @@ -447,39 +483,55 @@ def listen_http(
hs=hs,
)

if isinstance(listener_config, TCPListenerConfig):
if listener_config.is_tls():
# refresh_certificate should have been called before this.
assert context_factory is not None
ports = listen_ssl(
listener_config.bind_addresses,
listener_config.port,
site,
context_factory,
reactor=reactor,
try:
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Best to review this part with the "Hide whitespace" option when viewing the diff

if isinstance(listener_config, TCPListenerConfig):
if listener_config.is_tls():
# refresh_certificate should have been called before this.
assert context_factory is not None
ports = listen_ssl(
listener_config.bind_addresses,
listener_config.port,
site,
context_factory,
reactor=reactor,
)
logger.info(
"Synapse now listening on TCP port %d (TLS)", listener_config.port
)
else:
ports = listen_tcp(
listener_config.bind_addresses,
listener_config.port,
site,
reactor=reactor,
)
logger.info(
"Synapse now listening on TCP port %d", listener_config.port
)

elif isinstance(listener_config, UnixListenerConfig):
ports = listen_unix(
listener_config.path, listener_config.mode, site, reactor=reactor
)
# getHost() returns a UNIXAddress which contains an instance variable of 'name'
# encoded as a byte string. Decode as utf-8 so pretty.
logger.info(
"Synapse now listening on TCP port %d (TLS)", listener_config.port
"Synapse now listening on Unix Socket at: %s",
ports[0].getHost().name.decode("utf-8"),
)
else:
ports = listen_tcp(
listener_config.bind_addresses,
listener_config.port,
site,
reactor=reactor,
)
logger.info("Synapse now listening on TCP port %d", listener_config.port)

else:
ports = listen_unix(
listener_config.path, listener_config.mode, site, reactor=reactor
)
# getHost() returns a UNIXAddress which contains an instance variable of 'name'
# encoded as a byte string. Decode as utf-8 so pretty.
logger.info(
"Synapse now listening on Unix Socket at: %s",
ports[0].getHost().name.decode("utf-8"),
)
assert_never(listener_config)
Comment on lines +512 to +523
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Superfluous but I updated to use a more robust matching pattern since I used it in ListenerException above

except Exception as exc:
# The Twisted interface says that "Users should not call this function
# themselves!" but this appears to be the correct/only way handle proper cleanup
Comment on lines +525 to +526
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

heh, well, I guess it is what it is.
If this is only during error handling code I'm OK with this, otherwise I find the idea of doing something we're told not to do a bit unappealing.

# of the site when things go wrong. In the normal case, a `Port` is created
# which we can call `Port.stopListening()` on to do the same thing (but no
# `Port` is created when an error occurs).
#
# We use `site.stopFactory()` instead of `site.doStop()` as the latter assumes
# that `site.doStart()` was called (which won't be the case if an error occurs).
site.stopFactory()
raise ListenerException(listener_config) from exc
Comment on lines +524 to +534
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried adding a test for this case but it's not effective as we're using the MemoryReactor in tests which doesn't actually try to bind any ports (just fakes it).

We do have a Complement test in the Synapse Pro for small hosts project (see element-hq/synapse-small-hosts -> complement/tests/multi_synapse/provision_test.go#L278-L295 which we will uncomment when this PR merges). I have tested that this PR does fix the problem (see https://github.com/element-hq/synapse-small-hosts/pull/326 for where I was playing around with this).


return ports

Expand Down
7 changes: 7 additions & 0 deletions synapse/http/site.py
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,13 @@ def stopFactory(self) -> None:
protocol.transport.loseConnection()
self.connections.clear()

# Replace the resource tree with an empty resource to break circular references
# to the resource tree which holds a bunch of homeserver references. This is
# important if we try to call `hs.shutdown()` after `start` fails. For some
# reason, this doesn't seem to be necessary in the normal case where `start`
# succeeds and we call `hs.shutdown()` later.
self.resource = Resource()
Comment on lines +818 to +823
Copy link
Copy Markdown
Contributor Author

@MadLittleMods MadLittleMods Nov 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've spent too long trying to figure out why this works exactly. Specifically, why the normal case works without this change but the error case requires it.

The internal references to hs should be the same between the normal and error cases. And we have even less external references to SynapseSite since it just gets orphaned in this function context in the error case and drops away as soon as we handle the traceback/exception in the layers above.

In the normal case, Port holds a reference to the site and then when we call Port.stopListening(), it calls site.stopFactory() down the line just like we're doing in the error case now. But in the error case, it doesn't work without this additional change to sever the circular references.

I've looked through the Twisted internals to try to spot the difference but was unsuccessful. Also tried throwing an LLM at the problem but they were also unable to spot anything.

In any case, clearing circular references in these kinds of callbacks are pretty normal. For example, it's even called out in the HTTPChannel.connectionLost docstring. twisted.web.server.Site.stopFactory describes it as:

This can be overridden to perform 'shutdown' tasks such as disconnecting database connections, closing files, etc.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy to have this + the comment saying we don't understand why it's necessary only sometimes.

Replacing your inners with empty values on shutdown/destruction is totally fine as a practice to me.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(I'm assuming the current comment is sufficient)


def log(self, request: SynapseRequest) -> None: # type: ignore[override]
pass

Expand Down
Loading