Skip to content

fix(state): check state readiness without a thread-pool job per request - #615

Merged
jsenecal merged 7 commits into
mainfrom
fix/532-cheap-state-check
Nov 25, 2026
Merged

jsenecal merged 7 commits into
mainfrom
fix/532-cheap-state-check

Conversation

@jsenecal

Copy link
Copy Markdown
Collaborator

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_state hook ran ensure_ready() on every request, and ensure_ready() ran rebuild_state through asyncio.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/info or the static files could delay every other request, including queries.

Change

fix(state): check state readiness without a thread-pool job per request

recovery.ensure_ready(cache) (new) handles the request-path check, and HyperglassState.ensure_ready() calls it:

  • Hot path: after a successful check, a worker trusts that state is present for READY_INTERVAL (1 s). Requests in that second make no Redis call and take no thread.
  • Shared check: after that, one is_populated check 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.
  • Recovery is unchanged: if state is incomplete, each request still calls rebuild_state in 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 answer rebuild_state would, because the shared check has just confirmed that state is still missing.
  • Ending the interval early: a StateError from a state property read, or HyperglassState.clear() (before and after its deletes), calls mark_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.
  • Plugin registry: plugin managers now read the registry with 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, and routes.py would cache the unparsed raw_output for cache.timeout. Now the manager raises StateError, which answers 503 and marks state stale, so the next request rebuilds.
  • Registry readiness: the required read also requires plugins.ready, in one MGET. init_user_config() and register_all_plugins() delete that key when they start, and register_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 set plugins.ready before serving: startup (start() calls register_all_plugins() before uvicorn starts) and recovery (_initialize). Onboarding registers with persist_ready=False, but into its own local registry, which ignores required. hyperglass build-ui runs init_user_config() and deletes the key on a shared Redis. That was already treated as lost state before this PR, because plugins.ready is in REQUIRED_KEYS, and the next check rebuilds it. Other readers, such as hyperglass 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.
  • Cooldown after boot (pre-existing): _last_failure started at 0.0, so in_cooldown() was true while time.monotonic() was under 30. On a host that had just booted, a worker that lost state answered 503 instead of rebuilding. None now means no rebuild has failed yet. in_cooldown() reads it once, so a reset from another thread cannot make it subtract None.

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/health still calls ensure_ready(), so its state check 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 limiting

  • installation/reverse-proxy.mdx has a new "Rate limiting" section:
    • NGINX: limit_req_zone/limit_req/limit_req_status 429. It notes that limit_req_zone must be in the http block, that the default status is 503, how to handle a CDN with realip, and that each IPv6 address is counted on its own.
    • Caddy: the third-party mholt/caddy-ratelimit rate_limit directive. It covers building with xcaddy or the download page, the 429 with Retry-After, the default ordering before basic_auth, and {client_ip} behind a CDN.
    • CDN examples: set_real_ip_from/real_ip_header (the realip module is not built by default, which nginx -V shows), and Caddy's trusted_proxies with trusted_proxies_strict and {client_ip}. Without strict mode, Caddy reads X-Forwarded-For from 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 (@master or a later release). v0.1.0's parser has no default case for zone subdirectives, so it ignores the option without an error.
    • Syntax was checked against nginx.org, the module source and README, and caddyserver.com.
  • The query rate limit page now links to that section.
  • The sample hyperglass.nginx and Caddyfile include the examples, commented out.

Tests

hyperglass/state/tests/test_recovery.py adds 14 tests:

  • After one check, 50 calls take no thread.
  • 20 concurrent requests share one check.
  • State flushed without being read is rebuilt after the interval, and not before.
  • A missing-state read ends the interval.
  • clear() ends the interval, including when a check arms it during the deletes.
  • Epoch races: a check that started earlier does not re-arm, a request after mark_stale() does not join the earlier check, and a joiner on an older epoch does not re-arm.
  • The cooldown starts no rebuild_state threads.
  • Near clock zero there is no cooldown without a failure, and a failure still cools down.
  • A missing plugin registry raises in the managers and marks state stale.
  • An API-level burst of 20 /api/info requests, with the clock frozen, runs one is_populated.
  • in_cooldown() survives a concurrent reset.

hyperglass/util/tests/test_plugin_registry_lost.py (new) sends POST /api/query through 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 and plugins.input missing, plugins.output missing, or plugins.ready missing, 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 root conftest.py resets 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.

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.
@github-actions github-actions Bot added docs Improve documentation backend Python backend: API, models, state, execution labels Nov 24, 2026
@coveralls

coveralls commented Nov 24, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 89.313% (+0.1%) from 89.198% — fix/532-cheap-state-check into main

@jsenecal
jsenecal marked this pull request as ready for review November 25, 2026 21:48
@jsenecal
jsenecal requested a review from WilhelmZA November 25, 2026 21:48

@WilhelmZA WilhelmZA left a comment

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.

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.

@WilhelmZA WilhelmZA added reviewing Issue is being reviewed by maintainers security Hardening and security-relevant changes labels Nov 25, 2026
@jsenecal
jsenecal merged commit 6840ddb into main Nov 25, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Python backend: API, models, state, execution docs Improve documentation reviewing Issue is being reviewed by maintainers security Hardening and security-relevant changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unauthenticated requests on any route can exhaust the shared thread pool

3 participants