Repository navigation
feat: poll manifest changes and shutdown cleanly - #22
Conversation
e571feb to
7238877
Compare
| 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() |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
A new cancellation signal for each initialize
| self._evaluator = FeatureFlagEvaluator.empty() | ||
| self._api_client.open() | ||
|
|
||
| _join_unless_current(previous_polling_thread) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
Periodic polling loop here.
| self._evaluator = FeatureFlagEvaluator.empty() | ||
| if not stop_requested.is_set(): | ||
| _logger.exception(_INITIAL_FETCH_FAILED) | ||
| return |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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_hashmeans every poll fetches again. Each failure logs a WARNING from the API client, thenERROR: ... 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
ContentHashCheckErrorgoes 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?
There was a problem hiding this comment.
👍 Nice one, thanks. I have updated the PR to tweak the log message and log ContentHashCheckError differently.
|
Everything looks fine to me, claude found one nit, but I don't think it's blocking |
| # 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( |
There was a problem hiding this comment.
🤖 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.pyor a module the tasks import) - uWSGI with default settings (
lazy-apps = false) - Gunicorn with
--preload/preload_app = True multiprocessingwith theforkstart 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:
- Minimum: say in the README that the provider has to be set after the fork, i.e. per worker or in a startup hook.
- Robust: in
FeatureFlagEvaluatorCache, registeros.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 aweakrefso the hook doesn't keep it alive.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
@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( |
There was a problem hiding this comment.
🤖 test_shutdown_during_initialization_discards_the_initial_fetch_and_stops_polling
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
shutdownis called while the request for the first fetch is in flight,shutdowncloses the httpx client will leave the request hanging.I also looked into Python's
asyncio(for easier request cancellation) andThreadPool(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