Repository navigation
fix(state): check state readiness without a thread-pool job per request - #615
Merged
Merged
Conversation
Every request ran rebuild_state through asyncio.to_thread in the app-wide recover_state hook, so a flood of requests to any route took jobs from the worker's shared default thread pool even while state was present. A worker now trusts a successful check for one second without touching Redis, and requests arriving while a check is in flight share it. When state is incomplete, each request still falls back to rebuild_state in a thread as before (one rebuilds under the Redis lock, the rest fail fast with 503), and during the failure cooldown requests fail without a thread. A StateError from a state read, or HyperglassState.clear(), ends the trusted interval so the next request recovers at once. Part of #532.
…h devices Add a Rate limiting section to the reverse proxy page with NGINX limit_req and the third-party caddy-ratelimit rate_limit directive, commented examples in the sample NGINX and Caddy configurations, and link it from the query rate limit page. Part of #532.
- Tie the readiness epoch to the shared is_populated check, and drop the check in mark_stale(), so a request arriving after state was found missing neither joins nor re-arms on an older check. - Mark state stale after HyperglassState.clear() deletes its keys as well as before, so a check running during the deletes cannot leave the window armed. - Plugin managers read the registry with required=True: a missing registry raises StateError and marks state stale, instead of reading as empty and running the query without input validation or output parsing, whose unparsed result would be cached for cache.timeout. Other readers (hyperglass plugins) still read it as empty. - Track the last failed rebuild as None until one happens. With 0.0, in_cooldown() was true for the first 30 seconds of the monotonic clock, i.e. right after the host booted. - Freeze the clock in the API burst test so a slow runner cannot reach the end of the interval. Part of #532.
Show set_real_ip_from/real_ip_header and Caddy's trusted_proxies with their syntax, note that NGINX's realip module is not built by default, and say that caddy-ratelimit's ipv6_prefix needs a build newer than v0.1.0, which ignores it without an error. Part of #532.
- Plugin managers' required registry read also requires plugins.ready, in one MGET. init_user_config() and register_all_plugins() delete it when they start and register_all_plugins() sets it once every plugin is registered, so an empty or partial registry being rebuilt by another worker answers 503 instead of running the query without its plugins and caching the unparsed output. Startup (start()) and state recovery (_initialize) both set it before serving; onboarding uses its own local registry, which ignores required. - in_cooldown() reads _last_failure once: a rebuild finishing in another thread between two reads made it subtract None. - Docs: set trusted_proxies_strict in the Caddy CDN example, so a client-supplied left-most X-Forwarded-For entry cannot choose the rate-limit key. - Update the READY_INTERVAL comment, which still said plugin lists read as empty. Part of #532.
…heck # Conflicts: # CHANGELOG.md # hyperglass/conftest.py
jsenecal
marked this pull request as ready for review
November 25, 2026 21:48
WilhelmZA
approved these changes
Nov 25, 2026
WilhelmZA
left a comment
Collaborator
There was a problem hiding this comment.
Approving at e87b2f82.
Checked the shared readiness check and its one-second trust window, the epoch handling around mark_stale and clear, the cooldown path, the required plugin registry read and its 503, recovery after Redis returns, the reverse-proxy samples and docs, and the test fixture change. All commits are verified and the CI gate passed.
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.
Closes #532
This finishes #532. The query rate limit (option 2) landed in #586 and the Redis socket timeouts in #570. This PR adds the cheap state check (option 3) and the reverse-proxy documentation (option 1).
Problem
The app-wide
recover_statehook ranensure_ready()on every request, andensure_ready()ranrebuild_statethroughasyncio.to_thread. Every request to any route therefore took a job on the worker's shared default thread pool, even when state was already in Redis. A client flooding/api/infoor the static files could delay every other request, including queries.Change
fix(state): check state readiness without a thread-pool job per requestrecovery.ensure_ready(cache)(new) handles the request-path check, andHyperglassState.ensure_ready()calls it:READY_INTERVAL(1 s). Requests in that second make no Redis call and take no thread.is_populatedcheck runs in a thread. Requests that arrive while it runs wait on the same task. The task is shielded, so a cancelled request does not cancel it for the others.rebuild_statein a thread, as before. One request takes the Redis lock and rebuilds. The others get a 503 at once (fix(state): answer 503 instead of waiting for another process rebuild #465). During the failure cooldown, requests now get the 503 without starting a thread. This gives the same answerrebuild_statewould, because the shared check has just confirmed that state is still missing.StateErrorfrom a state property read, orHyperglassState.clear()(before and after its deletes), callsmark_stale(). The next request then checks again instead of trusting the earlier result.mark_stale()also drops the shared check, so a later request starts its own. Each shared check records the epoch it started in, and only a check whose epoch is still current can mark state ready.required=True. Before this change, a registry key missing from Redis (for example, evicted while the rest of state stayed) read as an empty list. During the trusted interval, a query would then run without input validation or output parsing, androutes.pywould cache the unparsedraw_outputforcache.timeout. Now the manager raisesStateError, which answers 503 and marks state stale, so the next request rebuilds.plugins.ready, in oneMGET.init_user_config()andregister_all_plugins()delete that key when they start, andregister_all_plugins()sets it once every plugin is registered. While another worker rebuilds the registry, it may be empty or hold only some plugins, so it doesn't count as ready. Both healthy paths setplugins.readybefore serving: startup (start()callsregister_all_plugins()before uvicorn starts) and recovery (_initialize). Onboarding registers withpersist_ready=False, but into its own local registry, which ignoresrequired.hyperglass build-uirunsinit_user_config()and deletes the key on a shared Redis. That was already treated as lost state before this PR, becauseplugins.readyis inREQUIRED_KEYS, and the next check rebuilds it. Other readers, such ashyperglass plugins, still read a missing registry as empty. The test conftest now seeds an empty registry, because many existing tests ran plugin managers without registering any plugins._last_failurestarted at0.0, soin_cooldown()was true whiletime.monotonic()was under 30. On a host that had just booted, a worker that lost state answered 503 instead of rebuilding.Nonenow means no rebuild has failed yet.in_cooldown()reads it once, so a reset from another thread cannot make it subtractNone.The interval is short and not configurable. A worker can trust state that was flushed from Redis for up to one second, until a read finds a key missing or the next check runs.
/api/healthstill callsensure_ready(), so itsstatecheck can trust a check up to one second old. The health check already runs at most once per second per worker, so I left it on the shared path.docs: reverse-proxy rate limitinginstallation/reverse-proxy.mdxhas a new "Rate limiting" section:limit_req_zone/limit_req/limit_req_status 429. It notes thatlimit_req_zonemust be in thehttpblock, that the default status is 503, how to handle a CDN withrealip, and that each IPv6 address is counted on its own.mholt/caddy-ratelimitrate_limitdirective. It covers building with xcaddy or the download page, the 429 withRetry-After, the default ordering beforebasic_auth, and{client_ip}behind a CDN.set_real_ip_from/real_ip_header(the realip module is not built by default, whichnginx -Vshows), and Caddy'strusted_proxieswithtrusted_proxies_strictand{client_ip}. Without strict mode, Caddy readsX-Forwarded-Forfrom the left, so a client could choose its own key.ipv6_prefix 64: it needs a build newer than v0.1.0, the only tag (@masteror a later release). v0.1.0's parser has no default case for zone subdirectives, so it ignores the option without an error.hyperglass.nginxandCaddyfileinclude the examples, commented out.Tests
hyperglass/state/tests/test_recovery.pyadds 14 tests:clear()ends the interval, including when a check arms it during the deletes.mark_stale()does not join the earlier check, and a joiner on an older epoch does not re-arm.rebuild_statethreads./api/inforequests, with the clock frozen, runs oneis_populated.in_cooldown()survives a concurrent reset.hyperglass/util/tests/test_plugin_registry_lost.py(new) sendsPOST /api/querythrough the full app, with the output stage running. As a control, the query succeeds and is cached when the registry is in place. Then, with the readiness window armed andplugins.inputmissing,plugins.outputmissing, orplugins.readymissing, the query answers 503, nothing is cached, and the window is reset.Against the old
ensure_ready, 5 of these fail. Reverting each review fix fails its test. The existing recovery tests pass unchanged, including the fast-503 tests from #465. The rootconftest.pyresets the readiness state for each test, because each test gets an empty fake Redis.Full suite: 4689 passed, 4 skipped. Ruff and Black are clean.