Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/amplitude_experiment/deployment/deployment_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __init__(
self.flag_updater = FlagConfigUpdaterFallbackRetryWrapper(
FlagConfigPoller(flag_config_api, flag_config_storage, cohort_loader, cohort_storage, config, logger),
None,
0, 0, config.flag_config_polling_interval_millis, 0,
config.flag_config_polling_interval_millis, 0, config.flag_config_polling_interval_millis, 0,
logger
)
if flag_config_stream_api:
Expand Down
252 changes: 173 additions & 79 deletions src/amplitude_experiment/flag/flag_config_api.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import json
import socket
import threading
import time
from http.client import HTTPResponse, HTTPConnection, HTTPSConnection
from typing import List, Optional, Callable, Mapping, Union, Tuple

Expand Down Expand Up @@ -78,95 +80,157 @@ def __init__(self, server_url: str, path: str, headers: Mapping[str, str], conn_
self.conn: Optional[HTTPConnection | HTTPSConnection] = None
self.thread: Optional[threading.Thread] = None
self._stopped = False
self._generation = 0
self._socket: Optional[socket.socket] = None
self.lock = threading.RLock()

def start(self, on_update: Callable[[str], None], on_error: Callable[[str], None]):
@property
def generation(self):
with self.lock:
if self.sse is not None:
self.sse.close()
if self.conn is not None:
self.conn.close()
return self._generation

self.conn, response = self._get_conn()
def start(self, on_update: Callable[[str], None], on_error: Callable[[str], None],
generation: Optional[int] = None):
with self.lock:
if generation is not None and generation != self._generation:
return
previous = self._stop_locked()
self._stopped = False
generation = self._generation
self._close(previous)

try:
# Never hold the state lock while connecting or waiting for HTTP headers.
conn, response = self._get_conn(generation)
if response.status != 200:
on_error(f"[Experiment] Stream flagConfigs - received error response: ${response.status}: ${response.read().decode('utf-8')}")
self._fail(generation, on_error,
f"[Experiment] Stream flagConfigs - received error response: {response.status}: {response.read().decode('utf-8')}")
return

self.sse = sseclient.SSEClient(response, char_enc='utf-8')
self._stopped = False
self.thread = threading.Thread(target=self._run, args=[on_update, on_error])
self.thread.start()
self.reset_keep_alive_timer(on_error)
with self.lock:
current = self._is_current(generation)
if current:
self.conn = conn
self._socket = self._socket or conn.sock
if self._socket:
self._socket.settimeout(get_duration_with_jitter(
self.max_conn_duration_millis, self.max_jitter_millis) / 1000)
self.sse = sseclient.SSEClient(response, char_enc='utf-8')
self.thread = threading.Thread(target=self._run,
args=[self.sse, generation, on_update, on_error])
self.reset_keep_alive_timer(on_error, generation)
self.thread.start()
if not current:
# This handshake completed after its startup attempt was cancelled.
self._close((None, conn, conn.sock))
response.close()
except Exception as error:
self._fail(generation, on_error, f"[Experiment] Stream flagConfigs - connection failed: {error}")

def stop(self):
with self.lock:
self._stopped = True
if self.sse:
self.sse.close()
if self.conn:
self.conn.close()
if self.keep_alive_timer:
self.keep_alive_timer.cancel()
self.sse = None
self.conn = None
# No way to stop self.thread, on self.conn.close(),
# the loop in thread will raise exception, which will terminate the thread.

def reset_keep_alive_timer(self, on_error: Callable[[str], None]):
previous = self._stop_locked()
self._close(previous)

def _is_current(self, generation):
return generation == self._generation and not self._stopped

def _stop_locked(self):
self._stopped = True
self._generation += 1
previous = self.sse, self.conn, self._socket
self.sse = self.conn = self._socket = None
if self.keep_alive_timer:
self.keep_alive_timer.cancel()
self.keep_alive_timer = None
return previous

@staticmethod
def _close(previous):
sse, conn, sock = previous
# Interrupt an in-flight read before closing its HTTPResponse (which can
# otherwise wait for the reader's buffered-I/O lock).
if sock:
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
for resource in (conn, sse):
if resource:
try:
resource.close()
except OSError:
pass

def reset_keep_alive_timer(self, on_error: Callable[[str], None], generation: int):
with self.lock:
if not self._is_current(generation):
return
if self.keep_alive_timer:
self.keep_alive_timer.cancel()
self.keep_alive_timer = threading.Timer(self.keep_alive_timeout_millis / 1000, self.keep_alive_timed_out,
args=[on_error])
args=[on_error, generation])
self.keep_alive_timer.start()

def keep_alive_timed_out(self, on_error: Callable[[str], None]):
def keep_alive_timed_out(self, on_error: Callable[[str], None], generation: int):
self._fail(generation, on_error, "[Experiment] Stream flagConfigs - Keep alive timed out")

def _fail(self, generation: int, on_error: Callable[[str], None], message: str):
with self.lock:
if not self._stopped:
self.stop()
on_error("[Experiment] Stream flagConfigs - Keep alive timed out")
if not self._is_current(generation):
return
previous = self._stop_locked()
self._close(previous)
on_error(message)

def _run(self, on_update: Callable[[str], None], on_error: Callable[[str], None]):
def _run(self, sse, generation: int, on_update: Callable[[str], None], on_error: Callable[[str], None]):
try:
for event in self.sse.events():
for event in sse.events():
with self.lock:
if self._stopped:
if not self._is_current(generation):
return
self.reset_keep_alive_timer(on_error)
self.reset_keep_alive_timer(on_error, generation)
if event.data == ' ':
continue
on_update(event.data)
except TimeoutError:
# Due to connection max time reached, open another one.
with self.lock:
if self._stopped:
return
self.stop()
self.start(on_update, on_error)
self.start(on_update, on_error, generation)
except Exception as e:
# Closing connection can result in exception here as a way to stop generator.
with self.lock:
if self._stopped:
return
on_error("[Experiment] Stream flagConfigs - Unexpected exception" + str(e))
self._fail(generation, on_error, "[Experiment] Stream flagConfigs - Unexpected exception: " + str(e))

def _get_conn(self) -> Tuple[Union[HTTPConnection, HTTPSConnection], HTTPResponse]:
def _get_conn(self, generation: int) -> Tuple[Union[HTTPConnection, HTTPSConnection], HTTPResponse]:
scheme, _, host = self.server_url.split('/', 3)
connection = HTTPConnection if scheme == 'http:' else HTTPSConnection

body = None

conn = connection(host, timeout=get_duration_with_jitter(self.max_conn_duration_millis, self.max_jitter_millis) / 1000)
timeout = self.conn_timeout_millis / 1000
deadline = time.monotonic() + timeout
conn = connection(host, timeout=timeout)
try:
conn.request('GET', self.path, body, self.headers)
with self.lock:
if not self._is_current(generation):
raise RuntimeError("Stream connection stopped")
self.conn = conn
conn.request('GET', self.path, None, self.headers)
with self.lock:
if not self._is_current(generation):
raise RuntimeError("Stream connection stopped")
self._socket = conn.sock
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("stream connection timeout error")
if conn.sock:
conn.sock.settimeout(remaining)
response = conn.getresponse()
except Exception as e:
conn.close()
raise e

except Exception:
self._close((None, conn, conn.sock))
raise
return conn, response


class FlagConfigStreamError(Exception):
"""The initial stream connection or flag update failed."""


class FlagConfigStreamApi:
def __init__(self,
deployment_key: str,
Expand All @@ -181,50 +245,80 @@ def __init__(self,
self.max_jitter_millis = max_jitter_millis

self.lock = threading.RLock()
self._cancelled: Optional[threading.Event] = None

headers = {
'Authorization': f"Api-Key {self.deployment_key}",
'Content-Type': 'application/json;charset=utf-8',
'X-Amp-Exp-Library': f"experiment-python-server/{__version__}"
}

self.eventsource = EventSource(self.server_url, "/sdk/stream/v1/flags", headers, conn_timeout_millis)
self.eventsource = EventSource(self.server_url, "/sdk/stream/v1/flags", headers, conn_timeout_millis,
max_conn_duration_millis, max_jitter_millis)

def start(self, on_update: Callable[[List[EvaluationFlag]], None], on_error: Callable[[str], None]):
with self.lock:
init_finished_event = threading.Event()
init_error_event = threading.Event()
self.stop()
cancelled = threading.Event()
self._cancelled = cancelled
init_received_event = threading.Event()
init_updated_event = threading.Event()
init_lock = threading.Lock()
init_error: Optional[Exception] = None

def _on_update(data):
response_json = json.loads(data)
flags = EvaluationFlag.schema().load(response_json, many=True)
if init_finished_event.is_set():
on_update(flags)
else:
init_finished_event.set()
nonlocal init_error
with init_lock:
if cancelled.is_set() or init_error is not None:
return
initial = not init_received_event.is_set()
if initial:
init_received_event.set()
try:
response_json = json.loads(data)
flags = EvaluationFlag.schema().load(response_json, many=True)
on_update(flags)
init_updated_event.set()
except Exception as error:
if not initial:
raise
with init_lock:
init_error = error
finally:
if initial:
init_updated_event.set()

def _on_error(data):
if init_finished_event.is_set():
on_error(data)
else:
init_error_event.set()
init_finished_event.set()
on_error(data)

t = threading.Thread(target=self.eventsource.start, args=[_on_update, _on_error])
t.start()
init_finished_event.wait(self.conn_timeout_millis / 1000)
if t.is_alive() or not init_finished_event.is_set() or init_error_event.is_set():
self.stop()
on_error("stream connection timeout error")
return
nonlocal init_error
with init_lock:
if cancelled.is_set() or init_error is not None:
return
if not init_updated_event.is_set():
init_error = FlagConfigStreamError(str(data))
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.


generation = self.eventsource.generation

def connect():
try:
self.eventsource.start(_on_update, _on_error, generation)
except Exception as error:
_on_error(error)

threading.Thread(target=connect).start()
if not init_received_event.wait(self.conn_timeout_millis / 1000):
self.stop()
raise FlagConfigStreamError("stream connection timeout error")
# Wait for first update callback to finish before returning.
init_updated_event.wait()
Comment thread
zhukaihan marked this conversation as resolved.
Resolved
if init_error is not None:
self.stop()
raise FlagConfigStreamError(f"Initial flag stream failed: {init_error}") from init_error

def stop(self):
with self.lock:
threading.Thread(target=lambda: self.eventsource.stop()).start()
if self._cancelled:
self._cancelled.set()
self.eventsource.stop()
10 changes: 6 additions & 4 deletions src/amplitude_experiment/flag/flag_config_updater.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging
import threading
import time
from typing import List, Callable, Optional

from ..evaluation.types import EvaluationFlag
Expand Down Expand Up @@ -191,6 +190,7 @@ def _main_on_error(err: str):
self.stop_main_retry()
self.stop_fallback_retry()
except Exception as e:
self.logger.warning(f"Failed to start flag config updater: {e}")
if self.fallback_updater is not None:
self.fallback_updater.start(_fallback_on_error)
self.start_main_retry(_main_on_error)
Expand All @@ -215,7 +215,8 @@ def start_main_retry(self, main_on_error: Callable[[str], None]):

def retry_main():
while True:
time.sleep(get_duration_with_jitter(self.retry_delay_millis, self.max_jitter_millis) / 1000)
if stopper.wait(get_duration_with_jitter(self.retry_delay_millis, self.max_jitter_millis) / 1000):
break
with self.lock:
if stopper.is_set():
break
Expand Down Expand Up @@ -245,8 +246,9 @@ def start_fallback_retry(self, fallback_on_error: Callable[[str], None]):

def retry_fallback():
while True:
time.sleep(get_duration_with_jitter(self.fallback_start_retry_delay_millis,
self.fallback_start_retry_max_jitter_millis) / 1000)
if stopper.wait(get_duration_with_jitter(self.fallback_start_retry_delay_millis,
self.fallback_start_retry_max_jitter_millis) / 1000):
break
with self.lock:
if stopper.is_set():
break
Expand Down
1 change: 1 addition & 0 deletions tests/flag/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Loading
Loading