From c9771ff01a4ca13770d9c0f5d52041cce1457390 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20S=C3=A1nchez?= Date: Fri, 23 Oct 2026 12:07:56 +0200 Subject: [PATCH 1/2] fix: Dispose SQL registry connection pools after Gunicorn fork MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Gunicorn workers inherited the parent's pooled SQL registry connections, so several workers shared one socket and the server crashed on startup. A post_fork hook, set for every run, now disposes the pools with close=False, so the parent's connections are left open. Fixes #5784 Signed-off-by: Carlos Sánchez --- sdk/python/feast/feature_server.py | 8 +++ .../feast/infra/registry/base_registry.py | 7 +++ sdk/python/feast/infra/registry/sql.py | 8 +++ .../unit/infra/registry/test_sql_registry.py | 58 ++++++++++++++++++- sdk/python/tests/unit/test_feature_server.py | 43 +++++++++++++- 5 files changed, 122 insertions(+), 2 deletions(-) diff --git a/sdk/python/feast/feature_server.py b/sdk/python/feast/feature_server.py index d408b1b0eb3..2fb5504bf46 100644 --- a/sdk/python/feast/feature_server.py +++ b/sdk/python/feast/feature_server.py @@ -1286,6 +1286,9 @@ def load_config(self): self.cfg.set(key.lower(), value) self.cfg.set("worker_class", "uvicorn_worker.UvicornWorker") + self.cfg.set( + "post_fork", functools.partial(_gunicorn_post_fork, self._store) + ) if self._metrics_enabled: self.cfg.set( "post_worker_init", @@ -1296,6 +1299,11 @@ def load_config(self): def load(self): return self._app + def _gunicorn_post_fork(store: "feast.FeatureStore", server, worker): + """Give each Gunicorn worker its own registry connections after fork.""" + if store._registry is not None: + store._registry.reset_after_fork() + def _gunicorn_post_worker_init(store: "feast.FeatureStore", worker): """Start per-worker resource and freshness monitoring after Gunicorn forks.""" feast_metrics.init_worker_monitoring() diff --git a/sdk/python/feast/infra/registry/base_registry.py b/sdk/python/feast/infra/registry/base_registry.py index fbd0fbf256f..4cb13f3ebf2 100644 --- a/sdk/python/feast/infra/registry/base_registry.py +++ b/sdk/python/feast/infra/registry/base_registry.py @@ -1016,6 +1016,13 @@ def is_cache_valid(self) -> bool: """ return False + def reset_after_fork(self) -> None: + """Drop resources inherited from the parent process after os.fork(). + + Called in a forked child (e.g. a Gunicorn worker) before it uses the + registry. Registries that hold no connection pools need not override it. + """ + # Lineage operations def get_registry_lineage( self, diff --git a/sdk/python/feast/infra/registry/sql.py b/sdk/python/feast/infra/registry/sql.py index 771a3890886..fc400fe4c47 100644 --- a/sdk/python/feast/infra/registry/sql.py +++ b/sdk/python/feast/infra/registry/sql.py @@ -388,6 +388,14 @@ def __init__( if not self.purge_feast_metadata: self._maybe_init_project_metadata(project) + def reset_after_fork(self) -> None: + # close=False because the parent still owns those connections; closing + # them would send a disconnect on a socket the parent shares. See + # https://docs.sqlalchemy.org/en/20/core/pooling.html#using-connection-pools-with-multiprocessing-or-os-fork + self.write_engine.dispose(close=False) + if self.read_engine is not self.write_engine: + self.read_engine.dispose(close=False) + @staticmethod def _verify_schema(engine: Engine, registry_metadata: MetaData = metadata) -> None: """Verify that all expected registry tables exist in the database. diff --git a/sdk/python/tests/unit/infra/registry/test_sql_registry.py b/sdk/python/tests/unit/infra/registry/test_sql_registry.py index e39aaa247e6..51ae9ec83d0 100644 --- a/sdk/python/tests/unit/infra/registry/test_sql_registry.py +++ b/sdk/python/tests/unit/infra/registry/test_sql_registry.py @@ -13,14 +13,16 @@ # limitations under the License. import logging +import os import sys import tempfile import types from datetime import datetime, timedelta, timezone -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch import dill import pytest +from sqlalchemy.pool import QueuePool from feast import Field from feast.data_source import PushSource @@ -331,6 +333,60 @@ def test_warn_if_narrow_blob_columns_swallows_query_errors(caplog): assert "still typed BLOB" not in caplog.text +@pytest.mark.skipif(not hasattr(os, "fork"), reason="requires os.fork") +@pytest.mark.filterwarnings( + "ignore:This process .* is multi-threaded:DeprecationWarning" +) +def test_forked_child_does_not_reuse_parent_pooled_connection(sqlite_registry): + """A forked child (e.g. a Gunicorn worker) must not share the parent's pooled connections.""" + assert isinstance(sqlite_registry.write_engine.pool, QueuePool) + with sqlite_registry.write_engine.connect() as conn: + parent_conn = conn.connection.dbapi_connection + + pid = os.fork() + if pid == 0: + try: + sqlite_registry.reset_after_fork() + with sqlite_registry.write_engine.connect() as conn: + child_conn = conn.connection.dbapi_connection + os._exit(1 if child_conn is parent_conn else 0) + except BaseException: + os._exit(2) + _, status = os.waitpid(pid, 0) + + assert os.waitstatus_to_exitcode(status) == 0 + # The parent's pooled connection is still usable. + assert parent_conn.execute("SELECT 1").fetchone() == (1,) + + +def test_reset_after_fork_disposes_pool_without_closing(sqlite_registry): + with patch.object(sqlite_registry.write_engine, "dispose") as dispose: + sqlite_registry.reset_after_fork() + + dispose.assert_called_once_with(close=False) + + +def test_reset_after_fork_disposes_read_and_write_engines(tmp_path): + config = SqlRegistryConfig( + registry_type="sql", + path=f"sqlite:///{tmp_path / 'registry.db'}", + read_path=f"sqlite:///{tmp_path / 'registry.db'}", + purge_feast_metadata=False, + ) + registry = SqlRegistry(config, "test_project", None) + try: + with ( + patch.object(registry.write_engine, "dispose") as write_dispose, + patch.object(registry.read_engine, "dispose") as read_dispose, + ): + registry.reset_after_fork() + + write_dispose.assert_called_once_with(close=False) + read_dispose.assert_called_once_with(close=False) + finally: + registry.teardown() + + def test_sql_registry(sqlite_registry): """ Test the SQL registry diff --git a/sdk/python/tests/unit/test_feature_server.py b/sdk/python/tests/unit/test_feature_server.py index fd1b55ea460..7825481cd56 100644 --- a/sdk/python/tests/unit/test_feature_server.py +++ b/sdk/python/tests/unit/test_feature_server.py @@ -16,7 +16,7 @@ import time from collections import Counter from types import SimpleNamespace -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch import pytest from fastapi.testclient import TestClient @@ -782,6 +782,47 @@ def test_gunicorn_post_worker_init_starts_resource_and_freshness_monitoring(): mock_fm.init_worker_freshness_monitoring.assert_called_once_with(mock_store) +@pytest.mark.skipif(sys.platform == "win32", reason="Gunicorn is not used on Windows") +@pytest.mark.parametrize("metrics_enabled", [True, False]) +def test_gunicorn_post_fork_hook_is_registered(metrics_enabled): + from feast.feature_server import FeastServeApplication, _gunicorn_post_fork + + mock_store = MagicMock() + with patch("feast.feature_server.get_app"): + app = FeastServeApplication( + store=mock_store, + metrics_enabled=metrics_enabled, + registry_ttl_sec=5, + workers=2, + ) + + assert app.cfg.post_fork.func is _gunicorn_post_fork + assert app.cfg.post_fork.args == (mock_store,) + + +@pytest.mark.skipif(sys.platform == "win32", reason="Gunicorn is not used on Windows") +def test_gunicorn_post_fork_resets_registry(): + from feast.feature_server import _gunicorn_post_fork + + mock_store = MagicMock() + _gunicorn_post_fork(mock_store, server=MagicMock(), worker=MagicMock()) + + mock_store._registry.reset_after_fork.assert_called_once_with() + + +@pytest.mark.skipif(sys.platform == "win32", reason="Gunicorn is not used on Windows") +def test_gunicorn_post_fork_does_not_build_registry(): + from feast.feature_server import _gunicorn_post_fork + + mock_store = MagicMock() + mock_store._registry = None + registry = PropertyMock() + type(mock_store).registry = registry + _gunicorn_post_fork(mock_store, server=MagicMock(), worker=MagicMock()) + + registry.assert_not_called() + + def test_get_online_features_returns_feature_view_version_metadata(test_client): """``include_feature_view_version_metadata=True`` must surface the ``feature_view_metadata`` block over REST, like it does on the proto.""" From 8557e38c471b4d3e5ea6c84f653784af511f2f9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20S=C3=A1nchez?= Date: Wed, 28 Oct 2026 11:37:59 +0100 Subject: [PATCH 2/2] docs: explain why the post-fork hook reads store._registry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Carlos Sánchez --- sdk/python/feast/feature_server.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sdk/python/feast/feature_server.py b/sdk/python/feast/feature_server.py index 2fb5504bf46..52202ff213a 100644 --- a/sdk/python/feast/feature_server.py +++ b/sdk/python/feast/feature_server.py @@ -1301,6 +1301,9 @@ def load(self): def _gunicorn_post_fork(store: "feast.FeatureStore", server, worker): """Give each Gunicorn worker its own registry connections after fork.""" + # store._registry and not store.registry: a worker that inherited no + # registry builds its own on first use, with its own connections, so + # this hook must not build one here. if store._registry is not None: store._registry.reset_after_fork()