mirror of
https://github.com/rommapp/romm.git
synced 2026-12-04 21:02:21 +01:00
perf(gunicorn): preload the app so web workers share its memory (#5846)
* perf(gunicorn): preload the app so web workers share its memory Each gunicorn worker imported the whole app on its own, ~160 MB private per worker. Preloading imports it once in the master; gc.freeze keeps the shared pages from being copied when workers collect garbage. - gunicorn.conf.py: GC off during import, OpenAPI schema built and all objects frozen before fork, inherited SQL pool dropped in each worker - Socket.IO managers renew their pub/sub host ID after fork, otherwise preloaded workers drop each other's emits as their own - WEB_SERVER_CONCURRENCY defaults to 2 - Page limit capped at 1,000 (was 10,000): a worker keeps the memory of its largest response until recycled; select-all pages by 1,000 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(gunicorn): address Greptile review on the preload change - Shorten the renew_host_id docstring and the gunicorn.conf.py comment - Close the fork test's pipe in a finally block - Test that when_ready builds the schema before freezing and re-enabling the GC, and that post_fork disposes the pool with close=False Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(gunicorn): WEB_SERVER_PRELOAD switch and an import fork-safety test - WEB_SERVER_PRELOAD (default true) sets preload_app from the gunicorn config; false restores per-worker imports and skips every hook - tests/test_api_import_is_fork_safe.py imports main in a fresh interpreter with the database on a closed port and fails if the import opens a connection or starts a thread (adapted from #5735) - BACKEND_ARCHITECTURE notes the preload and what it requires of imports Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(coherence): record the invariant run for the preload change Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: drop trunk-ignore comments bandit never needed in tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
committed by
GitHub
parent
ec1684d2af
commit
88d71bbe36
1
.coherence/runs/e0f60f29-18e3-4897-b93f-3861c5a74523.996610d2.jsonl
generated
Normal file
1
.coherence/runs/e0f60f29-18e3-4897-b93f-3861c5a74523.996610d2.jsonl
generated
Normal file
File diff suppressed because one or more lines are too long
@@ -29,9 +29,9 @@ class BaseModel(PydanticBaseModel):
|
||||
|
||||
|
||||
class PageParams(BaseModel):
|
||||
# Temporarily high until every app paginates
|
||||
limit: int = Field(50, ge=1, le=10_000)
|
||||
"""The number of items to return, such as 72. Defaults to 50. The maximum is 10,000."""
|
||||
# A worker keeps the memory of its largest response until it is recycled.
|
||||
limit: int = Field(50, ge=1, le=1_000)
|
||||
"""The number of items to return, such as 72. Defaults to 50. The maximum is 1,000."""
|
||||
offset: int = Field(0, ge=0)
|
||||
"""The number of items to skip. For example, 144 returns the third page of 72."""
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
@@ -73,6 +75,11 @@ class SocketHandler:
|
||||
|
||||
return register
|
||||
|
||||
def renew_host_id(self) -> None:
|
||||
"""Give a forked process its own pub/sub host ID."""
|
||||
# A manager ignores messages stamped with its own host ID.
|
||||
self.socket_server.manager.host_id = uuid.uuid4().hex
|
||||
|
||||
def _login_session_sockets_key(self, session_id: str) -> str:
|
||||
# Per channel, since a sid only means something to the server that issued it.
|
||||
return f"session_sockets:{self.channel}:{session_id}"
|
||||
@@ -222,6 +229,15 @@ socket_handler = SocketHandler(path="/ws/socket.io")
|
||||
netplay_socket_handler = SocketHandler(path="/netplay/socket.io", channel="netplay")
|
||||
|
||||
|
||||
def _renew_host_ids() -> None:
|
||||
socket_handler.renew_host_id()
|
||||
netplay_socket_handler.renew_host_id()
|
||||
|
||||
|
||||
# Gunicorn preloads the app, so every worker is forked with these managers.
|
||||
os.register_at_fork(after_in_child=_renew_host_ids)
|
||||
|
||||
|
||||
async def close_login_session_sockets(session_ids: Iterable[str]) -> None:
|
||||
"""Disconnect the sockets the given login sessions opened, on every server."""
|
||||
ids = list(session_ids)
|
||||
|
||||
@@ -364,7 +364,7 @@ def test_facet_search_matches_wildcards_literally(
|
||||
@pytest.mark.parametrize(
|
||||
"path", ["/api/roms", "/api/music/tracks", "/api/music/artists"]
|
||||
)
|
||||
@pytest.mark.parametrize("query", ["limit=0", "limit=10001", "offset=-1"])
|
||||
@pytest.mark.parametrize("query", ["limit=0", "limit=1001", "offset=-1"])
|
||||
def test_page_params_out_of_bounds_422(
|
||||
client: TestClient, access_token: str, path: str, query: str
|
||||
):
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import cast
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
@@ -29,6 +30,37 @@ def test_netplay_cannot_join_the_main_servers_rooms():
|
||||
assert netplay.channel != main.channel
|
||||
|
||||
|
||||
@pytest.mark.filterwarnings(
|
||||
"ignore:This process .* is multi-threaded:DeprecationWarning"
|
||||
)
|
||||
def test_a_forked_process_gets_its_own_host_ids():
|
||||
# A manager ignores pub/sub messages stamped with its own host ID, so workers
|
||||
# forked from a preloaded master must not share one.
|
||||
parent_ids = [
|
||||
h.socket_server.manager.host_id
|
||||
for h in (socket_handler, netplay_socket_handler)
|
||||
]
|
||||
read_end, write_end = os.pipe()
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
ids = [
|
||||
h.socket_server.manager.host_id
|
||||
for h in (socket_handler, netplay_socket_handler)
|
||||
]
|
||||
os.write(write_end, ",".join(ids).encode())
|
||||
os._exit(0)
|
||||
os.close(write_end)
|
||||
try:
|
||||
child_ids = os.read(read_end, 1024).decode().split(",")
|
||||
finally:
|
||||
os.close(read_end)
|
||||
os.waitpid(pid, 0)
|
||||
|
||||
assert len(child_ids) == 2
|
||||
assert set(child_ids).isdisjoint(parent_ids)
|
||||
assert child_ids[0] != child_ids[1]
|
||||
|
||||
|
||||
class TestEmitToUser:
|
||||
async def test_targets_the_users_room_on_the_servers_channel(self, mocker):
|
||||
manager = MagicMock(emit=AsyncMock())
|
||||
|
||||
49
backend/tests/test_api_import_is_fork_safe.py
Normal file
49
backend/tests/test_api_import_is_fork_safe.py
Normal file
@@ -0,0 +1,49 @@
|
||||
"""Gunicorn forks its workers from a master that imported the app, so the import must open nothing."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
# Run in a fresh interpreter, the way the gunicorn master imports the app.
|
||||
REPORT = """
|
||||
import threading
|
||||
import main
|
||||
from handler.database.base_handler import sync_engine
|
||||
others = [t.name for t in threading.enumerate() if t is not threading.main_thread()]
|
||||
print("THREADS=" + ",".join(others))
|
||||
print("DB=" + str(sync_engine.pool.checkedin() + sync_engine.pool.checkedout()))
|
||||
"""
|
||||
|
||||
|
||||
def test_importing_the_api_opens_no_connection_and_starts_no_thread() -> None:
|
||||
env = {
|
||||
**os.environ,
|
||||
"PYTHONPATH": str(BACKEND),
|
||||
# Nothing listens on port 1, so a query made during the import fails it.
|
||||
"DB_PORT": "1",
|
||||
"OTEL_SDK_DISABLED": "true",
|
||||
}
|
||||
# Import the app as production does, not in its pytest mode.
|
||||
for name in ("PYTEST_VERSION", "PYTEST_CURRENT_TEST", "SENTRY_DSN"):
|
||||
env.pop(name, None)
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", REPORT],
|
||||
cwd=BACKEND,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, (
|
||||
"importing main failed, possibly on a database query:\n" + result.stderr[-2000:]
|
||||
)
|
||||
report = dict(
|
||||
line.split("=", 1) for line in result.stdout.splitlines() if "=" in line
|
||||
)
|
||||
assert report["THREADS"] == "", f"threads started at import: {report['THREADS']}"
|
||||
assert report["DB"] == "0", "a database connection was opened at import"
|
||||
83
backend/tests/test_gunicorn_conf.py
Normal file
83
backend/tests/test_gunicorn_conf.py
Normal file
@@ -0,0 +1,83 @@
|
||||
import gc
|
||||
import importlib.util
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import main
|
||||
import pytest
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from handler.database import base_handler
|
||||
|
||||
GUNICORN_CONF = Path(__file__).parents[2] / "docker" / "gunicorn" / "gunicorn.conf.py"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def gc_disable(mocker: MockerFixture) -> MagicMock:
|
||||
# Loading the config turns the GC off, which must not leak into the test run.
|
||||
disable = MagicMock()
|
||||
mocker.patch.object(gc, "disable", disable)
|
||||
return disable
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def load_conf(gc_disable, monkeypatch) -> Callable[[str | None], ModuleType]:
|
||||
def load(preload: str | None) -> ModuleType:
|
||||
if preload is None:
|
||||
monkeypatch.delenv("WEB_SERVER_PRELOAD", raising=False)
|
||||
else:
|
||||
monkeypatch.setenv("WEB_SERVER_PRELOAD", preload)
|
||||
spec = importlib.util.spec_from_file_location("gunicorn_conf", GUNICORN_CONF)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
return load
|
||||
|
||||
|
||||
@pytest.mark.parametrize("preload", [None, "true"])
|
||||
def test_preload_is_on_by_default_and_pauses_the_gc(load_conf, gc_disable, preload):
|
||||
conf = load_conf(preload)
|
||||
|
||||
assert conf.preload_app is True
|
||||
gc_disable.assert_called_once_with()
|
||||
|
||||
|
||||
def test_when_ready_builds_the_schema_before_freezing(load_conf, mocker):
|
||||
conf = load_conf(None)
|
||||
calls = MagicMock()
|
||||
mocker.patch.object(main.app, "openapi", calls.openapi)
|
||||
mocker.patch.object(gc, "freeze", calls.freeze)
|
||||
mocker.patch.object(gc, "enable", calls.enable)
|
||||
|
||||
conf.when_ready(MagicMock())
|
||||
|
||||
assert [name for name, *_ in calls.mock_calls] == ["openapi", "freeze", "enable"]
|
||||
|
||||
|
||||
def test_post_fork_drops_inherited_pool_connections_without_closing(load_conf, mocker):
|
||||
conf = load_conf(None)
|
||||
dispose = mocker.patch.object(base_handler.sync_engine, "dispose")
|
||||
|
||||
conf.post_fork(MagicMock(), MagicMock())
|
||||
|
||||
dispose.assert_called_once_with(close=False)
|
||||
|
||||
|
||||
def test_without_preload_every_hook_is_a_no_op(load_conf, gc_disable, mocker):
|
||||
conf = load_conf("false")
|
||||
openapi = mocker.patch.object(main.app, "openapi")
|
||||
freeze = mocker.patch.object(gc, "freeze")
|
||||
dispose = mocker.patch.object(base_handler.sync_engine, "dispose")
|
||||
|
||||
conf.when_ready(MagicMock())
|
||||
conf.post_fork(MagicMock(), MagicMock())
|
||||
|
||||
assert conf.preload_app is False
|
||||
gc_disable.assert_not_called()
|
||||
openapi.assert_not_called()
|
||||
freeze.assert_not_called()
|
||||
dispose.assert_not_called()
|
||||
@@ -368,6 +368,7 @@ COPY ./docker/nginx/js/ /etc/nginx/js/
|
||||
COPY ./docker/nginx/templates/ /etc/nginx/templates/
|
||||
COPY ./docker/nginx/default.conf /etc/nginx/nginx.conf
|
||||
COPY ./docker/gunicorn/logging.conf /etc/gunicorn/logging.conf
|
||||
COPY ./docker/gunicorn/gunicorn.conf.py /etc/gunicorn/gunicorn.conf.py
|
||||
|
||||
# User permissions
|
||||
# - Create default user `romm` (1000) and group `romm` (1000).
|
||||
|
||||
37
docker/gunicorn/gunicorn.conf.py
Normal file
37
docker/gunicorn/gunicorn.conf.py
Normal file
@@ -0,0 +1,37 @@
|
||||
"""Gunicorn hooks for a preloaded app whose memory the workers share."""
|
||||
|
||||
import gc
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
from utils import safe_str_to_bool
|
||||
|
||||
PRELOAD = safe_str_to_bool(os.environ.get("WEB_SERVER_PRELOAD", "true"), default=True)
|
||||
preload_app = PRELOAD
|
||||
|
||||
if PRELOAD:
|
||||
# Collecting during the import would leave holes that later allocations fill,
|
||||
# copying shared pages, so the GC stays off until everything is frozen.
|
||||
gc.disable()
|
||||
|
||||
|
||||
def when_ready(server: Any) -> None:
|
||||
if not PRELOAD:
|
||||
return
|
||||
from main import app
|
||||
|
||||
# Built here, the schema is shared instead of costing every worker ~30 MB on
|
||||
# the first /openapi.json request.
|
||||
app.openapi()
|
||||
# Frozen objects are never scanned, so a collection doesn't copy their pages.
|
||||
gc.freeze()
|
||||
gc.enable()
|
||||
|
||||
|
||||
def post_fork(server: Any, worker: Any) -> None:
|
||||
if not PRELOAD:
|
||||
return
|
||||
from handler.database.base_handler import sync_engine
|
||||
|
||||
# Drops pooled connections inherited from the master without closing them.
|
||||
sync_engine.dispose(close=False)
|
||||
@@ -36,7 +36,8 @@ exec "${wrap[@]}" gunicorn \
|
||||
--no-control-socket \
|
||||
--forwarded-allow-ips="${FORWARDED_ALLOW_IPS:-127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,100.64.0.0/10,fc00::/7}" \
|
||||
--worker-class uvicorn_worker.UvicornWorker \
|
||||
--workers "${WEB_SERVER_CONCURRENCY:-4}" \
|
||||
--workers "${WEB_SERVER_CONCURRENCY:-2}" \
|
||||
--config /etc/gunicorn/gunicorn.conf.py \
|
||||
--timeout "${WEB_SERVER_TIMEOUT:-300}" \
|
||||
--keep-alive "${WEB_SERVER_KEEPALIVE:-65}" \
|
||||
--max-requests "${WEB_SERVER_MAX_REQUESTS:-1000}" \
|
||||
|
||||
@@ -174,6 +174,7 @@ Behaviour worth knowing:
|
||||
|
||||
- **A failed startup step exits the container** (`S6_BEHAVIOUR_IF_STAGE2_FAILS=2`). An unreachable database at boot is normal when the daemon's restart policy starts containers before their dependencies, so migrations fail, the container exits non-zero, and the restart policy retries.
|
||||
- **A crashed service is restarted on its own**, without taking the rest of the container down. Its leftover children are swept first (`finish`), so a replacement can rebind the port a hard-killed parent's workers were still holding.
|
||||
- **Gunicorn imports the app once and forks its workers from it** (`WEB_SERVER_PRELOAD`, on by default), so they share its memory. Importing the app must not open a connection or start a thread, which `tests/test_api_import_is_fork_safe.py` pins, and anything holding a per-process identity is renewed after the fork (`docker/gunicorn/gunicorn.conf.py`, `os.register_at_fork` in `handler/socket_handler.py`).
|
||||
- **Shutdown is bounded.** Each service gets `timeout-kill` (10s) before SIGKILL, escalated to the whole process group (`flag-timeout-killpg`). No process can hold PID 1 open indefinitely.
|
||||
|
||||
Optional services have no conditional mechanism in `s6-rc`: they start, check their environment variable, and take themselves down with `s6-svc -O` when disabled.
|
||||
|
||||
@@ -180,7 +180,8 @@ FORCE_COLOR=false # Force colored log output
|
||||
NO_COLOR=false # Disable colored log output
|
||||
|
||||
# Web Server
|
||||
WEB_SERVER_CONCURRENCY=4 # Number of API worker processes, raise for several concurrent users
|
||||
WEB_SERVER_CONCURRENCY=2 # Number of API worker processes, raise for several concurrent users
|
||||
WEB_SERVER_PRELOAD=true # Import the API once and share its memory across the workers (false to have each worker import it)
|
||||
WEB_SERVER_TIMEOUT=300 # Timeout for web server requests in seconds
|
||||
WEB_SERVER_KEEPALIVE=65 # Keep-Alive connection wait time in seconds, keep above nginx's 60s upstream idle timeout
|
||||
WEB_SERVER_MAX_REQUESTS=1000 # Maximum requests a worker processes before restarting
|
||||
|
||||
@@ -20,7 +20,7 @@ services:
|
||||
- STEAMGRIDDB_API_KEY= # https://docs.romm.app/latest/Getting-Started/Metadata-Providers/#steamgriddb
|
||||
- HASHEOUS_API_ENABLED=true # https://docs.romm.app/latest/Getting-Started/Metadata-Providers/#hasheous
|
||||
- SCAN_WORKERS=4 # How many ROMs to scan at once
|
||||
- WEB_SERVER_CONCURRENCY=4 # Workers for API calls, raise for several concurrent users
|
||||
- WEB_SERVER_CONCURRENCY=2 # Workers for API calls, raise for several concurrent users
|
||||
volumes:
|
||||
- romm_resources:/romm/resources # Resources fetched from IGDB (covers, screenshots, etc.)
|
||||
- romm_redis_data:/redis-data # Cached data for background tasks
|
||||
|
||||
@@ -88,9 +88,9 @@ type GalleryFilterStore = ExtractPiniaStoreType<typeof storeGalleryFilter>;
|
||||
const WINDOW_SIZE = 72;
|
||||
|
||||
// Page size for the whole-result fetch behind "select all": the
|
||||
// backend's ceiling on the `/roms` limit param (le=10_000). Exported
|
||||
// backend's ceiling on the `/roms` limit param (le=1_000). Exported
|
||||
// for the tests that exercise the paging.
|
||||
export const SELECT_ALL_PAGE_SIZE = 10_000;
|
||||
export const SELECT_ALL_PAGE_SIZE = 1_000;
|
||||
|
||||
// One home for "skip every sidecar": each flag is its own server-side
|
||||
// scan, and a misspelled name would silently re-enable one.
|
||||
|
||||
Reference in New Issue
Block a user