Skip to content

Commit 6e05c04

Browse files
authored
feat: Add experimental support for flag overrides (#580)
<!-- TERMAG_PR_BODY_BEGIN --> BEGIN_COMMIT_OVERRIDE feat: Add experimental support for flag overrides, read from local JSON or YAML files or supplied by a custom override source feat: Mark evaluations that a flag override affected with `overrideAffected` in the evaluation reason, and count them under separate summary counters fix: Stop the components that already started when the client fails to start END_COMMIT_OVERRIDE Every change in this PR was already reviewed and merged through its own PR against `feat/overrides`: #525, #526, #527, #528, #529, #530, #572, #574, #576, #577. This PR merges the branch into `main`. Flag overrides let an operator force flags and segments to known definitions on a running client, whether or not the client can reach LaunchDarkly, and remove the override when the incident is over. They are an option of the FDv2 data system, on both `LDClient` and `AsyncLDClient`, with a file-based source in `ldclient.integrations.overrides.FileOverrideSourceBuilder`, and are experimental. The one change outside the feature: #527 stops the components that had already started when the data system fails to start, so a failed client construction no longer leaves threads behind. `main` was merged into `feat/overrides` in 46e5f0e, so the branch has every `main` commit. That merge resolved two conflicts and made one follow-up change: - The capability lists of both contract test services keep both sides: `flag-overrides` from this branch, and the retry conformance, service endpoints, wrapper, proxy and TLS capabilities from `main`. - One async override test used `AsyncHook`, which #548 removed from `main`. It now uses `Hook`, which the async client accepts. Before the push: - the unit test suite passed (2,357 tests, without the Redis, DynamoDB and Consul store tests, which need servers); - `mypy`, `isort` and `pycodestyle` were clean; - the contract test harness's `flag overrides` suite passed against both the sync and the async test service (88 tests each). <!-- TERMAG_PR_BODY_END --> <!-- termag: box=i-0575d1c54853058d7 project=python-server-sdk --> <sub>Opened from termag</sub> <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Overview** > Adds **experimental flag overrides** so operators can force known flag/segment definitions at runtime (via local JSON/YAML files through `FileOverrideSourceBuilder`, or a custom `OverrideSource`), integrated into the FDv2 data system for sync and async clients through `datasystem_config.override_source` / `ConfigBuilder.overrides()`. > > The data system now maintains an **override layer** merged over the normal store, serves override-only flags when LaunchDarkly data is not ready, and fans out **dependency-aware flag-change notifications** when LD data affects overridden prerequisites/segments. Evaluations propagate an **`overrideAffected`** reason marker; analytics treat those evaluations differently (summary counters only, `all_flags_state` disables per-flag tracking for them). > > Contract test services advertise **`flag-overrides`** and build override sources from harness config; docs add `ldclient.integrations.overrides`. > > Also **fixes client startup**: if the data system fails to start, already-started components are stopped so failed construction does not leak threads. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 46e5f0e. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent ad37b18 commit 6e05c04

52 files changed

Lines changed: 10768 additions & 102 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎contract-tests/async_client_entity.py‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
)
2828
from ldclient.impl.util import Result
2929
from ldclient.integrations import Redis
30+
from ldclient.integrations.overrides import FileOverrideSourceBuilder
3031
from ldclient.interfaces import DataStoreMode
3132
from ldclient.migrations import (
3233
AsyncMigratorBuilder,
@@ -82,8 +83,10 @@ async def start(self):
8283
opts['events_uri'] = endpoints['events']
8384

8485
datasystem_config = config_params.get('dataSystem')
86+
if config_params.get('overrides') is not None and datasystem_config is None:
87+
raise ValueError("flag overrides require the data system to be configured")
8588
if datasystem_config is not None:
86-
opts["datasystem_config"] = _build_async_data_system(datasystem_config, opts)
89+
opts["datasystem_config"] = _build_async_data_system(datasystem_config, opts, config_params.get('overrides'))
8790
elif config_params.get("streaming") is not None:
8891
streaming = config_params["streaming"]
8992
if streaming.get("baseUri") is not None:
@@ -320,13 +323,13 @@ def _set_optional_value(params_in: dict, name_in: str, func: Callable[[Any], Any
320323
func(params_in[name_in])
321324

322325

323-
def _build_async_data_system(datasystem_config: dict, opts: dict) -> AsyncDataSystemConfig:
326+
def _build_async_data_system(datasystem_config: dict, opts: dict, overrides_config: Optional[dict] = None) -> AsyncDataSystemConfig:
324327
"""Build an AsyncDataSystemConfig from the harness's dataSystem config.
325328
326329
Wires the FDv2 initializers, the ordered synchronizer chain, the FDv1
327-
fallback synchronizer, the payload filter, and an optional async
328-
persistent store. The async client injects its shared aiohttp session
329-
into these builders when it starts.
330+
fallback synchronizer, the payload filter, an optional async persistent
331+
store, and the optional file-based override source. The async client
332+
injects its shared aiohttp session into these builders when it starts.
330333
"""
331334
initializers: Optional[list] = None
332335
init_configs = datasystem_config.get('initializers')
@@ -379,6 +382,9 @@ def _build_async_data_system(datasystem_config: dict, opts: dict) -> AsyncDataSy
379382
"fdv1_fallback_synchronizer": fdv1_fallback_synchronizer,
380383
}
381384

385+
if overrides_config is not None:
386+
ds_kwargs["override_source"] = _make_override_source(overrides_config)
387+
382388
store_config = datasystem_config.get("store")
383389
if store_config is not None:
384390
persistent_store_config = store_config.get("persistentDataStore")
@@ -393,6 +399,18 @@ def _build_async_data_system(datasystem_config: dict, opts: dict) -> AsyncDataSy
393399
return AsyncDataSystemConfig(**ds_kwargs)
394400

395401

402+
def _make_override_source(params: dict) -> FileOverrideSourceBuilder:
403+
"""
404+
Builds the file-based override source from the harness's overrides configuration. The
405+
files are written by the harness on a file system shared with this service.
406+
"""
407+
builder = FileOverrideSourceBuilder(params["filePaths"])
408+
_set_optional_value(params, "duplicateKeysHandling", builder.duplicate_keys_handling)
409+
_set_optional_value(params, "changeDetection", builder.change_detection)
410+
_set_optional_time(params, "pollIntervalMs", builder.poll_interval)
411+
return builder
412+
413+
396414
def _create_async_persistent_store(persistent_store_config: dict):
397415
"""Create an async persistent feature store from the harness config.
398416

‎contract-tests/async_service.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ async def handle_status(request: aiohttp.web.Request) -> aiohttp.web.Response:
6969
'migrations',
7070
'persistent-data-store-redis',
7171
'fdv1-fallback',
72+
'flag-overrides',
7273
'retry-conformance-fdv1-streaming',
7374
'retry-conformance-fdv1-polling',
7475
'service-endpoints',

‎contract-tests/client_entity.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from ldclient.feature_store import CacheConfig
2929
from ldclient.impl.datasourcev2.polling import PollingDataSourceBuilder
3030
from ldclient.integrations import Consul, DynamoDB, Redis
31+
from ldclient.integrations.overrides import FileOverrideSourceBuilder
3132
from ldclient.interfaces import DataStoreMode
3233

3334

@@ -69,6 +70,8 @@ def __init__(self, tag, config):
6970
opts['events_uri'] = endpoints['events']
7071

7172
datasystem_config = config.get('dataSystem')
73+
if config.get('overrides') is not None and datasystem_config is None:
74+
raise ValueError("flag overrides require the data system to be configured")
7275
if datasystem_config is not None:
7376
datasystem = custom()
7477

@@ -132,6 +135,10 @@ def __init__(self, tag, config):
132135

133136
datasystem.data_store(store, store_mode)
134137

138+
overrides_config = config.get('overrides')
139+
if overrides_config is not None:
140+
datasystem.overrides(_make_override_source(overrides_config))
141+
135142
opts["datasystem_config"] = datasystem.build()
136143

137144
elif config.get("streaming") is not None:
@@ -352,6 +359,18 @@ def _set_optional_value(params_in: dict, name_in: str, func: Callable[[Any], Any
352359
func(params_in[name_in])
353360

354361

362+
def _make_override_source(params: dict) -> FileOverrideSourceBuilder:
363+
"""
364+
Builds the file-based override source from the harness's overrides configuration. The
365+
files are written by the harness on a file system shared with this service.
366+
"""
367+
builder = FileOverrideSourceBuilder(params["filePaths"])
368+
_set_optional_value(params, "duplicateKeysHandling", builder.duplicate_keys_handling)
369+
_set_optional_value(params, "changeDetection", builder.change_detection)
370+
_set_optional_time(params, "pollIntervalMs", builder.poll_interval)
371+
return builder
372+
373+
355374
def _create_persistent_store(persistent_store_config: dict):
356375
"""
357376
Creates a persistent store instance based on the configuration.

‎contract-tests/service.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ def status():
8686
'flag-change-listeners',
8787
'flag-value-change-listeners',
8888
'fdv1-fallback',
89+
'flag-overrides',
8990
'retry-conformance-fdv1-streaming',
9091
'retry-conformance-fdv1-polling',
9192
'service-endpoints',

‎docs/api-integrations.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,13 @@ ldclient.integrations module
88
:members:
99
:special-members: __init__
1010
:show-inheritance:
11+
12+
ldclient.integrations.overrides module
13+
--------------------------------------
14+
15+
The entry point for this feature is :class:`ldclient.integrations.overrides.FileOverrideSourceBuilder`.
16+
17+
.. automodule:: ldclient.integrations.overrides
18+
:members:
19+
:special-members: __init__
20+
:show-inheritance:

‎ldclient/async_client.py‎

Lines changed: 97 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import asyncio
66
import traceback
7-
from typing import Any, Callable, List, Optional, Tuple
7+
from typing import Any, Callable, Dict, List, Optional, Tuple
88
from uuid import uuid4
99

1010
from ldclient.async_config import AsyncConfig
@@ -28,7 +28,7 @@
2828
)
2929
from ldclient.impl.client_common import secure_mode_hash as _secure_mode_hash
3030
from ldclient.impl.datasystem import AsyncDataSystem, DataAvailability
31-
from ldclient.impl.evaluator_common import error_reason
31+
from ldclient.impl.evaluator_common import error_reason, is_override_definition
3232
from ldclient.impl.events.async_event_processor import (
3333
DefaultAsyncEventProcessor
3434
)
@@ -95,6 +95,7 @@ def __init__(self, config: AsyncConfig):
9595
# these flags, so plain booleans are safe.
9696
self._eval_cached_data_warned = False
9797
self._all_flags_cached_data_warned = False
98+
self._all_flags_overrides_only_warned = False
9899

99100
# Build the object graph here (loop-free). start() supplies the loop-bound
100101
# resources: the HTTP session (created lazily), the data source, the
@@ -485,7 +486,12 @@ async def evaluate():
485486
tracker = OpTracker(key, flag, context, detail, default_stage)
486487
return _EvaluationWithHookResult(evaluation_detail=detail, results={'default_stage': stage, 'tracker': tracker})
487488

488-
detail = EvaluationDetail(default_stage.value, None, error_reason('WRONG_TYPE'))
489+
# The type mismatch replaces the reason. The evaluation read the same definitions,
490+
# so the new reason keeps the override-affected marking.
491+
reason = error_reason('WRONG_TYPE')
492+
if detail.reason.get('overrideAffected') is True:
493+
reason['overrideAffected'] = True
494+
detail = EvaluationDetail(default_stage.value, None, reason)
489495
tracker = OpTracker(key, flag, context, detail, default_stage)
490496
return _EvaluationWithHookResult(evaluation_detail=detail, results={'default_stage': default_stage, 'tracker': tracker})
491497

@@ -498,30 +504,42 @@ async def _evaluate_internal(self, key: str, context: Context, default: Any, eve
498504
if self._config.offline:
499505
return EvaluationDetail(default, None, error_reason('CLIENT_NOT_READY')), None
500506

507+
def not_ready() -> Tuple[EvaluationDetail, Optional[FeatureFlag]]:
508+
log.warning("Feature Flag evaluation attempted before client has initialized! Feature store unavailable - returning default: " + str(default) + " for feature key: " + key)
509+
reason = error_reason('CLIENT_NOT_READY')
510+
self._send_event(event_factory.new_unknown_flag_event(key, context, default, reason))
511+
return EvaluationDetail(default, None, reason), None
512+
513+
flag: Any = None
501514
availability = await self._data_system.data_availability()
502515
if availability != DataAvailability.REFRESHED:
503516
if availability == DataAvailability.CACHED:
504517
if not self._eval_cached_data_warned:
505518
self._eval_cached_data_warned = True
506519
log.warning("Feature Flag evaluation attempted before client has initialized - using last known values from feature store for feature key: " + key + ". This message is logged once.")
507520
else:
508-
log.warning("Feature Flag evaluation attempted before client has initialized! Feature store unavailable - returning default: " + str(default) + " for feature key: " + key)
509-
reason = error_reason('CLIENT_NOT_READY')
510-
self._send_event(event_factory.new_unknown_flag_event(key, context, default, reason))
511-
return EvaluationDetail(default, None, reason), None
521+
# No data from LaunchDarkly is available. A flag that the override layer holds
522+
# is served anyway. A flag the layer does not hold gets the not-ready default,
523+
# as it does without an override source.
524+
layer = self._data_system.override_layer
525+
if layer is not None:
526+
flag = layer.get(FEATURES, key)
527+
if flag is None:
528+
return not_ready()
512529

513530
if not context.valid:
514531
log.warning("Context was invalid for flag evaluation (%s); returning default value" % context.error)
515532
return EvaluationDetail(default, None, error_reason('USER_NOT_SPECIFIED')), None
516533

517-
try:
518-
flag = await self._data_system.store.get(FEATURES, key)
519-
except Exception as e:
520-
log.error("Unexpected error while retrieving feature flag \"%s\": %s" % (key, repr(e)))
521-
log.debug(traceback.format_exc())
522-
reason = error_reason('EXCEPTION')
523-
self._send_event(event_factory.new_unknown_flag_event(key, context, default, reason))
524-
return EvaluationDetail(default, None, reason), None
534+
if flag is None:
535+
try:
536+
flag = await self._data_system.store.get(FEATURES, key)
537+
except Exception as e:
538+
log.error("Unexpected error while retrieving feature flag \"%s\": %s" % (key, repr(e)))
539+
log.debug(traceback.format_exc())
540+
reason = error_reason('EXCEPTION')
541+
self._send_event(event_factory.new_unknown_flag_event(key, context, default, reason))
542+
return EvaluationDetail(default, None, reason), None
525543
if not flag:
526544
reason = error_reason('FLAG_NOT_FOUND')
527545
self._send_event(event_factory.new_unknown_flag_event(key, context, default, reason))
@@ -534,13 +552,19 @@ async def _evaluate_internal(self, key: str, context: Context, default: Any, eve
534552
detail = result.detail
535553
if detail.is_default_value():
536554
detail = EvaluationDetail(default, None, detail.reason)
537-
self._send_event(event_factory.new_eval_event(flag, context, detail, default))
555+
self._send_event(event_factory.new_eval_event(flag, context, detail, default, None, result.override_affected))
538556
return detail, flag
539557
except Exception as e:
540558
log.error("Unexpected error while evaluating feature flag \"%s\": %s" % (key, repr(e)))
541559
log.debug(traceback.format_exc())
542560
reason = error_reason('EXCEPTION')
543-
self._send_event(event_factory.new_default_event(flag, context, default, reason))
561+
# The evaluation read the flag definition before it failed. A definition from
562+
# the override layer marks the result, so the failure is reported in the
563+
# summary counters only, like any other override-affected evaluation.
564+
override_affected = is_override_definition(flag)
565+
if override_affected:
566+
reason['overrideAffected'] = True
567+
self._send_event(event_factory.new_default_event(flag, context, default, reason, override_affected))
544568
return EvaluationDetail(default, None, reason), flag
545569

546570
async def all_flags_state(self, context: Context, **kwargs) -> FeatureFlagsState:
@@ -572,56 +596,97 @@ async def all_flags_state(self, context: Context, **kwargs) -> FeatureFlagsState
572596
log.warning("all_flags_state() called, but client is in offline mode. Returning empty state")
573597
return FeatureFlagsState(False)
574598

599+
override_flags: Optional[Dict[str, Any]] = None
575600
availability = await self._data_system.data_availability()
576601
if availability != DataAvailability.REFRESHED:
577602
if availability == DataAvailability.CACHED:
578603
if not self._all_flags_cached_data_warned:
579604
self._all_flags_cached_data_warned = True
580605
log.warning("all_flags_state() called before client has finished initializing! Using last known values from feature store. This message is logged once.")
581606
else:
582-
log.warning("all_flags_state() called before client has finished initializing! Feature store unavailable - returning empty state")
583-
return FeatureFlagsState(False)
607+
# No data from LaunchDarkly is available. When the override layer holds flags,
608+
# the state contains only those, read from the layer itself: a store that is not
609+
# initialized can still hold LaunchDarkly data, which the state must not include.
610+
# Without override flags the state is unavailable, as it is without an override
611+
# source.
612+
layer = self._data_system.override_layer
613+
override_flags = layer.all(FEATURES) if layer is not None else {}
614+
if len(override_flags) == 0:
615+
log.warning("all_flags_state() called before client has finished initializing! Feature store unavailable - returning empty state")
616+
return FeatureFlagsState(False)
584617

585618
if not context.valid:
586619
log.warning("Context was invalid for all_flags_state (%s); returning default value" % context.error)
587620
return FeatureFlagsState(False)
588621

589-
state = FeatureFlagsState(True)
622+
valid = True
590623
client_only = kwargs.get('client_side_only', False)
591624
with_reasons = kwargs.get('with_reasons', False)
592625
details_only_if_tracked = kwargs.get('details_only_for_tracked_flags', False)
593-
try:
594-
flags_map = await self._data_system.store.all(FEATURES)
595-
if flags_map is None:
596-
raise ValueError("feature store error")
597-
except Exception as e:
598-
log.error("Unable to read flags for all_flag_state: %s" % repr(e))
599-
return FeatureFlagsState(False)
600-
626+
if override_flags is not None:
627+
if not self._all_flags_overrides_only_warned:
628+
self._all_flags_overrides_only_warned = True
629+
log.warning("all_flags_state() called before client has finished initializing! Returning only flags from the override layer. This message is logged once.")
630+
flags_map = override_flags
631+
else:
632+
try:
633+
flags_map = await self._data_system.store.all(FEATURES)
634+
if flags_map is None:
635+
raise ValueError("feature store error")
636+
except Exception as e:
637+
log.error("Unable to read flags for all_flag_state: %s" % repr(e))
638+
# Overrides only add to the state. Without them the state is invalid and empty
639+
# here, so it holds the override layer's flags and stays invalid. A client-side
640+
# SDK bootstrapped from the state uses its flags whatever $valid says (the
641+
# JavaScript client SDKs 3.x and 4.x only warn), so the overridden values still
642+
# reach it.
643+
layer = self._data_system.override_layer
644+
flags_map = layer.all(FEATURES) if layer is not None else {}
645+
if len(flags_map) == 0:
646+
return FeatureFlagsState(False)
647+
valid = False
648+
649+
state = FeatureFlagsState(valid)
601650
for key, flag in flags_map.items():
602651
if client_only and not flag.get('clientSide', False):
603652
continue
604653
try:
605654
result = await self._evaluator.evaluate(flag, context, self._event_factory_default)
606655
detail = result.detail
607656
prerequisites = result.prerequisites
657+
override_affected = result.override_affected
608658
except Exception as e:
609659
log.error("Error evaluating flag \"%s\" in all_flags_state: %s" % (key, repr(e)))
610660
log.debug(traceback.format_exc())
611-
reason = {'kind': 'ERROR', 'errorKind': 'EXCEPTION'}
661+
reason = error_reason('EXCEPTION')
662+
# The evaluation read the flag definition before it failed, so a definition from
663+
# the override layer marks the result.
664+
override_affected = is_override_definition(flag)
665+
if override_affected:
666+
reason['overrideAffected'] = True
612667
detail = EvaluationDetail(None, None, reason)
613668
prerequisites = []
614669
requires_experiment_data = EventFactory.is_experiment(flag, detail.reason)
670+
track_events = flag.get('trackEvents', False) or requires_experiment_data
671+
track_reason = requires_experiment_data
672+
debug_events_until_date = flag.get('debugEventsUntilDate', None)
673+
if override_affected:
674+
# A consumer of this state sends individual events according to these fields.
675+
# An override-affected evaluation produces no individual events, so the state
676+
# turns them off for this flag. The flag, its value, and its reason stay.
677+
track_events = False
678+
track_reason = False
679+
debug_events_until_date = None
615680
flag_state = {
616681
'key': flag['key'],
617682
'value': detail.value,
618683
'variation': detail.variation_index,
619684
'reason': detail.reason,
620685
'version': flag['version'],
621686
'prerequisites': prerequisites,
622-
'trackEvents': flag.get('trackEvents', False) or requires_experiment_data,
623-
'trackReason': requires_experiment_data,
624-
'debugEventsUntilDate': flag.get('debugEventsUntilDate', None),
687+
'trackEvents': track_events,
688+
'trackReason': track_reason,
689+
'debugEventsUntilDate': debug_events_until_date,
625690
}
626691

627692
state.add_flag(flag_state, with_reasons, details_only_if_tracked)

0 commit comments

Comments
 (0)