Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
11 changes: 11 additions & 0 deletions sdk/python/feast/feature_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -1296,6 +1299,14 @@ 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."""
# 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()

def _gunicorn_post_worker_init(store: "feast.FeatureStore", worker):
"""Start per-worker resource and freshness monitoring after Gunicorn forks."""
feast_metrics.init_worker_monitoring()
Expand Down
7 changes: 7 additions & 0 deletions sdk/python/feast/infra/registry/base_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 8 additions & 0 deletions sdk/python/feast/infra/registry/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Engine.dispose(close=...) was added in SQLAlchemy 1.4.33. Feast's core dependency is SQLAlchemy[mypy]>1 (pyproject.toml line 31; line 59 has SQLAlchemy>=1.4.19), and the comment at line 107 of this file says 1.4.x is still supported. On 1.4.0–1.4.32 this call raises; an AI-assisted check against the 1.4.32 and 1.4.33 sources gives:

sqlalchemy 1.4.32: engine.dispose(close=False) -> TypeError: Engine.dispose() got an unexpected keyword argument 'close'
sqlalchemy 1.4.33: engine.dispose(close=False) -> OK

Because this runs in post_fork, an exception there should make the worker exit with a boot error and gunicorn stop the server. That last step comes from reading gunicorn's arbiter, not from running feast serve.

close= was introduced in 1.4.33, but 1.4.33 and 1.4.34 were both yanked from PyPI (an ORM insert regression in 1.4.33, and a caching issue in 1.4.34 that 1.4.35 resolves), which makes 1.4.35 the appropriate minimum supported version. Would raising the floor to SQLAlchemy[mypy]>=1.4.35 work for you?

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.
Expand Down
58 changes: 57 additions & 1 deletion sdk/python/tests/unit/infra/registry/test_sql_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
43 changes: 42 additions & 1 deletion sdk/python/tests/unit/test_feature_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."""
Expand Down
Loading