Skip to content
Merged
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
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
import os
import threading
from datetime import timedelta

Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()

Expand All @@ -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:
Expand Down
27 changes: 26 additions & 1 deletion tests/test_octopus_feature_provider.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import base64
import logging
import os
import threading
import time
from collections.abc import Callable, Iterator
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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


Expand Down