Skip to content

feat: poll manifest changes and shutdown cleanly - #22

Merged
yangguoif merged 5 commits into
mainfrom
yangguo/BMBB-1518-poll-manifest-and-shutdown
Nov 24, 2026
Merged

yangguoif merged 5 commits into
mainfrom
yangguo/BMBB-1518-poll-manifest-and-shutdown

Conversation

@yangguoif

Copy link
Copy Markdown
Contributor

Background

Currently the provider only fetches the feature flag manifest when initialised, and does not handle shutdown nicely (e.g. not closing the httpx client)

Result

This PR

  • adds a periodic polling in a daemon thread to keep the manifest updated
  • moves the initial fetch into the polling thread, so that all the request is through this thread, which is easier to manage and avoid race condition. e.g. shutdown is called while the request for the first fetch is in flight, shutdown closes the httpx client will leave the request hanging.
  • handles shutdown cleanly

I also looked into Python's asyncio (for easier request cancellation) and ThreadPool (for easier thread management), but neither of them is a good fit here.

Testing

Added unit test, and also did manual test by using a fastAPI app consuming the provider.

Screen.Recording.2026-11-24.at.4.29.53.PM.mov

@yangguoif
yangguoif requested a review from a team as a code owner November 24, 2026 03:39
@yangguoif
yangguoif force-pushed the yangguo/BMBB-1518-poll-manifest-and-shutdown branch from e571feb to 7238877 Compare November 24, 2026 03:42
Comment on lines +53 to +59
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()

@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.

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.

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.

"""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.

"""Fetch the evaluations and start polling. Never raises."""
with self._lock:
previous_polling_thread = self._signal_stop()
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._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.

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.

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._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._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.

@lourens-octopus

Copy link
Copy Markdown
Contributor

Everything looks fine to me, claude found one nit, but I don't think it's blocking

@yangguoif
yangguoif merged commit 80ed4b0 into main Nov 24, 2026
17 checks passed
@yangguoif
yangguoif deleted the yangguo/BMBB-1518-poll-manifest-and-shutdown branch November 24, 2026 21:35
# 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.

assert polling_threads() == []


def test_shutdown_during_initialization_does_not_start_polling(

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.

🤖 test_shutdown_during_initialization_discards_the_initial_fetch_and_stops_polling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants