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
57 changes: 56 additions & 1 deletion src/octopus_openfeature_provider/_feature_flag_api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import base64
import binascii
import json
import logging

import httpx
Expand All @@ -19,29 +20,64 @@
_logger = logging.getLogger(__name__)

EVALUATIONS_PATH = "/api/feature-flags/evaluations/v4/"
CHECK_PATH = "/api/feature-flags/check/v4/"
AUTHORIZATION_HEADER = "Authorization"
OCTOPUS_CLIENT_HEADER = "X-Octopus-Client"
RELEASE_VERSION_HEADER = "X-Release-Version"
CONTENT_HASH_HEADER = "ContentHash"
_PROVIDER_NAME = "openfeature-provider-python"


class ContentHashCheckError(Exception):
"""The check endpoint didn't return a usable content hash."""


class FeatureFlagApiClient:
"""Retrieves evaluations from the feature flags service."""
"""Retrieves evaluations and checks for changes from the feature flags service."""

def __init__(self, configuration: OctopusFeatureConfiguration) -> None:
self._server_url = configuration._server_url.rstrip("/")
self._headers = _build_headers(configuration)

request_timeout = configuration.request_timeout.total_seconds()
supplied_client = configuration.http_client
self._owns_client = supplied_client is None
if supplied_client is None:
self._client = httpx.Client(timeout=request_timeout)
self._timeout = self._client.timeout
else:
self._client = supplied_client
self._timeout = _shorter_timeout(supplied_client.timeout, request_timeout)

def open(self) -> None:
if self._owns_client and self._client.is_closed:
self._client = httpx.Client(timeout=self._timeout)

def close(self) -> None:
"""Close the HTTP client only if the provider created it"""
if self._owns_client:
self._client.close()
Comment on lines +53 to +59

@yangguoif yangguoif Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Only do this if consumer does not pass in a http_client, so that we do not close the http client consumer passed in unexpectedly.


def have_features_changed(self, content_hash: bytes) -> bool:
if not content_hash:
return True

response = self._client.get(
self._server_url + CHECK_PATH,
headers=self._headers,
timeout=self._timeout,
)

if not response.is_success:
raise ContentHashCheckError(
f"Feature flag check from {self._server_url} had unsuccessful status {response.status_code}"
)

return (
_parse_check_content_hash(response.content, self._server_url)
!= content_hash
)

def get_server_side_evaluations(self) -> EvaluationResponse | None:
response = self._client.get(
self._server_url + EVALUATIONS_PATH,
Expand Down Expand Up @@ -99,6 +135,25 @@ def get_server_side_evaluations(self) -> EvaluationResponse | None:
return None


def _parse_check_content_hash(content: bytes, server_url: str) -> bytes:
invalid = ContentHashCheckError(
f"Feature flag check from {server_url} did not return a valid content hash"
)
try:
body = json.loads(content)
except ValueError as error:
raise invalid from error

raw_content_hash = body.get("contentHash") if isinstance(body, dict) else None
if not isinstance(raw_content_hash, str) or not raw_content_hash:
raise invalid

try:
return base64.b64decode(raw_content_hash, validate=True)
except binascii.Error as error:
raise invalid from error


def _build_headers(configuration: OctopusFeatureConfiguration) -> dict[str, str]:
headers = {
AUTHORIZATION_HEADER: f"Bearer {configuration.client_identifier}",
Expand Down
160 changes: 145 additions & 15 deletions src/octopus_openfeature_provider/_feature_flag_evaluator_cache.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,168 @@
import logging
import threading
from datetime import timedelta

from octopus_openfeature_provider._feature_flag_api_client import FeatureFlagApiClient
from octopus_openfeature_provider._feature_flag_api_client import (
ContentHashCheckError,
FeatureFlagApiClient,
)
from octopus_openfeature_provider._feature_flag_evaluator import FeatureFlagEvaluator

_logger = logging.getLogger(__name__)

POLLING_THREAD_NAME = "octopus-openfeature-provider-polling"

_INITIAL_FETCH_FAILED = "Failed to retrieve feature manifest during initialization. Falling back to no evaluations, defaults will be used during evaluation."
_REFRESH_FAILED = (
"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."


class FeatureFlagEvaluatorCache:
"""Holds the evaluator the provider resolves flags against.
"""Holds the evaluator the provider resolves flags against, and keeps it
updated by polling the feature flags service.

Until a fetch succeeds it holds an empty evaluator, so every flag is
missing.
missing. A failed refresh keeps the last good evaluator.
"""

def __init__(self, client: FeatureFlagApiClient) -> None:
self._client = client
def __init__(
self, api_client: FeatureFlagApiClient, poll_interval: timedelta
) -> None:
self._api_client = api_client
self._poll_interval_seconds = poll_interval.total_seconds()
self._evaluator = FeatureFlagEvaluator.empty()

# The SDK may call initialize and shutdown on different threads,
# while the polling thread runs. The lock stops them from interfering.
# Reads of _evaluator don't need this lock.
self._lock = threading.Lock()
# Set to stop the work that initialize call started: its initial fetch
# and the polling after it. Each initialize call replaces it with a new
# event, so a fetch or refresh left over from an earlier call can tell
# it's been stopped, and won't install evaluations or outlive shutdown.
self._stop_requested = threading.Event()
self._polling_thread: threading.Thread | None = None

def get_evaluator(self) -> FeatureFlagEvaluator:
return self._evaluator

def initialize(self) -> None:
"""Fetch the evaluations. Never raises."""
"""Fetch the evaluations and start polling. Never raises."""
with self._lock:
previous_polling_thread = self._signal_stop()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In case the openfeature SDK call initialize -> shutdown -> initialize for the same instance.

stop_requested = threading.Event()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

A new cancellation signal for each initialize

self._stop_requested = stop_requested
self._evaluator = FeatureFlagEvaluator.empty()
self._api_client.open()

_join_unless_current(previous_polling_thread)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

wait for the previous polling thread if there is any, so that there is alway only one daemon thread for http request, and we can make sure all the thread are cleaned up.


# The initial fetch runs on the polling thread too, so every request
# is made there and shutdown only has to wait for that thread before
# it closes the HTTP client.
initial_fetch_done = threading.Event()
polling_thread = threading.Thread(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 Polling stops in servers that fork after the provider is set

A forked child process gets only the thread that called fork(). If set_provider runs before the server forks its workers, each worker inherits _polling_thread pointing at a thread that doesn't run in that process. It also inherits the parent's httpx connection pool. The worker then serves the manifest it had at startup indefinitely, and nothing is logged.

Affected setups:

  • Celery with the default prefork pool, when the provider is set at import time (e.g. in celery.py or a module the tasks import)
  • uWSGI with default settings (lazy-apps = false)
  • Gunicorn with --preload / preload_app = True
  • multiprocessing with the fork start method (the default on Linux up to Python 3.13)

Not affected: Gunicorn with default settings, Uvicorn --workers (uses spawn), and anything that sets the provider in a per-worker startup hook such as a FastAPI lifespan.

Suggested options:

  1. Minimum: say in the README that the provider has to be set after the fork, i.e. per worker or in a startup hook.
  2. Robust: in FeatureFlagEvaluatorCache, register os.register_at_fork(after_in_child=...) to clear the stale thread and lock state, create a fresh httpx client if the provider owns it, and restart polling if it was running. Hold the cache through a weakref so the hook doesn't keep it alive.

@yangguoif yangguoif Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hey @liamhughes , thanks for catching this issue.

I have done some reading about it, instead of auto-fixing the issue (e.g. with register_at_fork), I think we should just raise warning when the consumer calling fork() and document possible solution.

Reasoning:

This issue only happen if consumer sets the provider before calling fork(), but this is not really a good practice. If developer wants to kick off something in a new process, then shouldn't the provider being initialised in that new process? Documentation side, os.fork() is also calling this out since 3.12, and there seems also be actions in Python ecosystem for this. There are library maintainer tends to build safety net for this bad practice, but from this CPython maintainer: "It is impossible to safely code threads that can be used in an application that calls fork() in Python because the CPython runtime itself is by definition unsafe for use after fork()".

However, we should resolve the problem that this fails silently, so I think we can log warning when this happens (forked process has different pid), and suggesting setup the new provider in the worker.

What do you think?

@liamhughes liamhughes Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@yangguoif, thank you for digging into this. It definitely seems like a complicated space.

Given we are 0.1.0, I think it is reasonable to leave it, as you say, and see how folks go with it in real applications.

Logging a warning sounds great.

target=self._poll,
args=(stop_requested, initial_fetch_done),
name=POLLING_THREAD_NAME,
daemon=True,
)
with self._lock:
if stop_requested.is_set():
return
polling_thread.start()
self._polling_thread = polling_thread

initial_fetch_done.wait()

def shutdown(self) -> None:
"""Stop polling, wait for a fetch or refresh in flight to finish, and
close the HTTP client if the provider created it."""
with self._lock:
stop_requested = self._stop_requested
polling_thread = self._signal_stop()

_join_unless_current(polling_thread)

@yangguoif yangguoif Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

wait for current in flight request before closing the http client, as documented.


with self._lock:
# If the cache was initialized again while this waited, that later
# initialize call owns the HTTP client now.
if self._stop_requested is stop_requested:
self._api_client.close()

def _signal_stop(self) -> threading.Thread | None:
self._stop_requested.set()
polling_thread = self._polling_thread
self._polling_thread = None
return polling_thread

def _poll(
self, stop_requested: threading.Event, initial_fetch_done: threading.Event
) -> None:
try:
self._initial_fetch(stop_requested)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Initial fetch is moved to here, so that the request for initial fetching is sent in the same thread as periodic polling.

finally:
initial_fetch_done.set()

while not stop_requested.wait(self._poll_interval_seconds):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Periodic polling loop here.

self._refresh(stop_requested)

def _initial_fetch(self, stop_requested: threading.Event) -> None:
"""Never raises. A failed fetch leaves the empty evaluator."""
try:
response = self._client.get_server_side_evaluations()
response = self._api_client.get_server_side_evaluations()
if response is None:
return
evaluator = FeatureFlagEvaluator(response)
except Exception:
_logger.exception(
"Failed to retrieve feature manifest during initialization. Falling back to no evaluations, defaults will be used during evaluation."
)
self._evaluator = FeatureFlagEvaluator.empty()
if not stop_requested.is_set():
_logger.exception(_INITIAL_FETCH_FAILED)
return

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Because we already set the self.evaluator to FeatureFlagEvaluator.empty() in __init__, so we do not really need to set it to the empty evaluator again as previous code.


self._evaluator = (
FeatureFlagEvaluator(response)
if response is not None
else FeatureFlagEvaluator.empty()
self._install_evaluator(evaluator, stop_requested)

def _refresh(self, stop_requested: threading.Event) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Refresh failures log a misleading error, often with a stack trace, every poll

  • No manifest loaded (for example a wrong client identifier): an empty content_hash means every poll fetches again. Each failure logs a WARNING from the API client, then ERROR: ... Retaining the existing evaluations. That repeats every minute by default, and there are no evaluations to retain, which points whoever is on call the wrong way.
  • The check endpoint returns a non-2xx status: the ContentHashCheckError goes to _logger.exception, so a plain 500 logs a full stack trace every poll. The error message already has the URL and status.

Could we use a different message when no manifest is held, and log ContentHashCheckError without the stack trace, keeping traces for unexpected exceptions only?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

👍 Nice one, thanks. I have updated the PR to tweak the log message and log ContentHashCheckError differently.

"""Never raises. A failed refresh keeps the current evaluator, and the
next interval tries again."""
current_evaluator = self._evaluator
failed_message = (
_REFRESH_FAILED
if current_evaluator.content_hash
else _FETCH_WITHOUT_MANIFEST_FAILED
)
try:
if not self._api_client.have_features_changed(
current_evaluator.content_hash
):
return

response = self._api_client.get_server_side_evaluations()
if response is None:
_logger.error(failed_message)
return

evaluator = FeatureFlagEvaluator(response)
except ContentHashCheckError as error:
if not stop_requested.is_set():
_logger.error("%s %s", failed_message, error)
return
except Exception:
if not stop_requested.is_set():
_logger.exception(failed_message)
return

self._install_evaluator(evaluator, stop_requested)

def _install_evaluator(
self, evaluator: FeatureFlagEvaluator, stop_requested: threading.Event
) -> None:
with self._lock:
if not stop_requested.is_set():
self._evaluator = evaluator


def _join_unless_current(thread: threading.Thread | None) -> None:
if thread is not None and thread is not threading.current_thread():
thread.join()
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ class OctopusFeatureConfiguration:
the response. It doesn't limit a request's total time. If
`http_client` has its own timeouts, the shorter limit applies to
each phase. Keep it well under `cache_duration` so a stalled
request can't hold up the next poll. Must be positive.
request can't hold up the next poll. Must be positive. Shutting the
provider down waits for a request in flight.

@yangguoif yangguoif Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I couldn't find a proper way to cancel the request with the current implementation.

To cancel a request in flight with httpx properly, most of the researches point to asyncio, which is not a choice here, because asyncio requires a event loop which is more of a consumer choice, but not a choice for library implementation.

Therefore updating the doc here to be more specific.

release_version_override: Overrides the application release version
embedded in `client_identifier`. It's sent to the feature flags
service only when it isn't `None`.
Expand Down
20 changes: 17 additions & 3 deletions src/octopus_openfeature_provider/_octopus_feature_provider.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import copy
import threading
from collections.abc import Mapping, Sequence
from datetime import timedelta

Expand All @@ -16,6 +17,8 @@
OctopusFeatureConfiguration,
)

MAX_CACHE_DURATION = timedelta(seconds=threading.TIMEOUT_MAX)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is a different value from the Typescript implementation, I decided to go with the constant native for Python to avoid magic number.



class OctopusFeatureProvider(AbstractProvider):
"""An OpenFeature provider for Octopus feature flags.
Expand All @@ -25,7 +28,8 @@ class OctopusFeatureProvider(AbstractProvider):

Raises:
ValueError: If the configuration's client identifier is empty, or its
`cache_duration` or `request_timeout` isn't positive.
`cache_duration` or `request_timeout` isn't positive, or its
`cache_duration` is longer than `threading.TIMEOUT_MAX` seconds.
TypeError: If the configuration's client identifier isn't a `str`,
or its `cache_duration` or `request_timeout` isn't a `timedelta`.
"""
Expand All @@ -37,14 +41,18 @@ def __init__(self, configuration: OctopusFeatureConfiguration) -> None:
self._configuration = copy.copy(configuration)
_validate(self._configuration)
self._evaluator_cache = FeatureFlagEvaluatorCache(
FeatureFlagApiClient(self._configuration)
FeatureFlagApiClient(self._configuration),
self._configuration.cache_duration,
)

def initialize(self, evaluation_context: EvaluationContext) -> None:
# Never raises, so the SDK reports the provider as ready even when the
# fetch fails. Every flag is then missing.
# fetch fails. Every flag is then missing until a refresh succeeds.
self._evaluator_cache.initialize()

def shutdown(self) -> None:
self._evaluator_cache.shutdown()

def get_metadata(self) -> Metadata:
return Metadata(name="octopus-python-provider")

Expand Down Expand Up @@ -108,6 +116,12 @@ def _validate(configuration: OctopusFeatureConfiguration) -> None:
if not client_identifier.strip():
raise ValueError("client_identifier must not be empty.")
_validate_positive_duration("cache_duration", configuration.cache_duration)
# The polling thread waits this long between checks, and a longer wait
# raises OverflowError there, which would stop polling without a log.
if configuration.cache_duration > MAX_CACHE_DURATION:
raise ValueError(
f"cache_duration must be at most {MAX_CACHE_DURATION}, but was {configuration.cache_duration}."
)
_validate_positive_duration("request_timeout", configuration.request_timeout)


Expand Down
2 changes: 1 addition & 1 deletion tests/public_api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class OctopusFeatureProvider(openfeature.provider.AbstractProvider):
self,
evaluation_context: openfeature.evaluation_context.EvaluationContext,
) -> None
def shutdown(self) -> None
def get_metadata(self) -> openfeature.provider.Metadata
def resolve_boolean_details(
self,
Expand Down Expand Up @@ -63,7 +64,6 @@ class OctopusFeatureProvider(openfeature.provider.AbstractProvider):
on_emit: collections.abc.Callable[[openfeature.provider.FeatureProvider, openfeature.event.ProviderEvent, openfeature.event.ProviderEventDetails], None],
) -> None
def detach(self) -> None
def shutdown(self) -> None
def get_provider_hooks(self) -> list[openfeature.hook.Hook]
async def resolve_boolean_details_async(
self,
Expand Down
Loading