diff --git a/README.md b/README.md index 9d0052d..82befc4 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,33 @@ Call `api.shutdown()` when your application stops, so the provider releases its For more on evaluating flags, see the [OpenFeature evaluation API documentation](https://openfeature.dev/docs/reference/concepts/evaluation-api/). +### Forked processes + +The provider checks for flag changes on a background thread, and a forked process doesn't get a copy of that thread. If you set the provider and then fork, flags in the forked processes stop updating. Instead, create and set a new provider in each process after it's forked: + +```python +from openfeature import api + +from octopus_openfeature_provider import ( + OctopusFeatureConfiguration, + OctopusFeatureProvider, + ProductMetadata, +) + + +# Call this from your server's per-worker startup hook, which runs after the fork. +def set_up_feature_flags() -> None: + provider = OctopusFeatureProvider( + OctopusFeatureConfiguration( + client_identifier="YourClientIdentifier", + product_metadata=ProductMetadata("YourProductName", "1.0.0"), + ) + ) + api.set_provider_and_wait(provider) +``` + +If a process is forked while the provider is polling for changes, the provider logs a warning the first time that process evaluates a flag. + ## Configuration `OctopusFeatureConfiguration` takes these arguments. Pass everything after `product_metadata` by keyword. diff --git a/src/octopus_openfeature_provider/_feature_flag_evaluator_cache.py b/src/octopus_openfeature_provider/_feature_flag_evaluator_cache.py index 5f6875e..136998c 100644 --- a/src/octopus_openfeature_provider/_feature_flag_evaluator_cache.py +++ b/src/octopus_openfeature_provider/_feature_flag_evaluator_cache.py @@ -1,4 +1,5 @@ import logging +import os import threading from datetime import timedelta @@ -17,6 +18,7 @@ "Failed to retrieve updated feature manifest. Retaining the existing evaluations." ) _FETCH_WITHOUT_MANIFEST_FAILED = "Failed to retrieve feature manifest. No evaluations have been retrieved yet, defaults will be used during evaluation." +_FORKED_WHILE_POLLING = "This process was forked while the provider was polling for flag changes on a background thread. Polling doesn't run in a forked process, so flags won't be updated in this process. Create and set a new provider after forking." class FeatureFlagEvaluatorCache: @@ -44,8 +46,16 @@ def __init__( # it's been stopped, and won't install evaluations or outlive shutdown. self._stop_requested = threading.Event() self._polling_thread: threading.Thread | None = None + # The process ID the polling thread runs in, or None when it isn't + # running. A process forked from it gets a copy of the cache but not + # the thread, so evaluations compare this with the current process to + # warn that flags won't update. + self._polling_pid: int | None = None + # The processes that have logged that warning. It's keyed by process. + self._fork_warned_pids: dict[int, object] = {} def get_evaluator(self) -> FeatureFlagEvaluator: + self._check_process_forked() return self._evaluator def initialize(self) -> None: @@ -74,6 +84,7 @@ def initialize(self) -> None: return polling_thread.start() self._polling_thread = polling_thread + self._polling_pid = os.getpid() initial_fetch_done.wait() @@ -96,8 +107,21 @@ def _signal_stop(self) -> threading.Thread | None: self._stop_requested.set() polling_thread = self._polling_thread self._polling_thread = None + self._polling_pid = None return polling_thread + def _check_process_forked(self) -> None: + polling_pid = self._polling_pid + pid = os.getpid() + if polling_pid is None or polling_pid == pid: + return + + # setdefault returns this token only to the call that stored it, to ensure + # a log per process. + token = object() + if self._fork_warned_pids.setdefault(pid, token) is token: + _logger.warning(_FORKED_WHILE_POLLING) + def _poll( self, stop_requested: threading.Event, initial_fetch_done: threading.Event ) -> None: diff --git a/tests/test_octopus_feature_provider.py b/tests/test_octopus_feature_provider.py index 4760cfc..9c4d640 100644 --- a/tests/test_octopus_feature_provider.py +++ b/tests/test_octopus_feature_provider.py @@ -1,5 +1,6 @@ import base64 import logging +import os import threading import time from collections.abc import Callable, Iterator @@ -456,7 +457,7 @@ def test_shutdown_waits_for_a_refresh_in_flight( assert polling_threads() == [] -def test_shutdown_during_initialization_does_not_start_polling( +def test_shutdown_during_initialization_discards_the_initial_fetch_and_stops_polling( feature_flags_server: FakeFeatureFlagsServer, polling_provider: OctopusFeatureProvider, ) -> None: @@ -501,6 +502,30 @@ def test_shutdown_never_closes_a_supplied_http_client( assert not http_client.is_closed +# Forking + + +def test_evaluating_in_a_process_forked_while_polling_warns_once( + polling_provider: OctopusFeatureProvider, + caplog: pytest.LogCaptureFixture, + monkeypatch: pytest.MonkeyPatch, +) -> None: + polling_provider.initialize(EvaluationContext()) + + with caplog.at_level(logging.WARNING, logger=LOGGER): + polling_provider._evaluator_cache.get_evaluator() + assert caplog.messages == [] + + # Look like a process forked from this one. + forked_pid = os.getpid() + 1 + monkeypatch.setattr(os, "getpid", lambda: forked_pid) + polling_provider._evaluator_cache.get_evaluator() + polling_provider._evaluator_cache.get_evaluator() + + [message] = caplog.messages + assert message.startswith("This process was forked while the provider was polling") + + # Boolean evaluation