Repository navigation
feat: configurable polling interval, per-key pollers, refresh backoff - #173
Open
vazarkevych wants to merge 10 commits into
Open
vazarkevych wants to merge 10 commits into
vazarkevych wants to merge 10 commits into
Conversation
start_background_refresh() returned early whenever *a* refresh thread was already running, regardless of which connection it was polling for. The second SDK connection in a process therefore got no background refreshes at all — it silently relied on whatever the first key happened to fetch. Pollers are now tracked per (api_host, client_key), each with its own stop event. stop_background_refresh() gains optional api_host/client_key arguments to stop a single connection; with no arguments it still stops everything, which is what a full teardown wants. GrowthBook.destroy() now passes its own connection, so destroying one instance no longer kills another instance's poller.
The sync worker retried at the configured interval forever, so an unreachable CDN kept costing a request every interval from every process. It now backs off exponentially from the interval, capped at five minutes, and resets on the first success. Jitter is proportional rather than a flat window, so many clients retrying the same host spread out instead of re-colliding on the next tick. The helper is shared-shaped (`backoff_delay(base, attempt, cap)`) so the async client's BackoffStrategy can be folded into it later; it is left alone here to keep this commit to the failure path that had no backoff at all. Note the ordinary failure path is `_fetch_features` returning None rather than raising — the previous code only logged there, which is why the missing backoff was easy to overlook.
`Options.polling_interval` (seconds) makes the async client refresh features on a fixed schedule. Previously the built-in HTTP refresh ran at a hardcoded 60s with no way to configure it. Two properties make the option mean what it says: It bypasses the feature cache. The existing loop went through `load_features_async`, which returns the cached payload when it is still fresh, so any interval shorter than `cache_ttl` issued no requests at all — it re-read the cache and slept again. Verified: at a 50ms interval with a 60s cache_ttl, 0.6s of polling made 1 request before this change and 12 after. It is orthogonal to `refresh_strategy` rather than another strategy value, so it runs alongside SSE. That is the case worth supporting: a stream blocked by a proxy is indistinguishable from a stream with no events yet, and polling is what keeps such an app refreshing. Enabling it is opt-in, so no existing deployment changes its traffic on upgrade. Out-of-range values are rejected with a warning rather than clamped. `Event.wait()` and `asyncio.sleep()` both return immediately on a negative delay, so silently reinterpreting a typo as "poll as fast as possible" would turn a config slip into a request flood; leaving polling off and saying so is the safer failure. Remote-eval mode warns and ignores it — payloads there are per-user, so there is no global payload to poll for. The sync class keeps `stale_while_revalidate` + `stale_ttl`, which already fetches directly rather than through the cache; it is documented as the equivalent rather than given a second spelling.
…nterval - Polling gets its own task (`_poll_task`). `_start_sse_refresh` had already set `_refresh_task`, so with SSE + `polling_interval` the HTTP loop returned immediately and never polled. `stop_refresh` now cancels and awaits both. - The async loop treated a `None` fetch (the ordinary failure path) as success and reset the backoff. Both `None` and exceptions now count as failures and use `backoff_delay(interval, failures)`, the same helper as the sync worker, instead of `BackoffStrategy`, whose 1s start would retry faster than the configured interval. - `backoff_delay` clipped below `base` when the interval exceeded the 300s cap; the cap is now `max(cap, base)`. - The SSE + polling test stubs only the network and asserts fetches happen.
destroy() stopped the poller for every instance on the same key, so destroying a per-request instance stopped refreshes for a long-lived one. Instances now take a lease on the shared poller and it stops when the last lease is released; a lease on a poller that was hard-stopped since can't stop its replacement, and a second destroy() is a no-op. stale_ttl is the sync poller's interval and was used unchecked, so stale_ttl=-1 was a tight request loop. It now goes through the same validation as polling_interval: out-of-range values log a warning and leave the poller off.
# Conflicts: # tests/test_growthbook.py
…er errors out of backoff - backoff_delay raised OverflowError once failures reached 1024 (base * 2**n no longer fits a float). After a multi-day outage or a wrong client key the sync worker then spun without waiting and the async poll task died. Cap the exponent. - Async polling counted an exception from the update handler as a failed fetch and backed off although the CDN answered. Log it separately. - Instances on one key share a poller, so a later instance's interval was silently ignored (sync and async). Warn when it differs and document that the first instance's settings apply. - README: describe the real backoff range (jitter up to 2x), what an invalid polling_interval falls back to, and that stale_ttl over a day no longer polls.
Confidence Score: 5/5
[Medium impact] The PR appears safe to merge; the callback-removal race is fixed. Reviews (4) · Last reviewed commit: "fix: guard feature update callback chang..." · Reviewed by Greptile |
…ck SSE, reject NaN intervals - The feature update callback list is shared by every connection in the process, and each key's poller broadcast to all of it, so two SDK connections kept overwriting each other's flags. Callbacks can now be registered for an (api_host, client_key); GrowthBook does, and pollers and loads notify with their key. Unkeyed callbacks still hear everything. - With SSE and polling, an inline SSE payload applied while a poll's fetch was in flight could be overwritten by the poll's older response. Count applied updates and drop a polled payload superseded during its fetch. - validate_polling_interval accepted NaN (both range checks are False), and Event.wait(nan) doesn't wait. Reject non-finite values.
Collaborator
Author
|
@greptile review |
Routing callbacks by connection went through a dict keyed by the callback, so an unhashable callable (e.g. a non-frozen dataclass with __call__) raised TypeError in notify and stopped every later callback. Store each callback with its connection as a pair in the existing list instead; add and remove keep the identity-then-equality match of the old `in` check.
Collaborator
Author
|
@greptile review |
add/remove find an entry and then change it by index. Instances destroyed from two threads could shift the list in between, deleting a live client's callback or failing with IndexError; the list.remove() this replaced did the search and delete in one call. Guard both with a lock and snapshot the list under it before notifying.
Collaborator
Author
|
@greptile review |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What and why
Background feature refresh had four problems:
load_features_async, which returns the cached payload while it's fresh, so any interval shorter thancache_ttlsent no requests. At a 50ms interval with a 60scache_ttl, 0.6s of polling made 1 request before and 12 after.start_background_refresh()returned early if any refresh thread was running, so a second SDK connection got no background refreshes._fetch_featuresreturningNone, not raising, which is why this was easy to miss.Event.wait()andasyncio.sleep()return immediately on a negative delay, so a negative interval was a tight request loop.What changed
Options.polling_interval(seconds, async client, opt-in). Polling then bypasses the cache, and it runs alongsiderefresh_strategyrather than replacing it, so it works together with SSE:A stream blocked by a proxy looks like a stream with no events yet, and polling keeps such an app refreshing. Polling has its own task, and
stop_refresh()cancels both. A polled payload superseded by an SSE update during its fetch is dropped, so polling can't roll back newer flags. Remote-eval mode warns and ignores the option, since payloads there are per-user.Per-key pollers (sync): one poller per
(api_host, client_key), shared by all instances on that key.destroy()releases the instance's share, and the poller stops when the last instance is destroyed. Callingdestroy()twice is safe.stop_background_refresh()takes an optional host and key to stop one poller; with no arguments it stops all of them, as before.Connections stay isolated (sync): feature update callbacks can be registered for an
(api_host, client_key), andGrowthBookdoes. Each connection now receives only its own payloads (they used to be broadcast to every connection in the process). Callbacks registered without a key still receive everything.First instance's settings win: the first instance on a key sets the poller's interval,
cache_ttland decryption key. A later instance with a different interval gets a warning. Async works the same way, since there is one repository per key.Backoff (sync and async): after a failure (
Noneor an exception) the wait doubles from the interval up to 5 minutes or the interval, whichever is longer. Proportional jitter then stretches it by up to 2x, and it resets on the next success. It never goes below the interval and stays bounded however long an outage lasts. In async, an error in the update handler is logged but doesn't count as a failed fetch.Validation: non-positive, non-finite, non-numeric or over-a-day values are rejected with a warning instead of clamped:
stale_ttl/refresh_interval: the poller stays off. Astale_ttlabove a day used to poll and now doesn't.polling_interval: the client refreshes as if it were unset.The sync client keeps
stale_while_revalidate+stale_ttl, which already fetches directly. The README documents it as the equivalent.README: new "Polling" section.
Not included: automatic fallback from SSE to polling. It would start sending requests for every user whose stream is already silently broken, which is a traffic change that shouldn't ride along here. The option gives the same thing explicitly.
How to test
pytest tests/test_growthbook.py tests/test_growthbook_client.py -k "poll or poller or backoff or stale_ttl or background_refresh or update_handler or feature_update_callback or roll_back"23 new tests:
Nonefetches back off, handler errors don't, a secondpolling_intervalon the same key warns;destroy(), doubledestroy(), stale leases, a mismatched interval warns, invalidstale_ttl/ interval;Full suite with current
mainmerged: 1967 passed. The 2cachefixture errors intest_growthbook_client.pyalso happen onmain.Size
Production code +373 / −75, tests +554 / −12, README +57. About 990 lines, more than half of it tests. If that's too much for one review, the sync part (per-key pollers, isolation, backoff) and the async
polling_intervalcould be split.Migration
None for existing configs, except a
stale_ttlabove one day, which now disables background refresh with a warning. Polling at a new interval is opt-in.stop_background_refresh()without arguments andadd_feature_update_callback(callback)without a key behave as before.