From 88d71bbe3647e8cdceeb392753deaddc0f3c8bea Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi <3247106+gantoine@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:15:50 -0500 Subject: [PATCH] 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 * 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 * 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 * chore(coherence): record the invariant run for the preload change Co-Authored-By: Claude Opus 5.5 * test: drop trunk-ignore comments bandit never needed in tests Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- ...18e3-4897-b93f-3861c5a74523.996610d2.jsonl | 1 + backend/endpoints/responses/base.py | 6 +- backend/handler/socket_handler.py | 16 ++++ backend/tests/endpoints/test_music.py | 2 +- backend/tests/handler/test_socket_handler.py | 32 +++++++ backend/tests/test_api_import_is_fork_safe.py | 49 +++++++++++ backend/tests/test_gunicorn_conf.py | 83 +++++++++++++++++++ docker/Dockerfile | 1 + docker/gunicorn/gunicorn.conf.py | 37 +++++++++ docker/s6-overlay/s6-rc.d/romm-gunicorn/run | 3 +- docs/BACKEND_ARCHITECTURE.md | 1 + env.template | 3 +- examples/docker-compose.example.yml | 2 +- frontend/src/stores/galleryRoms.ts | 4 +- 14 files changed, 231 insertions(+), 9 deletions(-) create mode 100644 .coherence/runs/e0f60f29-18e3-4897-b93f-3861c5a74523.996610d2.jsonl create mode 100644 backend/tests/test_api_import_is_fork_safe.py create mode 100644 backend/tests/test_gunicorn_conf.py create mode 100644 docker/gunicorn/gunicorn.conf.py diff --git a/.coherence/runs/e0f60f29-18e3-4897-b93f-3861c5a74523.996610d2.jsonl b/.coherence/runs/e0f60f29-18e3-4897-b93f-3861c5a74523.996610d2.jsonl new file mode 100644 index 000000000..1e536c7cd --- /dev/null +++ b/.coherence/runs/e0f60f29-18e3-4897-b93f-3861c5a74523.996610d2.jsonl @@ -0,0 +1 @@ +{"at":"2026-12-03T14:06:22.692Z","session":"e0f60f29-18e3-4897-b93f-3861c5a74523","agent":"main","binding":"none: this session owns no active work order","commit":"0f05c802d","dirty":true,"instrument":{"language":"python","server":"cold"},"latency":41872,"load":{"average":3.07,"cores":10},"batch":{"ms":34505},"full":true,"invariants":[{"component":"backend","name":"api routes require auth","form":"totality oracle","verdict":"pass","refutation":"witnessed","bypasses":[],"testReferences":0,"files":[],"latency":34505,"reason":"1 test under \"test_every_api_route_requires_auth_or_is_listed_public\" passed in one invocation of ROMM_TEST_DB_TAG=\"${ROMM_TEST_DB_TAG:-coherence_$$}\" uv run pytest -q -k <3 names> --junitxml=","language":"python","testMs":15950,"mode":"batched","state":"invariant","enforces":["test_every_api_route_requires_auth_or_is_listed_public"]},{"component":"backend/endpoints","name":"hidden entities answer as missing","form":"totality oracle","verdict":"pass","refutation":"witnessed","bypasses":[],"testReferences":0,"files":[],"latency":34505,"reason":"1 test under \"test_every_entity_route_answers_a_hidden_id_like_a_missing_one\" passed in one invocation of ROMM_TEST_DB_TAG=\"${ROMM_TEST_DB_TAG:-coherence_$$}\" uv run pytest -q -k <3 names> --junitxml=","language":"python","testMs":3199,"mode":"batched","state":"invariant","enforces":["test_every_entity_route_answers_a_hidden_id_like_a_missing_one"]},{"component":"backend/endpoints","name":"save fetch by id stays in its router","form":"chokepoint","grade":"reference-choked","verdict":"pass","enforcer":"Coherence's check at the edit and in CI","from":{"value":"anywhere","by":"default"},"refutation":"automatic","bypasses":[],"sites":[{"file":"backend/endpoints/saves.py","line":320,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":344,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":387,"symbol":"add_save.device_id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":389,"symbol":"add_save.content_hash","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":390,"symbol":"add_save.session_id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":419,"symbol":"add_save.saveFile","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":420,"symbol":"add_save.screenshotFile","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":429,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":485,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":567,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":570,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":571,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":624,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":627,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":659,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":659,"symbol":"add_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":663,"symbol":"get_saves","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":687,"symbol":"get_saves.device_id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":702,"symbol":"get_saves","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":709,"symbol":"get_saves","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":714,"symbol":"get_save_identifiers","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":722,"symbol":"get_saves_summary","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":738,"symbol":"get_saves_summary","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":747,"symbol":"get_save_layouts","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":754,"symbol":"get_save_layouts","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":779,"symbol":"get_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":784,"symbol":"get_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":788,"symbol":"get_save.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":788,"symbol":"get_save.device_id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":794,"symbol":"get_save","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":797,"symbol":"get_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":797,"symbol":"get_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":802,"symbol":"_readable_save_or_404","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":833,"symbol":"_record_download","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":837,"symbol":"_record_download","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":882,"symbol":"conversion_params","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":894,"symbol":"conversion_params","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":899,"symbol":"conversion_params","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":911,"symbol":"_companions","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":914,"symbol":"_companions","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":918,"symbol":"_companions","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":919,"symbol":"_companions","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":944,"symbol":"_restore_error","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":985,"symbol":"_convertible_rom_or_400","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":994,"symbol":"_restore_for_core.conversion","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":997,"symbol":"_restore_for_core","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1010,"symbol":"_restore_for_core","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1022,"symbol":"_restored_response","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1041,"symbol":"module top level","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1050,"symbol":"module top level","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1074,"symbol":"module top level","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1079,"symbol":"download_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1082,"symbol":"download_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1086,"symbol":"download_save.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1087,"symbol":"download_save.conversion","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1087,"symbol":"download_save.conversion","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1088,"symbol":"download_save.device_id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1089,"symbol":"download_save.session_id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1090,"symbol":"download_save.optimistic","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1094,"symbol":"download_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1095,"symbol":"download_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1098,"symbol":"download_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1103,"symbol":"download_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1106,"symbol":"download_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1108,"symbol":"download_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1113,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1117,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1120,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1138,"symbol":"merge_save_into_container.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1139,"symbol":"merge_save_into_container.conversion","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1139,"symbol":"merge_save_into_container.conversion","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1151,"symbol":"merge_save_into_container.device_id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1152,"symbol":"merge_save_into_container.session_id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1153,"symbol":"merge_save_into_container.optimistic","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1174,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1175,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1176,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1178,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1181,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1191,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1192,"symbol":"merge_save_into_container","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1196,"symbol":"confirm_download","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1200,"symbol":"confirm_download","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1205,"symbol":"confirm_download.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1214,"symbol":"confirm_download","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":1235,"symbol":"confirm_download","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1235,"symbol":"confirm_download","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1239,"symbol":"update_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1247,"symbol":"update_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1254,"symbol":"update_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1259,"symbol":"update_save.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1260,"symbol":"update_save.device_id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1261,"symbol":"update_save.content_hash","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1262,"symbol":"update_save.saveFile","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1263,"symbol":"update_save.screenshotFile","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1274,"symbol":"update_save","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":1326,"symbol":"update_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1328,"symbol":"update_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1328,"symbol":"update_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1332,"symbol":"update_save_visibility","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1336,"symbol":"update_save_visibility","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1344,"symbol":"update_save_visibility.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1353,"symbol":"update_save_visibility","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":1370,"symbol":"update_save_visibility","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1374,"symbol":"update_save_favorite","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1377,"symbol":"update_save_favorite","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1381,"symbol":"update_save_favorite.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1389,"symbol":"update_save_favorite","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":1392,"symbol":"update_save_favorite","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1398,"symbol":"update_save_labels","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1401,"symbol":"update_save_labels","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1405,"symbol":"update_save_labels.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1416,"symbol":"update_save_labels","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":1419,"symbol":"update_save_labels","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1427,"symbol":"rename_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1450,"symbol":"rename_save.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1461,"symbol":"rename_save","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":1465,"symbol":"rename_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1469,"symbol":"delete_saves","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1503,"symbol":"delete_saves","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":1522,"symbol":"track_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1526,"symbol":"track_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1531,"symbol":"track_save.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1536,"symbol":"track_save","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":1544,"symbol":"track_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1544,"symbol":"track_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1548,"symbol":"untrack_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1552,"symbol":"untrack_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1557,"symbol":"untrack_save.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1565,"symbol":"untrack_save","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/saves.py","line":1573,"symbol":"untrack_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/saves.py","line":1573,"symbol":"untrack_save","class":"inside","of":"chokepoint","test":false},{"file":"backend/main.py","line":57,"symbol":"module top level","class":"chokepoint-reference","of":"chokepoint","test":false,"form":"import"},{"file":"backend/tests/endpoints/test_save_conversion.py","line":25,"symbol":"module top level","class":"chokepoint-reference","of":"chokepoint","test":true,"form":"import"},{"file":"backend/tests/endpoints/test_save_conversion.py","line":227,"symbol":"TestGetWithCore.test_companions_are_read_once_each_and_capped","class":"chokepoint-reference","of":"chokepoint","test":true},{"file":"backend/tests/endpoints/test_save_conversion.py","line":237,"symbol":"TestGetWithCore.test_more_companions_than_the_cap_are_refused","class":"chokepoint-reference","of":"chokepoint","test":true}],"testReferences":0,"files":["backend/endpoints/saves.py","backend/handler/database/saves_handler.py","backend/main.py","backend/tests/endpoints/test_save_conversion.py"],"latency":4216,"reason":"get_save_by_id in backend/handler/database/saves_handler.py is reference-choked, enforced by Coherence's check at the edit and in CI: get_save_by_id is a member of DBSavesHandler, reachable through the class from any file (get_save_by_id carries no underscore prefix; backend/handler/database/saves_handler.py declares no __all__; no Pyright configuration); every reference in the project is inside the chokepoint","language":"python","state":"invariant","enforces":["backend/endpoints/saves.py"]},{"component":"backend/endpoints","name":"state fetch by id stays in its router","form":"chokepoint","grade":"reference-choked","verdict":"pass","enforcer":"Coherence's check at the edit and in CI","from":{"value":"anywhere","by":"default"},"refutation":"automatic","bypasses":[],"sites":[{"file":"backend/endpoints/states.py","line":86,"symbol":"add_state","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":108,"symbol":"add_state","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":143,"symbol":"add_state.stateFile","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":144,"symbol":"add_state.screenshotFile","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":217,"symbol":"get_states","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":244,"symbol":"get_state_identifiers","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":255,"symbol":"get_state","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":258,"symbol":"get_state","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":260,"symbol":"get_state.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":263,"symbol":"get_state","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/states.py","line":270,"symbol":"download_state","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":282,"symbol":"download_state.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":286,"symbol":"download_state","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/states.py","line":307,"symbol":"update_state","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":327,"symbol":"update_state","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":332,"symbol":"update_state.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":337,"symbol":"update_state.stateFile","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":338,"symbol":"update_state.screenshotFile","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":348,"symbol":"update_state","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/states.py","line":398,"symbol":"update_state_visibility","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":402,"symbol":"update_state_visibility","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":403,"symbol":"update_state_visibility","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":408,"symbol":"update_state_visibility.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":417,"symbol":"update_state_visibility","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/states.py","line":438,"symbol":"update_state_favorite","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":441,"symbol":"update_state_favorite","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":445,"symbol":"update_state_favorite.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":453,"symbol":"update_state_favorite","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/states.py","line":462,"symbol":"update_state_labels","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":465,"symbol":"update_state_labels","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":469,"symbol":"update_state_labels.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":480,"symbol":"update_state_labels","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/states.py","line":491,"symbol":"rename_state","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":514,"symbol":"rename_state.id","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":525,"symbol":"rename_state","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/states.py","line":532,"symbol":"delete_states","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/states.py","line":566,"symbol":"delete_states","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/states.py","line":577,"symbol":"delete_states","class":"inside","of":"chokepoint","test":false},{"file":"backend/main.py","line":61,"symbol":"module top level","class":"chokepoint-reference","of":"chokepoint","test":false,"form":"import"}],"testReferences":0,"files":["backend/endpoints/states.py","backend/handler/database/states_handler.py","backend/main.py"],"latency":1563,"reason":"get_state_by_id in backend/handler/database/states_handler.py is reference-choked, enforced by Coherence's check at the edit and in CI: get_state_by_id is a member of DBStatesHandler, reachable through the class from any file (get_state_by_id carries no underscore prefix; backend/handler/database/states_handler.py declares no __all__; no Pyright configuration); every reference in the project is inside the chokepoint","language":"python","state":"invariant","enforces":["backend/endpoints/states.py"]},{"component":"backend/endpoints","name":"screenshot fetch by id stays in its router","form":"chokepoint","grade":"reference-choked","verdict":"pass","enforcer":"Coherence's check at the edit and in CI","from":{"value":"anywhere","by":"default"},"refutation":"automatic","bypasses":[],"sites":[{"file":"backend/endpoints/screenshots.py","line":39,"symbol":"add_screenshot","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/screenshots.py","line":60,"symbol":"add_screenshot.screenshotFile","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/screenshots.py","line":138,"symbol":"download_screenshot","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/screenshots.py","line":156,"symbol":"download_screenshot","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/screenshots.py","line":187,"symbol":"update_screenshot","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/screenshots.py","line":206,"symbol":"update_screenshot","class":"inside","of":"protected","test":false},{"file":"backend/endpoints/screenshots.py","line":214,"symbol":"delete_screenshot","class":"inside","of":"chokepoint","test":false},{"file":"backend/endpoints/screenshots.py","line":229,"symbol":"delete_screenshot","class":"inside","of":"protected","test":false},{"file":"backend/main.py","line":58,"symbol":"module top level","class":"chokepoint-reference","of":"chokepoint","test":false,"form":"import"}],"testReferences":0,"files":["backend/endpoints/screenshots.py","backend/handler/database/screenshots_handler.py","backend/main.py"],"latency":726,"reason":"get_screenshot_by_id in backend/handler/database/screenshots_handler.py is reference-choked, enforced by Coherence's check at the edit and in CI: get_screenshot_by_id is a member of DBScreenshotsHandler, reachable through the class from any file (get_screenshot_by_id carries no underscore prefix; backend/handler/database/screenshots_handler.py declares no __all__; no Pyright configuration); every reference in the project is inside the chokepoint","language":"python","state":"invariant","enforces":["backend/endpoints/screenshots.py"]},{"component":"backend/handler/filesystem","name":"paths stay in their base","form":"totality oracle","verdict":"pass","refutation":"witnessed","bypasses":[],"testReferences":0,"files":[],"latency":34505,"reason":"1 test under \"test_validate_path_never_escapes_its_base\" passed in one invocation of ROMM_TEST_DB_TAG=\"${ROMM_TEST_DB_TAG:-coherence_$$}\" uv run pytest -q -k <3 names> --junitxml=","language":"python","testMs":399,"mode":"batched","state":"invariant","enforces":["test_validate_path_never_escapes_its_base"]}]} diff --git a/backend/endpoints/responses/base.py b/backend/endpoints/responses/base.py index 16326adb2..5b84618c3 100644 --- a/backend/endpoints/responses/base.py +++ b/backend/endpoints/responses/base.py @@ -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.""" diff --git a/backend/handler/socket_handler.py b/backend/handler/socket_handler.py index c894ab9eb..3139a08d2 100644 --- a/backend/handler/socket_handler.py +++ b/backend/handler/socket_handler.py @@ -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) diff --git a/backend/tests/endpoints/test_music.py b/backend/tests/endpoints/test_music.py index 4f523bc61..688f4a701 100644 --- a/backend/tests/endpoints/test_music.py +++ b/backend/tests/endpoints/test_music.py @@ -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 ): diff --git a/backend/tests/handler/test_socket_handler.py b/backend/tests/handler/test_socket_handler.py index 704456c15..074b2a342 100644 --- a/backend/tests/handler/test_socket_handler.py +++ b/backend/tests/handler/test_socket_handler.py @@ -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()) diff --git a/backend/tests/test_api_import_is_fork_safe.py b/backend/tests/test_api_import_is_fork_safe.py new file mode 100644 index 000000000..bb866a761 --- /dev/null +++ b/backend/tests/test_api_import_is_fork_safe.py @@ -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" diff --git a/backend/tests/test_gunicorn_conf.py b/backend/tests/test_gunicorn_conf.py new file mode 100644 index 000000000..2ab1aee2b --- /dev/null +++ b/backend/tests/test_gunicorn_conf.py @@ -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() diff --git a/docker/Dockerfile b/docker/Dockerfile index 16a982867..e986266c0 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -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). diff --git a/docker/gunicorn/gunicorn.conf.py b/docker/gunicorn/gunicorn.conf.py new file mode 100644 index 000000000..e0fda1fbd --- /dev/null +++ b/docker/gunicorn/gunicorn.conf.py @@ -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) diff --git a/docker/s6-overlay/s6-rc.d/romm-gunicorn/run b/docker/s6-overlay/s6-rc.d/romm-gunicorn/run index 9163f764c..c435cb1c9 100755 --- a/docker/s6-overlay/s6-rc.d/romm-gunicorn/run +++ b/docker/s6-overlay/s6-rc.d/romm-gunicorn/run @@ -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}" \ diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 034f38516..67435f645 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -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. diff --git a/env.template b/env.template index 8c1d48f49..007857532 100644 --- a/env.template +++ b/env.template @@ -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 diff --git a/examples/docker-compose.example.yml b/examples/docker-compose.example.yml index f433d621d..bce878390 100644 --- a/examples/docker-compose.example.yml +++ b/examples/docker-compose.example.yml @@ -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 diff --git a/frontend/src/stores/galleryRoms.ts b/frontend/src/stores/galleryRoms.ts index 5db617df3..7f2d0eacf 100644 --- a/frontend/src/stores/galleryRoms.ts +++ b/frontend/src/stores/galleryRoms.ts @@ -88,9 +88,9 @@ type GalleryFilterStore = ExtractPiniaStoreType; 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.