From 557ee9ef0dc6371a94827ea063835ee265a30b9b Mon Sep 17 00:00:00 2001 From: Adam Harwell Date: Wed, 11 Nov 2026 21:29:29 -0500 Subject: [PATCH] Register server statistics only while the server serves Every HTTPServer registered its statistics in the process-wide logging.statistics when it was constructed, and nothing removed them. Their callbacks hold the server, so every server ever built stayed alive with its gateway: stopped ones, ones whose prepare() failed to bind, and ones that never started. A server is now registered only while it serves, from prepare() to stop(), and clear_stats() replaces its entry while it serves. One lock covers the ready flag together with each registry update, so a clear_stats() or prepare() racing a stop() cannot register a server that has stopped. stop() holds it only for those two steps, not while it joins the workers. The docs now load pytest's intersphinx inventory: the new tests' annotations name pytest's fixture classes, which the API pages link. Assisted-By: Anthropic Claude Opus 5.5 Signed-off-by: Adam Harwell --- cheroot/server.py | 18 ++++++-- cheroot/server.pyi | 3 ++ cheroot/test/test_server.py | 54 +++++++++++++++++++++++ docs/changelog-fragments.d/858.bugfix.rst | 8 ++++ docs/conf.py | 1 + 5 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 docs/changelog-fragments.d/858.bugfix.rst diff --git a/cheroot/server.py b/cheroot/server.py index 89793309aa..3d84bae4f0 100644 --- a/cheroot/server.py +++ b/cheroot/server.py @@ -1659,6 +1659,10 @@ def __init__( # pylint: disable=too-many-positional-arguments peercreds_resolve_enabled and peercreds_enabled ) self.reuse_port = reuse_port + self._stats_key = f'Cheroot HTTPServer {id(self)}' + # Guards `ready` together with the server's entry in + # `logging.statistics`, so a stopped server is never registered + self._stats_lock = threading.Lock() self.clear_stats() self._unservicable_conns = queue.Queue() @@ -1732,7 +1736,9 @@ def clear_stats(self): ), 'Worker Threads': {}, } - logging.statistics['Cheroot HTTPServer %d' % id(self)] = self.stats + with self._stats_lock: + if self.ready: + logging.statistics[self._stats_key] = self.stats def runtime(self): """Return server uptime.""" @@ -1884,7 +1890,11 @@ def prepare(self): # noqa: C901 # FIXME # Create worker threads self.requests.start() - self.ready = True + with self._stats_lock: + self.ready = True + # Only while serving: the statistics' callbacks hold the server, + # which the process-wide registry would otherwise keep alive + logging.statistics[self._stats_key] = self.stats self._start_time = time.time() def _serve_unservicable(self): @@ -2262,7 +2272,9 @@ def stop(self): # noqa: C901 # FIXME if not self.ready: return # already stopped - self.ready = False + with self._stats_lock: + self.ready = False + logging.statistics.pop(self._stats_key, None) # This tells the thread that handles unservicable connections to shut # down: diff --git a/cheroot/server.pyi b/cheroot/server.pyi index 8ea38fd99b..5d27b4ffe3 100644 --- a/cheroot/server.pyi +++ b/cheroot/server.pyi @@ -1,3 +1,4 @@ +import threading import typing as _t __all__ = ( @@ -164,6 +165,8 @@ class HTTPServer: reuse_port: bool = ..., ) -> None: ... stats: _t.Any + _stats_key: str + _stats_lock: threading.Lock def clear_stats(self): ... def runtime(self): ... @property diff --git a/cheroot/test/test_server.py b/cheroot/test/test_server.py index 11c47231fa..edfcfb64f7 100644 --- a/cheroot/test/test_server.py +++ b/cheroot/test/test_server.py @@ -1,6 +1,10 @@ """Tests for the HTTP server.""" +from __future__ import annotations + +import errno import gc +import logging import os import pathlib import queue @@ -10,6 +14,7 @@ import tempfile import threading import types +import typing as _t import urllib.parse # noqa: WPS301 import uuid from http import HTTPStatus @@ -84,6 +89,18 @@ def unix_file_sock(): os.unlink(tmp_sock_fname) +def _make_server( + server_class: type[HTTPServer] = HTTPServer, + **kwargs: _t.Any, +) -> HTTPServer: + """Make a server on an ephemeral port, without starting it.""" + return server_class( + bind_addr=(ANY_INTERFACE_IPV4, EPHEMERAL_PORT), + gateway=Gateway, + **kwargs, + ) + + def test_prepare_makes_server_ready(): """Check that prepare() makes the server ready, and stop() clears it.""" httpserver = HTTPServer( @@ -627,3 +644,40 @@ def test_overload_thread_does_not_leak(): # We use special exit code to indicate success, rather than normal zero, so # the test doesn't acidentally pass: assert process.returncode == SUCCESSFUL_SUBPROCESS_EXIT + + +def test_statistics_are_published_while_serving( + request: pytest.FixtureRequest, +) -> None: + """Test that a server's statistics are published only while it serves.""" + httpserver = _make_server() + stats_key = f'Cheroot HTTPServer {id(httpserver)}' + assert stats_key not in logging.statistics + + httpserver.prepare() + request.addfinalizer(httpserver.stop) + assert logging.statistics[stats_key] is httpserver.stats + httpserver.clear_stats() + assert logging.statistics[stats_key] is httpserver.stats + + httpserver.stop() + assert stats_key not in logging.statistics + + httpserver.prepare() + assert logging.statistics[stats_key] is httpserver.stats + + +def test_statistics_are_not_published_after_failed_bind( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Test that a server that fails to bind publishes no statistics.""" + httpserver = _make_server() + stats_key = f'Cheroot HTTPServer {id(httpserver)}' + + def _fail_bind(*_args: object) -> None: + raise OSError(errno.EADDRINUSE, 'Address already in use') + + monkeypatch.setattr(httpserver, 'bind', _fail_bind) + with pytest.raises(OSError, match='No socket could be created'): + httpserver.prepare() + assert stats_key not in logging.statistics diff --git a/docs/changelog-fragments.d/858.bugfix.rst b/docs/changelog-fragments.d/858.bugfix.rst new file mode 100644 index 0000000000..710b93b332 --- /dev/null +++ b/docs/changelog-fragments.d/858.bugfix.rst @@ -0,0 +1,8 @@ +Fixed ``logging.statistics`` retaining +:py:class:`~cheroot.server.HTTPServer` instances and their gateways for the +life of the process, including servers that had stopped, failed to start, +or never started. Server statistics are now registered after +:py:meth:`~cheroot.server.HTTPServer.prepare` succeeds and removed by +:py:meth:`~cheroot.server.HTTPServer.stop`. + +-- by :user:`rm-you` diff --git a/docs/conf.py b/docs/conf.py index 89292604d8..506cd68708 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -96,6 +96,7 @@ 'coverage': ('https://coverage.readthedocs.io/en/latest/', None), 'towncrier': ('https://towncrier.readthedocs.io/en/latest/', None), 'sphinx': ('https://www.sphinx-doc.org', None), + 'pytest': ('https://docs.pytest.org/en/stable', None), } linkcheck_ignore = [