Skip to content

fix: preserve flag stream startup and recovery - #90

Open
zhukaihan wants to merge 3 commits into
mainfrom
fix/stream-startup-recovery
Open

zhukaihan wants to merge 3 commits into
mainfrom
fix/stream-startup-recovery

Conversation

@zhukaihan

@zhukaihan zhukaihan commented Dec 4, 2026 •

Copy link
Copy Markdown
Collaborator

With stream_updates=True, an initial stream failure could return normally and make the updater cancel polling and all recovery. Startup could also reject an already-processed first payload because the connector thread had not exited, and cleanup queued behind a stalled handshake could later close a recovered stream.

The client now starts successfully after the first payload is processed, or after the polling fallback loads flags. Initial stream failures raise into the fallback path. Polling stays active while the stream retries and stops when streaming recovers. If both initial paths fail, start() raises without background retries, matching Node and JVM startup semantics.

Connection lifecycle

  • Decide readiness from the first update/error, independently of connector thread liveness. Initial callback exceptions release the waiting caller and raise FlagConfigStreamError with the original cause; HTTP status/body, connection, and parse errors are preserved and logged.
  • Keep blocking HTTP work outside the connection state lock. Use the configured startup timeout for the handshake and restore the longer read timeout after connection.
  • Close synchronously after detaching attempt-owned resources, interrupting blocked reads with socket shutdown. Generation checks reject old connectors, reader errors, and timers; cancelled startup callbacks cannot affect a later attempt.
  • Report reconnection errors through on_error so polling fallback remains available after an established stream fails.
  • Use the configured polling interval for polling retries after a later flag API failure, replacing the previous zero-delay loop. Retry waits are interruptible by stop().

Python validation

Python 3.13.13:

  • python -m unittest discover -s ./tests -p '*_test.py' -k FlagConfig -k StreamStartup -k EventSource -k StalledHandshake -k LocalEvaluationConfig — 37 passed without a custom PYTHONPATH.
  • Repeated the startup, connection lifecycle, real stalled-handshake, and client regression classes 20 times — 380 passed.
  • Real loopback HTTP/SSE validation also covered a refused stream followed by recovery, both endpoints unavailable, HTTP 503 streaming responses, and delayed initial payloads.
  • New regressions cover accepted data while the connector is still alive, initial update exceptions, processing beyond the receive deadline, stale callbacks/connectors/timers, recovery before a stalled old handshake is released, preserved HTTP error details, reconnection failures, delayed polling retries, and cancellation of a pending retry.
  • Test imports follow repository conventions; tests/flag/__init__.py enables CI discovery. The existing both-updaters-fail test now actually asserts an exception.
  • git diff --check passed. Credential-dependent live-service suites were not run locally.

Node behavior check

Reviewed Node v1.13.6. Initial stream failures reject, polling remains active during stream retries and stops on recovery, and both startup paths failing rejects without scheduling stream retries. Five existing focused streamer tests and one local both-paths-fail parity check passed. Initial payload processing completes before readiness; processing time is separate from the receive deadline.

JVM behavior check

Reviewed JVM v1.8.4. Initial stream failures throw; the wrapper keeps polling and retrying the stream, and propagates an initial fallback failure without background retries. Polling retry delay uses the polling interval. ./gradlew test --tests 'com.amplitude.experiment.flag.FlagConfigStreamApiTest' --tests 'com.amplitude.experiment.flag.FlagConfigFallbackRetryWrapperTest' — 15 passed. Initial payload processing completes before readiness and is separate from the receive deadline.

Node and JVM source is unchanged. This PR preserves the configured stream retry interval and startup deadline; Python now applies that deadline to HTTP connection setup and uses the polling interval for polling retries.

Existing limitation outside this change

Poller.stop() is not synchronized with a timer callback already running, so that callback can re-arm polling after stop. This separate pre-existing polling timer race remains unchanged.


Note

High Risk
Substantial rewrite of stream connection lifecycle, threading, and startup/fallback logic in the flag config path, where races and stuck or missing updates would affect all local evaluation clients. The threading changes are subtle and mitigated by new concurrency tests.

Overview
Fixes flag stream startup and recovery when stream_updates=True. Previously an initial stream failure could return normally and cancel polling and all recovery; now initial failures raise into the polling fallback, and polling stays active while the stream retries and stops once streaming recovers.

The stream API now decides readiness from the first update or error rather than connector thread liveness, so an already-processed first payload is no longer rejected. Initial callback exceptions and HTTP/connection/parse errors surface as FlagConfigStreamError. If both startup paths fail, start() raises with no background retries.

The EventSource connection lifecycle gains generation tracking: blocking HTTP work happens outside the state lock, stale connectors, reader errors, and keep-alive timers from old attempts are ignored, and stop() interrupts blocked reads via socket shutdown. Reconnection failures are now reported through on_error. Polling retries after a later failure use the configured polling interval (previously zero delay), and retry waits are interruptible by stop().

The diff also adds new tests for startup, stalled handshakes, and retry behavior, and fixes the existing both-fail test so it actually asserts an exception.

Reviewed by Cursor Bugbot for commit a09f8dc. Bugbot is set up for automated code reviews on this repo. Configure here.

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

The initial error callback and fallback handoff work for the tested failure paths, and the latest commit fixes CI discovery. Two timing cases still need coverage:

  1. FlagConfigStreamApi.start() raises whenever the connector thread is alive, even after a valid first update has completed (flag_config_api.py:219-223). The SSE reader starts before that connector thread finishes, so a fast first payload can be accepted and then reported as a startup timeout. I reproduced one accepted update followed by the exception. Please use the first update/error state to decide success and add a concurrent regression.
  2. When the initial HTTP request itself remains blocked past the startup deadline, stop() and stream retries wait behind that request's EventSource lock (flag_config_api.py:83-90, 153-165, 218-230). Polling starts, but streaming cannot recover until the old request releases; the socket can wait far longer than the configured startup deadline. I reproduced retries making no second connection attempt until the first request was released. Please bound or cancel that request at the startup deadline and test the stalled-handshake path.

@zhukaihan zhukaihan left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The startup fix looks right to me: raising sends initial stream failures to the wrapper's fallback/retry path, which matches Node and JVM. Inline comments cover one race I'd want fixed before merging, plus two nits.

Two problems outside this diff that already existed (not caused by this PR, noting them for context):

  • flag_config_api.py _run, TimeoutError branch: the reconnect calls self.stop() and then self.start(...). If _get_conn raises there (connection refused, DNS, TLS), the exception kills the _run thread without calling on_error. The keep-alive timer is already cancelled, so the stream dies silently and the wrapper never falls back to polling. At startup, the same gap makes FlagConfigStreamApi.start wait out the full conn timeout after the thread has already died. Suggest catching exceptions from _get_conn in EventSource.start and passing them to on_error.
  • deployment_runner.py:38: the inner poller wrapper uses retry_delay_millis=0 and max_jitter_millis=0 (your PR description mentions this). With this PR, polling stays on whenever the stream can't start, for example when a proxy blocks SSE. A flag API outage in that state makes retry_main call the flag API back to back with no delay. It may be worth giving it a real delay, such as the polling interval, either in this PR or right after.

Comment thread tests/flag/flag_config_api_test.py Resolved
@zhukaihan zhukaihan changed the title fix: recover from initial flag stream failures fix: preserve flag stream startup and recovery Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed the requested startup/concurrency changes in a09f8dc:

  • Readiness uses first-update/error completion, not connector-thread liveness. A regression holds the connector open after delivering valid data and verifies start() succeeds.
  • HTTP handshakes use the configured startup timeout, perform I/O outside the state lock, and can be interrupted by socket shutdown. Attempt generation checks prevent delayed connectors, cleanup, and timers from affecting a recovered stream. A real HTTP/SSE regression recovers before the old stalled handshake is released and verifies subsequent updates still arrive.
  • Initial processing exceptions and original connection/HTTP/parse errors propagate as FlagConfigStreamError and are logged before fallback.
  • Connection failures during stream renewal now reach on_error. Polling retries after a later flag API failure use the polling interval; retry waits can be interrupted by stop().

Local validation: 37 tests passed under CI-style discovery, 380 repeated startup/lifecycle cases passed, and the four original real HTTP/SSE scenarios passed. The PR description has the updated scope and the remaining pre-existing Poller timer race.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit a09f8dc. Configure here.

init_received_event.set()
init_updated_event.set()
return
on_error(data)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keep-alive aborts initial flag apply

High Severity

The keep-alive timer is reset immediately before the initial on_update callback and is not paused while that callback runs. If applying the first payload takes longer than the keep-alive interval, such as a cohort download, the timer closes the socket and _on_error records a startup failure because init_updated_event is still unset. start() then raises and the polling fallback updates flag storage while the original update is still running, so flag configs can be dropped.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit a09f8dc. Configure here.

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

The two earlier startup races are fixed: a valid first update succeeds even while the connector is alive, and a stalled handshake no longer blocks polling or later stream attempts. I reproduced both improvements. Two follow-ups remain:

  1. Each timed-out start leaves its connector thread running, and retry starts another default non-daemon thread (flag_config_api.py:302-313, flag_config_updater.py:216-233). A stalled DNS lookup is outside the socket timeout and cannot be closed before a socket exists. With a blocked getaddrinfo, a 30 ms startup deadline, and 50 ms retries, I observed three non-daemon connectors still alive after 180 ms. Please bound outstanding attempts and make abandoned connectors unable to hold process exit.
  2. The new startup warning logs the full FlagConfigStreamError, including an HTTP error body (flag_config_api.py:105-108, 290-318, flag_config_updater.py:192-196). An HTTP 401 body echoing the Authorization header put the deployment key into the warning in my repro. Please keep the useful status/error context while ensuring credentials and other sensitive body content are not logged.

This branch was successfully deployed

1 active deployment
Unit Test — a09f8dc3 Deployed Dec 4, 2026 by zhukaihan via test (3.12) #246
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.

2 participants