diff --git a/docs/how-to-guides/online-server-performance-tuning.md b/docs/how-to-guides/online-server-performance-tuning.md index 24d3c5d2238..152affc048a 100644 --- a/docs/how-to-guides/online-server-performance-tuning.md +++ b/docs/how-to-guides/online-server-performance-tuning.md @@ -829,7 +829,7 @@ This exposes a `/metrics` endpoint on port 8000. If the Prometheus Operator's `S | `feast_feature_server_transformation_duration_seconds` | ODFV execution time (requires `track_metrics=True` on the ODFV). | | `feast_feature_server_cpu_usage` | Per-worker CPU. Sustained > 80% means you need more workers or replicas. | | `feast_feature_server_memory_usage` | Per-worker memory. Growing over time may indicate a memory leak — use `maxRequests` to recycle. | -| `feast_feature_server_request_total` | Request throughput and error rates by endpoint and status. | +| `feast_feature_server_request_total` | Request throughput and error rates by endpoint and status. Filter on `status_class="5xx"` to alert on server errors only. | | `feast_feature_freshness_seconds` | Seconds since last materialization per feature view. Alerts you to stale data. | #### Example Prometheus alert rules diff --git a/docs/reference/feature-servers/python-feature-server.md b/docs/reference/feature-servers/python-feature-server.md index f8b79e233d5..94ed4efbede 100644 --- a/docs/reference/feature-servers/python-feature-server.md +++ b/docs/reference/feature-servers/python-feature-server.md @@ -368,7 +368,7 @@ thread from starting). All categories default to `true` except |--------|------|--------|----------|-------------| | `feast_feature_server_cpu_usage` | Gauge | — | `resource` | Process CPU usage % | | `feast_feature_server_memory_usage` | Gauge | — | `resource` | Process memory usage % | -| `feast_feature_server_request_total` | Counter | `endpoint`, `status` | `request` | Total requests per endpoint | +| `feast_feature_server_request_total` | Counter | `endpoint`, `status`, `status_class` | `request` | Total requests per endpoint and response status (see below) | | `feast_feature_server_request_latency_seconds` | Histogram | `endpoint`, `feature_count`, `feature_view_count` | `request` | Request latency with p50/p95/p99 support (`feature_count` is bucketed, see below) | | `feast_online_features_request_total` | Counter | — | `online_features` | Total online feature retrieval requests | | `feast_online_features_entity_count` | Histogram | — | `online_features` | Entity rows per online feature request | @@ -405,6 +405,25 @@ This produces the labels `0`, `1-5`, `6-20`, and `21+`. Note that this only affects the Prometheus label; the `feature_count` field in audit logs (see below) always reports the exact count. +### Request status labels + +`feast_feature_server_request_total` carries two status labels derived from +the HTTP status code the server responds with: + +- `status_class` is the status code class: `2xx`, `4xx` or `5xx`. Use it to + tell client errors (an unknown feature view or feature service, a denied + permission, a materialization that is already running) apart from server + errors. +- `status` is `success` for status codes below 400 and `error` otherwise. + +For example, the server-side error rate per endpoint, excluding client +errors: + +``` +sum by (endpoint) (rate(feast_feature_server_request_total{status_class="5xx"}[5m])) + / sum by (endpoint) (rate(feast_feature_server_request_total[5m])) +``` + ### Per-ODFV transformation metrics The `transformation_duration_seconds` and `write_transformation_duration_seconds` diff --git a/sdk/python/feast/feature_server.py b/sdk/python/feast/feature_server.py index 82b492f2ae6..e963ade846e 100644 --- a/sdk/python/feast/feature_server.py +++ b/sdk/python/feast/feature_server.py @@ -827,7 +827,7 @@ async def vector_store_search( ) -> JSONResponse: with feast_metrics.track_request_latency( "/v1/vector_stores/{vector_store_id}/search" - ): + ) as metrics_ctx: try: feature_view = vs_registry.resolve(vector_store_id) assert_permissions( @@ -854,6 +854,7 @@ async def vector_store_search( ), ) except FeatureViewNotFoundException: + metrics_ctx.status_code = 404 return JSONResponse( status_code=404, content={ @@ -864,6 +865,7 @@ async def vector_store_search( }, ) except ValueError as e: + metrics_ctx.status_code = 422 return JSONResponse( status_code=422, content={ @@ -1027,7 +1029,7 @@ async def materialize( async_mode: bool = Query(False, alias="async"), force: bool = Query(False), ): - with feast_metrics.track_request_latency("/materialize"): + with feast_metrics.track_request_latency("/materialize") as metrics_ctx: fv_names = _authorize_materialize_views( store, request.feature_views, version=request.version ) @@ -1039,6 +1041,7 @@ async def materialize( else: conflict = _check_already_materializing(store, fv_names) if conflict: + metrics_ctx.status_code = conflict.status_code return conflict # Reserve MATERIALIZING before 202 so concurrent requests hit 409. @@ -1086,7 +1089,9 @@ async def materialize_incremental( async_mode: bool = Query(False, alias="async"), force: bool = Query(False), ): - with feast_metrics.track_request_latency("/materialize-incremental"): + with feast_metrics.track_request_latency( + "/materialize-incremental" + ) as metrics_ctx: fv_names = _authorize_materialize_views( store, request.feature_views, version=request.version ) @@ -1098,6 +1103,7 @@ async def materialize_incremental( else: conflict = _check_already_materializing(store, fv_names) if conflict: + metrics_ctx.status_code = conflict.status_code return conflict _update_fv_state(store, fv_names, FeatureViewState.MATERIALIZING) diff --git a/sdk/python/feast/metrics.py b/sdk/python/feast/metrics.py index 4f62814edf3..caf6c9cbe29 100644 --- a/sdk/python/feast/metrics.py +++ b/sdk/python/feast/metrics.py @@ -189,7 +189,7 @@ def build_metrics_flags(metrics_config: Optional[object] = None) -> _MetricsFlag request_count = Counter( "feast_feature_server_request_total", "Total number of requests to the Feast feature server", - ["endpoint", "status"], + ["endpoint", "status", "status_class"], ) request_latency = Histogram( "feast_feature_server_request_latency_seconds", @@ -313,13 +313,47 @@ class RequestMetricsContext: (e.g. ``/get-online-features`` where the feature count is only known after ``_get_features`` succeeds) can set the attributes on the yielded object and they will be picked up in ``finally``. + + ``status_code`` is the HTTP status code of the response. It defaults + to ``200`` and is derived from the exception when the block raises, + so handlers only need to set it when they *return* a non-2xx + response (e.g. a 404 or 409 ``JSONResponse``). """ - __slots__ = ("feature_count", "feature_view_count") + __slots__ = ("feature_count", "feature_view_count", "status_code") - def __init__(self, feature_count: str = "", feature_view_count: str = ""): + def __init__( + self, + feature_count: str = "", + feature_view_count: str = "", + status_code: int = 200, + ): self.feature_count = feature_count self.feature_view_count = feature_view_count + self.status_code = status_code + + +def _status_code_for_exception(exc: Exception) -> int: + """Return the HTTP status code the feature server responds with for *exc*. + + Mirrors the REST exception handling: ``FeastError`` subclasses carry + their own status code, ``HTTPException`` is answered with its status + code, and anything else becomes a 500. + """ + from starlette.exceptions import HTTPException + + from feast.errors import FeastError + + if isinstance(exc, FeastError): + return exc.http_status_code() + if isinstance(exc, HTTPException): + return exc.status_code + return 500 + + +def _status_class(status_code: int) -> str: + """Map an HTTP status code to its class label, e.g. ``404`` -> ``"4xx"``.""" + return f"{status_code // 100}xx" @contextmanager @@ -328,11 +362,16 @@ def track_request_latency( ): """Context manager that records endpoint latency and increments request count. - Yields a :class:`RequestMetricsContext` whose ``feature_count`` and - ``feature_view_count`` attributes can be updated inside the block. - The final values are used when recording the histogram and counter - in ``finally``, so labels are accurate even when they depend on - work done inside the block. + Yields a :class:`RequestMetricsContext` whose ``feature_count``, + ``feature_view_count`` and ``status_code`` attributes can be updated + inside the block. The final values are used when recording the + histogram and counter in ``finally``, so labels are accurate even + when they depend on work done inside the block. + + The request counter is labelled with ``status`` (``success`` for + status codes below 400, ``error`` otherwise) and ``status_class`` + (``2xx``, ``4xx``, ``5xx``, ...), so client errors can be told + apart from server errors. Gated by the ``request`` category flag. """ @@ -342,11 +381,10 @@ def track_request_latency( return start = time.monotonic() - status_label = "success" try: yield ctx - except Exception: - status_label = "error" + except Exception as exc: + ctx.status_code = _status_code_for_exception(exc) raise finally: elapsed = time.monotonic() - start @@ -355,7 +393,11 @@ def track_request_latency( feature_count=ctx.feature_count, feature_view_count=ctx.feature_view_count, ).observe(elapsed) - request_count.labels(endpoint=endpoint, status=status_label).inc() + request_count.labels( + endpoint=endpoint, + status="success" if ctx.status_code < 400 else "error", + status_class=_status_class(ctx.status_code), + ).inc() def track_online_features_entities(entity_count: int): diff --git a/sdk/python/tests/unit/test_metrics.py b/sdk/python/tests/unit/test_metrics.py index 2c856f425ca..84f969cd181 100644 --- a/sdk/python/tests/unit/test_metrics.py +++ b/sdk/python/tests/unit/test_metrics.py @@ -24,7 +24,9 @@ from unittest.mock import MagicMock, patch import pytest +from fastapi import HTTPException +from feast.errors import FeastPermissionError, FeatureViewNotFoundException from feast.metrics import ( _make_metrics_httpd, emit_offline_audit_log, @@ -87,20 +89,20 @@ def _enable_metrics(): class TestTrackRequestLatency: def test_success_increments_counter_and_records_latency(self): before_count = request_count.labels( - endpoint="/test", status="success" + endpoint="/test", status="success", status_class="2xx" )._value.get() with track_request_latency("/test"): pass after_count = request_count.labels( - endpoint="/test", status="success" + endpoint="/test", status="success", status_class="2xx" )._value.get() assert after_count == before_count + 1 def test_error_increments_error_counter(self): before_count = request_count.labels( - endpoint="/test-err", status="error" + endpoint="/test-err", status="error", status_class="5xx" )._value.get() with pytest.raises(ValueError): @@ -108,7 +110,7 @@ def test_error_increments_error_counter(self): raise ValueError("boom") after_count = request_count.labels( - endpoint="/test-err", status="error" + endpoint="/test-err", status="error", status_class="5xx" )._value.get() assert after_count == before_count + 1 @@ -174,7 +176,7 @@ def test_labels_updated_via_yielded_context(self): def test_error_before_labels_set_still_records(self): """Errors before labels are updated still record with default labels.""" before_count = request_count.labels( - endpoint="/early-fail", status="error" + endpoint="/early-fail", status="error", status_class="5xx" )._value.get() with pytest.raises(RuntimeError): @@ -182,7 +184,7 @@ def test_error_before_labels_set_still_records(self): raise RuntimeError("auth failed") after_count = request_count.labels( - endpoint="/early-fail", status="error" + endpoint="/early-fail", status="error", status_class="5xx" )._value.get() assert after_count == before_count + 1 @@ -191,6 +193,69 @@ def test_error_before_labels_set_still_records(self): )._sum.get() assert recorded_sum > 0 + @pytest.mark.parametrize( + "exc,expected_status_class", + [ + (ValueError("boom"), "5xx"), + (FeatureViewNotFoundException("missing_fv", "project"), "4xx"), + (FeastPermissionError("denied"), "4xx"), + (HTTPException(status_code=404), "4xx"), + (HTTPException(status_code=503), "5xx"), + ], + ids=[ + "unhandled_error", + "feast_not_found", + "feast_permission_denied", + "http_404", + "http_503", + ], + ) + def test_status_class_derived_from_exception(self, exc, expected_status_class): + """The status class matches the response the REST exception handling sends.""" + endpoint = f"/status-class-{expected_status_class}-{type(exc).__name__}" + before_count = request_count.labels( + endpoint=endpoint, status="error", status_class=expected_status_class + )._value.get() + + with pytest.raises(type(exc)): + with track_request_latency(endpoint): + raise exc + + after_count = request_count.labels( + endpoint=endpoint, status="error", status_class=expected_status_class + )._value.get() + assert after_count == before_count + 1 + + @pytest.mark.parametrize( + "status_code,expected_status,expected_status_class", + [ + (202, "success", "2xx"), + (404, "error", "4xx"), + (409, "error", "4xx"), + (503, "error", "5xx"), + ], + ) + def test_status_code_set_via_yielded_context( + self, status_code, expected_status, expected_status_class + ): + """Handlers that return a response without raising set its status code on the context.""" + endpoint = f"/returned-{status_code}" + before_count = request_count.labels( + endpoint=endpoint, + status=expected_status, + status_class=expected_status_class, + )._value.get() + + with track_request_latency(endpoint) as ctx: + ctx.status_code = status_code + + after_count = request_count.labels( + endpoint=endpoint, + status=expected_status, + status_class=expected_status_class, + )._value.get() + assert after_count == before_count + 1 + class TestMetricsOptIn: """Verify that when a category is disabled, its helpers are true no-ops.""" @@ -1189,7 +1254,7 @@ def test_get_online_features_records_metrics(self, mock_fs_factory): client = TestClient(get_app(fs)) before_req = request_count.labels( - endpoint="/get-online-features", status="success" + endpoint="/get-online-features", status="success", status_class="2xx" )._value.get() before_entity = online_features_request_count._value.get() @@ -1203,7 +1268,7 @@ def test_get_online_features_records_metrics(self, mock_fs_factory): assert ( request_count.labels( - endpoint="/get-online-features", status="success" + endpoint="/get-online-features", status="success", status_class="2xx" )._value.get() == before_req + 1 ) @@ -1290,6 +1355,71 @@ def test_latency_labels_use_custom_feature_count_bins(self, mock_fs_factory): after_sum = request_latency.labels(**label_set)._sum.get() assert after_sum > before_sum + @pytest.mark.parametrize( + "exc,expected_http_status,expected_status_class", + [ + (FeatureViewNotFoundException("fv", "project"), 404, "4xx"), + (RuntimeError("online store unavailable"), 500, "5xx"), + ], + ids=["not_found", "server_error"], + ) + def test_get_online_features_error_records_status_class( + self, mock_fs_factory, exc, expected_http_status, expected_status_class + ): + from fastapi.testclient import TestClient + + from feast.feature_server import get_app + + fs = mock_fs_factory(online_read=False) + fs.get_online_features = MagicMock(side_effect=exc) + client = TestClient(get_app(fs), raise_server_exceptions=False) + + labels = dict( + endpoint="/get-online-features", + status="error", + status_class=expected_status_class, + ) + before = request_count.labels(**labels)._value.get() + + response = client.post( + "/get-online-features", + json={"features": ["fv:feat1"], "entities": {"id": [1]}}, + ) + + assert response.status_code == expected_http_status + assert request_count.labels(**labels)._value.get() == before + 1 + + def test_materialize_conflict_records_4xx(self, mock_fs_factory): + from fastapi.testclient import TestClient + + from feast.feature_server import get_app + from feast.feature_view import FeatureViewState + + fs = mock_fs_factory() + fv = MagicMock() + fv.name = "fv1" + fv.state = FeatureViewState.MATERIALIZING + fs._validate_materialize_version.return_value = None + fs._get_feature_views_to_materialize.return_value = [fv] + fs.registry.get_feature_view.return_value = fv + client = TestClient(get_app(fs)) + + labels = dict(endpoint="/materialize", status="error", status_class="4xx") + before = request_count.labels(**labels)._value.get() + + response = client.post( + "/materialize?async=true", + json={ + "feature_views": ["fv1"], + "start_ts": "2021-01-01T00:00:00", + "end_ts": "2021-01-02T00:00:00", + }, + ) + + assert response.status_code == 409 + assert request_count.labels(**labels)._value.get() == before + 1 + fs.materialize.assert_not_called() + def test_push_records_metrics(self, mock_fs_factory): from fastapi.testclient import TestClient