diff --git a/.github/workflows/sdk-compliance.yml b/.github/workflows/sdk-compliance.yml index be2c15f50..a9b8f8e69 100644 --- a/.github/workflows/sdk-compliance.yml +++ b/.github/workflows/sdk-compliance.yml @@ -41,7 +41,7 @@ jobs: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.compression }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} env: - HARNESS_IMAGE: ghcr.io/posthog/sdk-test-harness:1.33.0@sha256:c501156720c1f5a4daab18eabd6bd29507c340e8260c26d7bd7c87acac582c2f + HARNESS_IMAGE: ghcr.io/posthog/sdk-test-harness:1.34.0@sha256:43f75861fbcf5bc6c3d35511caa2be2d55274054c6071ebeb943aca0bcd0633a steps: - name: Check out source code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/.sampo/changesets/flag-dependency-own-context.md b/.sampo/changesets/flag-dependency-own-context.md new file mode 100644 index 000000000..7ea497d59 --- /dev/null +++ b/.sampo/changesets/flag-dependency-own-context.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +Local evaluation now evaluates a flag dependency as if the referenced flag were evaluated directly with the same inputs. It uses the referenced flag's own aggregation, properties and bucketing value, as the flags service does. Before, a person flag that depended on a group flag evaluated the group flag with the person's properties and distinct ID, and could return a different value than `/flags`. A group dependency whose group isn't passed now resolves as `false` locally instead of falling back to `/flags`. diff --git a/.sampo/changesets/group-condition-skip.md b/.sampo/changesets/group-condition-skip.md new file mode 100644 index 000000000..6cc571e26 --- /dev/null +++ b/.sampo/changesets/group-condition-skip.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +Local evaluation of a group flag without a usable group key now skips only its group conditions, as the flags service does. Its conditions aggregated on the person still run and can enable the flag, directly or as a dependency. A group flag with a holdout above 0% and no usable group key is inconclusive (`missing_context`) and falls back to `/flags`. diff --git a/.sampo/changesets/known-absent-property-keys.md b/.sampo/changesets/known-absent-property-keys.md new file mode 100644 index 000000000..2f4fee61a --- /dev/null +++ b/.sampo/changesets/known-absent-property-keys.md @@ -0,0 +1,5 @@ +--- +posthog: minor +--- + +Add `person_property_keys_known_absent` and `group_property_keys_known_absent` to flag evaluation. Local evaluation treats a listed key as absent, so `is_not_set` and negated operators match without a `/flags` request, and a listed `$feature_enrollment/` means not enrolled. Remote requests send the listed keys. Each list allows at most 1000 keys; a longer list raises `ValueError` and nothing is sent. diff --git a/.sampo/changesets/unusable-group-key.md b/.sampo/changesets/unusable-group-key.md new file mode 100644 index 000000000..02612e369 --- /dev/null +++ b/.sampo/changesets/unusable-group-key.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: patch +--- + +Local evaluation now treats an empty-string, `None`, boolean, list or dict group key as no group key, as the flags service does. Conditions aggregated on that group type are skipped locally without a `/flags` request, so a flag with only such conditions resolves as `false`, directly or as a dependency. Before, an empty string was used as the bucketing key and the other kinds fell back to `/flags`. diff --git a/posthog/__init__.py b/posthog/__init__.py index 7d2493321..4d88c5da3 100644 --- a/posthog/__init__.py +++ b/posthog/__init__.py @@ -1,5 +1,5 @@ import datetime # noqa: F401 -from typing import Any, Callable, Dict, Mapping, Optional, Union # noqa: F401 +from typing import Any, Callable, Dict, Iterable, Mapping, Optional, Union # noqa: F401 from typing_extensions import Unpack @@ -865,6 +865,9 @@ def feature_enabled( send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[bool]: """ Use feature flags to enable or disable features for users. @@ -883,6 +886,10 @@ def feature_enabled( send_feature_flag_events: Whether to send feature flag events disable_geoip: Whether to disable GeoIP lookup device_id: Optional device ID override for experience-continuity flags + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Details: You can call `posthog.load_feature_flags()` before to make sure you're not doing unexpected requests. @@ -909,6 +916,8 @@ def feature_enabled( send_feature_flag_events=send_feature_flag_events, disable_geoip=disable_geoip, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) @@ -922,6 +931,9 @@ def get_feature_flag( send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[FlagValue]: """ Get feature flag variant for users. Used with experiments. @@ -940,6 +952,10 @@ def get_feature_flag( send_feature_flag_events: Whether to send feature flag events disable_geoip: Whether to disable GeoIP lookup device_id: Optional device ID override for experience-continuity flags + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Details: `groups` are a mapping from group type to group key. So, if you have a group type of "organization" and a group key of "5", you would pass groups={"organization": "5"}. `group_properties` take the format: { group_type_name: { group_properties } }. So, for example, if you have the group type "organization" and the group key "5", with the properties name, and employee count, you'll send these as: group_properties={"organization": {"name": "PostHog", "employees": 11}}. @@ -966,6 +982,8 @@ def get_feature_flag( send_feature_flag_events=send_feature_flag_events, disable_geoip=disable_geoip, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) @@ -978,6 +996,9 @@ def get_all_flags( disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, flag_keys_to_evaluate: Optional[list[str]] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[dict[str, FlagValue]]: """ Get all flags for a given user. @@ -991,6 +1012,10 @@ def get_all_flags( disable_geoip: Whether to disable GeoIP lookup device_id: Optional device ID override for experience-continuity flags flag_keys_to_evaluate: Optional list of flag keys to evaluate (evaluates all if None) + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Details: Flags are key-value pairs where the key is the flag key and the value is the flag variant, or True, or False. @@ -1014,6 +1039,8 @@ def get_all_flags( disable_geoip=disable_geoip, device_id=device_id, flag_keys_to_evaluate=flag_keys_to_evaluate, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) @@ -1027,6 +1054,9 @@ def get_feature_flag_result( send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[FeatureFlagResult]: """ Get a FeatureFlagResult object which contains the flag result and payload. @@ -1048,6 +1078,10 @@ def get_feature_flag_result( send_feature_flag_events: Whether to send a $feature_flag_called event. disable_geoip: Whether to disable GeoIP lookup. device_id: Optional device ID override for experience-continuity flags. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Example: ```python @@ -1069,6 +1103,8 @@ def get_feature_flag_result( send_feature_flag_events=send_feature_flag_events, disable_geoip=disable_geoip, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) @@ -1083,6 +1119,9 @@ def get_feature_flag_payload( send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[object]: """ Get the payload associated with a feature flag value. @@ -1101,6 +1140,10 @@ def get_feature_flag_payload( send_feature_flag_events: Whether to send a $feature_flag_called event. disable_geoip: Whether to disable GeoIP lookup. device_id: Optional device ID override for experience-continuity flags. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Returns: The payload associated with the matched feature flag value, or None. @@ -1122,6 +1165,8 @@ def get_feature_flag_payload( send_feature_flag_events=send_feature_flag_events, disable_geoip=disable_geoip, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) @@ -1154,6 +1199,9 @@ def get_all_flags_and_payloads( disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, flag_keys_to_evaluate: Optional[list[str]] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> FlagsAndPayloads: """ Get all feature flag values and payloads for a user. @@ -1168,6 +1216,10 @@ def get_all_flags_and_payloads( device_id: Optional device ID override for experience-continuity flags. flag_keys_to_evaluate: Optional list of flag keys to evaluate. Evaluates all flags when omitted. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Returns: A dict with ``featureFlags`` and ``featureFlagPayloads`` entries. @@ -1185,6 +1237,8 @@ def get_all_flags_and_payloads( disable_geoip=disable_geoip, device_id=device_id, flag_keys_to_evaluate=flag_keys_to_evaluate, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) @@ -1197,6 +1251,9 @@ def evaluate_flags( disable_geoip: Optional[bool] = None, flag_keys: Optional[list[str]] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> FeatureFlagEvaluations: """Evaluate all feature flags for a user in a single call and return a :class:`FeatureFlagEvaluations` snapshot. Branch on ``.is_enabled()`` / @@ -1226,6 +1283,17 @@ def evaluate_flags( device_id: Optional device ID override. If not provided, falls back to the context device_id (which may be set via tracing headers). Used by experience-continuity flags to match users across distinct_id changes. + person_property_keys_known_absent: Person property keys the caller knows are + absent for this person. Local evaluation treats a listed key as absent, + even when ``person_properties`` supplies a value for it: ``is_not_set`` + and the negated operators match, and every other operator does not, with + no remote fallback. A listed ``$feature_enrollment/`` means not + enrolled. Keys starting with ``__posthog_person_metadata__`` are ignored. + Sent to ``/flags`` on remote evaluation. At most 1000 keys, counting + duplicates; a longer list raises ``ValueError`` and nothing is evaluated. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. A key applies only to its own group type. Same + rules and per-group-type limit as ``person_property_keys_known_absent``. Examples: ```python @@ -1249,6 +1317,8 @@ def evaluate_flags( disable_geoip=disable_geoip, flag_keys=flag_keys, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) diff --git a/posthog/async_client.py b/posthog/async_client.py index 7401e3740..cc9caed8b 100644 --- a/posthog/async_client.py +++ b/posthog/async_client.py @@ -11,7 +11,7 @@ import weakref from dataclasses import replace from datetime import datetime, timezone -from typing import Any, Callable, Dict, Mapping, Optional, Union +from typing import Any, Callable, Dict, Iterable, Mapping, Optional, Union from uuid import UUID from typing_extensions import Unpack @@ -94,6 +94,7 @@ ) from .consumer import AI_MAX_MSG_SIZE, MAX_MSG_SIZE from .emails import AsyncEmails, _client_emails, _validate_options +from .feature_flags import _validate_known_absent_keys from .feature_flag_evaluations import ( FeatureFlagEvaluations, _EvaluatedFlagRecord, @@ -1117,6 +1118,8 @@ async def _get_flags_decision( disable_geoip: Optional[bool] = None, flag_keys: Optional[list[str]] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[list[str]] = None, + group_property_keys_known_absent: Optional[dict[str, list[str]]] = None, ): if disable_geoip is None: disable_geoip = self.disable_geoip @@ -1130,6 +1133,14 @@ async def _get_flags_decision( } if flag_keys: request_data["flag_keys_to_evaluate"] = flag_keys + if person_property_keys_known_absent: + request_data["person_property_keys_known_absent"] = ( + person_property_keys_known_absent + ) + if group_property_keys_known_absent: + request_data["group_property_keys_known_absent"] = ( + group_property_keys_known_absent + ) response = await _async_flags( self.api_key, self.host, @@ -1155,6 +1166,8 @@ async def evaluate_flags( disable_geoip: Optional[bool] = None, flag_keys: Optional[list[str]] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> FeatureFlagEvaluations: """Evaluate flags remotely without blocking the event loop. @@ -1162,8 +1175,17 @@ async def evaluate_flags( ``capture(flags=...)`` to attach the exact values used for branching. This client does not evaluate flags locally, so the snapshot's ``unresolved_flags`` is always empty. + + ``person_property_keys_known_absent`` and ``group_property_keys_known_absent`` + (keyed by group type) list property keys the caller knows are absent. They + are sent to ``/flags``, which treats each listed key as absent even when a + value is supplied for it. Each list holds at most 1000 keys, counting + duplicates; a longer list raises ``ValueError`` and no request is sent. """ host = self._get_feature_flag_evaluations_host() + person_keys_known_absent, group_keys_known_absent = _validate_known_absent_keys( + person_property_keys_known_absent, group_property_keys_known_absent + ) if distinct_id is None: distinct_id = _get_context_distinct_id() if device_id is None: @@ -1207,6 +1229,8 @@ async def evaluate_flags( disable_geoip=disable_geoip, flag_keys=flag_keys, device_id=device_id, + person_property_keys_known_absent=person_keys_known_absent, + group_property_keys_known_absent=group_keys_known_absent, ) request_id = response.get("requestId") raw_evaluated_at = response.get("evaluatedAt") diff --git a/posthog/client.py b/posthog/client.py index 7d4de2c8a..98c61373d 100644 --- a/posthog/client.py +++ b/posthog/client.py @@ -19,6 +19,7 @@ Callable, Dict, FrozenSet, + Iterable, List, Mapping, NamedTuple, @@ -122,10 +123,13 @@ from posthog.feature_flags import ( InconclusiveMatchError, RequiresServerEvaluation, + _compute_flag_locally, + _FlagEvaluationContext, _get_definition_unresolved_reason, - _group_key_to_string, - match_feature_flag_properties, - resolve_bucketing_value, + _mark_known_absent_properties, + _validate_known_absent_keys, + match_feature_flag_properties as match_feature_flag_properties, + resolve_bucketing_value as resolve_bucketing_value, ) from posthog.flag_definition_cache import ( FlagDefinitionCacheData, @@ -2085,6 +2089,9 @@ def get_feature_variants( disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> dict[str, Union[bool, str]]: """ Get feature flag variants for a user. @@ -2098,6 +2105,10 @@ def get_feature_variants( flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Category: Feature flags @@ -2110,6 +2121,8 @@ def get_feature_variants( disable_geoip, flag_keys_to_evaluate, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) return to_values(resp_data) or {} @@ -2122,6 +2135,9 @@ def get_feature_payloads( disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> dict[str, Optional[str]]: """ Get feature flag payloads for a user, preserving valid serialized JSON. @@ -2135,6 +2151,10 @@ def get_feature_payloads( flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Examples: ```python @@ -2152,6 +2172,8 @@ def get_feature_payloads( disable_geoip, flag_keys_to_evaluate, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) return { key: _parse_flag_payload(payload, decode=False) @@ -2167,6 +2189,9 @@ def get_feature_flags_and_payloads( disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> FlagsAndPayloads: """ Get feature flags and payloads for a user. @@ -2180,6 +2205,10 @@ def get_feature_flags_and_payloads( flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Examples: ```python @@ -2197,6 +2226,8 @@ def get_feature_flags_and_payloads( disable_geoip, flag_keys_to_evaluate, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) response = to_flags_and_payloads(resp) payloads = response.get("featureFlagPayloads") @@ -2216,6 +2247,9 @@ def get_flags_decision( disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> FlagsResponse: """ Get feature flags decision. @@ -2229,6 +2263,10 @@ def get_flags_decision( flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Examples: ```python @@ -2238,6 +2276,9 @@ def get_flags_decision( Category: Feature flags """ + person_keys_known_absent, group_keys_known_absent = _validate_known_absent_keys( + person_property_keys_known_absent, group_property_keys_known_absent + ) try: return self._get_flags_decision( distinct_id, @@ -2247,6 +2288,8 @@ def get_flags_decision( disable_geoip, flag_keys_to_evaluate, device_id=device_id, + person_property_keys_known_absent=person_keys_known_absent, + group_property_keys_known_absent=group_keys_known_absent, ) except Exception as err: self.log.exception("Unable to get feature flags: %s", err) @@ -2261,6 +2304,9 @@ def _get_flags_decision( disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, + *, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> FlagsResponse: if self.disabled: return normalize_flags_response({}) @@ -2293,6 +2339,14 @@ def _get_flags_decision( if flag_keys_to_evaluate: request_data["flag_keys_to_evaluate"] = flag_keys_to_evaluate + person_keys_known_absent, group_keys_known_absent = _validate_known_absent_keys( + person_property_keys_known_absent, group_property_keys_known_absent + ) + if person_keys_known_absent: + request_data["person_property_keys_known_absent"] = person_keys_known_absent + if group_keys_known_absent: + request_data["group_property_keys_known_absent"] = group_keys_known_absent + resp_data = flags( self.api_key, self.host, @@ -2496,6 +2550,12 @@ def _capture( disable_geoip=disable_geoip, only_evaluate_locally=True, flag_keys_to_evaluate=flag_options["flag_keys_filter"], + person_property_keys_known_absent=flag_options.get( + "person_property_keys_known_absent" + ), + group_property_keys_known_absent=flag_options.get( + "group_property_keys_known_absent" + ), ) elif flag_options["only_evaluate_locally"] is False: # Remote evaluation explicitly requested @@ -2506,6 +2566,12 @@ def _capture( group_properties=flag_options["group_properties"], disable_geoip=disable_geoip, flag_keys_to_evaluate=flag_options["flag_keys_filter"], + person_property_keys_known_absent=flag_options.get( + "person_property_keys_known_absent" + ), + group_property_keys_known_absent=flag_options.get( + "group_property_keys_known_absent" + ), ) elif self.feature_flags: # Local flags available, prefer local evaluation @@ -2517,6 +2583,12 @@ def _capture( disable_geoip=disable_geoip, only_evaluate_locally=True, flag_keys_to_evaluate=flag_options["flag_keys_filter"], + person_property_keys_known_absent=flag_options.get( + "person_property_keys_known_absent" + ), + group_property_keys_known_absent=flag_options.get( + "group_property_keys_known_absent" + ), ) else: # Fall back to remote evaluation @@ -2527,6 +2599,12 @@ def _capture( group_properties=flag_options["group_properties"], disable_geoip=disable_geoip, flag_keys_to_evaluate=flag_options["flag_keys_filter"], + person_property_keys_known_absent=flag_options.get( + "person_property_keys_known_absent" + ), + group_property_keys_known_absent=flag_options.get( + "group_property_keys_known_absent" + ), ) except Exception as e: self.log.exception( @@ -2574,7 +2652,7 @@ def _parse_send_feature_flags(self, send_feature_flags) -> SendFeatureFlagsOptio TypeError: If send_feature_flags is not bool or dict """ if isinstance(send_feature_flags, dict): - return { + options: SendFeatureFlagsOptions = { "should_send": True, "only_evaluate_locally": send_feature_flags.get( "only_evaluate_locally" @@ -2583,6 +2661,19 @@ def _parse_send_feature_flags(self, send_feature_flags) -> SendFeatureFlagsOptio "group_properties": send_feature_flags.get("group_properties"), "flag_keys_filter": send_feature_flags.get("flag_keys_filter"), } + # Validate here so invalid keys fail the whole capture call instead of + # being swallowed as a flag enrichment failure. + person_keys_known_absent, group_keys_known_absent = ( + _validate_known_absent_keys( + send_feature_flags.get("person_property_keys_known_absent"), + send_feature_flags.get("group_property_keys_known_absent"), + ) + ) + if person_keys_known_absent: + options["person_property_keys_known_absent"] = person_keys_known_absent + if group_keys_known_absent: + options["group_property_keys_known_absent"] = group_keys_known_absent + return options elif isinstance(send_feature_flags, bool): return { "should_send": send_feature_flags, @@ -4585,107 +4676,22 @@ def _compute_flag_locally( if _definition_snapshot is not None else self._local_evaluation_snapshot() ) - flags_by_key = snapshot["flags_by_key"] - property_matching_version = snapshot.get("property_matching_version", 1) - groups = groups or {} - person_properties = person_properties or {} - group_properties = group_properties or {} - - # Create evaluation cache for flag dependencies - evaluation_cache: dict[str, Optional[FlagValue]] = {} - - if not feature_flag.get("active"): - return False - - if feature_flag.get("ensure_experience_continuity", False): - raise InconclusiveMatchError( - "Flag has experience continuity enabled", - reason=UnresolvedFlagReason.EXPERIENCE_CONTINUITY, - ) - - flag_filters = feature_flag.get("filters") or {} - aggregation_group_type_index = flag_filters.get("aggregation_group_type_index") - group_type_mapping = snapshot["group_type_mapping"] - - if aggregation_group_type_index is not None: - group_name = group_type_mapping.get(str(aggregation_group_type_index)) - - if not group_name: - self.log.warning( - f"[FEATURE FLAGS] Unknown group type index {aggregation_group_type_index} for feature flag {feature_flag['key']}" - ) - # failover to `/flags` - raise InconclusiveMatchError( - "Flag has unknown group type index", - reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, - ) - - if group_name not in groups: - # Group flags are never enabled in `groups` aren't passed in - # don't failover to `/flags`, since response will be the same - if warn_on_unknown_groups: - self.log.warning( - f"[FEATURE FLAGS] Can't compute group feature flag: {feature_flag['key']} without group names passed in" - ) - else: - self.log.debug( - f"[FEATURE FLAGS] Can't compute group feature flag: {feature_flag['key']} without group names passed in" - ) - return False - - if group_name not in group_properties: - raise InconclusiveMatchError( - f"Flag has no group properties for group '{group_name}'", - reason=UnresolvedFlagReason.MISSING_CONTEXT, - ) - focused_group_properties = group_properties[group_name] - group_key = _group_key_to_string(groups[group_name]) - return match_feature_flag_properties( - feature_flag, - group_key, - focused_group_properties, - cohort_properties=snapshot["cohorts"], - flags_by_key=flags_by_key, - property_matching_version=property_matching_version, - evaluation_cache=evaluation_cache, - device_id=device_id, - bucketing_value=group_key, - group_type_mapping=group_type_mapping, - groups=groups, - group_properties=group_properties, - ) - else: - try: - bucketing_value = resolve_bucketing_value( - feature_flag, distinct_id, device_id - ) - except InconclusiveMatchError as e: - # No condition is checked without a bucketing value, so a cause in - # the definition also applies and outranks missing_context. - e.reason = ( - _get_definition_unresolved_reason( - feature_flag, - flags_by_key, - snapshot["cohorts"], - group_type_mapping, - ) - or e.reason - ) - raise - return match_feature_flag_properties( - feature_flag, - distinct_id, - person_properties, - cohort_properties=snapshot["cohorts"], - flags_by_key=flags_by_key, - property_matching_version=property_matching_version, - evaluation_cache=evaluation_cache, + return _compute_flag_locally( + feature_flag, + _FlagEvaluationContext( + distinct_id=distinct_id, + groups=groups or {}, + person_properties=person_properties or {}, + group_properties=group_properties or {}, + group_type_mapping=snapshot["group_type_mapping"], device_id=device_id, - bucketing_value=bucketing_value, - group_type_mapping=group_type_mapping, - groups=groups, - group_properties=group_properties, - ) + ), + cohort_properties=snapshot["cohorts"], + flags_by_key=snapshot["flags_by_key"], + property_matching_version=snapshot.get("property_matching_version", 1), + evaluation_cache={}, + warn_on_unknown_groups=warn_on_unknown_groups, + ) def feature_enabled( self, @@ -4699,6 +4705,8 @@ def feature_enabled( send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[bool]: """ Check if a feature flag is enabled for a user. @@ -4717,6 +4725,10 @@ def feature_enabled( send_feature_flag_events: Whether to send feature flag events. disable_geoip: Whether to disable GeoIP for this request. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Examples: ```python @@ -4750,6 +4762,8 @@ def feature_enabled( send_feature_flag_events=send_feature_flag_events, disable_geoip=disable_geoip, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) response = flag_result.get_value() if flag_result else None @@ -4757,12 +4771,39 @@ def feature_enabled( return None return bool(response) + @staticmethod + def _known_absent_listing_digest( + person_keys_known_absent: Optional[list[str]], + group_keys_known_absent: Optional[dict[str, list[str]]], + ) -> Optional[str]: + """Return the digest the fallback cache stores with this evaluation. + + Known-absent keys can change a flag's value, so a cached result is only + served to a call with the same listing. Equivalent listings (any order, + repeats) share a digest; an unlisted call has none.""" + if not person_keys_known_absent and not group_keys_known_absent: + return None + listing = json.dumps( + [ + sorted(set(person_keys_known_absent or [])), + sorted( + (group_type, sorted(set(keys))) + for group_type, keys in (group_keys_known_absent or {}).items() + ), + ], + separators=(",", ":"), + ) + return _hashlib.sha256(listing.encode("utf-8")).hexdigest() + def _get_stale_flag_fallback( - self, distinct_id: ID_TYPES, key: str + self, distinct_id: ID_TYPES, key: str, listing_digest: Optional[str] = None ) -> Optional[FeatureFlagResult]: """Returns a stale cached flag value if available, otherwise None.""" if self.flag_cache: - stale_result = self.flag_cache.get_stale_cached_flag(distinct_id, key) + # Only a result cached with the same listing is served. + stale_result = self.flag_cache._get_stale_cached_flag( + distinct_id, key, listing_digest=listing_digest + ) if isinstance(stale_result, FeatureFlagResult): self.log.info( f"[FEATURE FLAGS] Using stale cached value for flag {key}" @@ -4783,7 +4824,12 @@ def _get_feature_flag_result( send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[FeatureFlagResult]: + person_keys_known_absent, group_keys_known_absent = _validate_known_absent_keys( + person_property_keys_known_absent, group_property_keys_known_absent + ) if self.disabled: return None @@ -4813,19 +4859,21 @@ def _get_feature_flag_result( if device_id is None: device_id = get_context_device_id() - local_person_properties = self._person_properties_for_local_evaluation( - distinct_id, person_properties - ) flag_value, snapshot = self._locally_evaluate_flag( key, distinct_id, groups, - local_person_properties, + person_properties, group_properties, device_id, + person_keys_known_absent=person_keys_known_absent, + group_keys_known_absent=group_keys_known_absent, ) local_definition_version = snapshot["flag_definition_version"] flag_was_locally_evaluated = flag_value is not None + listing_digest = self._known_absent_listing_digest( + person_keys_known_absent, group_keys_known_absent + ) if flag_value is not None: lookup_match_value = ( @@ -4855,8 +4903,12 @@ def _get_feature_flag_result( if self.flag_cache and cached_flag_result: # The cache rejects invalidated generations, including writes # already in flight when new definitions are published. - self.flag_cache.set_cached_flag( - distinct_id, key, cached_flag_result, local_definition_version + self.flag_cache._set_cached_flag( + distinct_id, + key, + cached_flag_result, + local_definition_version, + listing_digest=listing_digest, ) elif only_evaluate_locally: if self.feature_flags is None: @@ -4880,6 +4932,8 @@ def _get_feature_flag_result( group_properties, disable_geoip, device_id=device_id, + person_property_keys_known_absent=person_keys_known_absent, + group_property_keys_known_absent=group_keys_known_absent, ) errors = [] if errors_while_computing: @@ -4907,13 +4961,18 @@ def _get_feature_flag_result( request_id = None evaluated_at = None flag_result = ( - self._get_stale_flag_fallback(distinct_id, key) or flag_result + self._get_stale_flag_fallback(distinct_id, key, listing_digest) + or flag_result ) # The request-start generation is an invalidation boundary, not # a claim about the server's definitions. Refresh rejects late writes. elif self.flag_cache and flag_result: self.flag_cache._set_cached_remote_flag( - distinct_id, key, flag_result, local_definition_version + distinct_id, + key, + flag_result, + local_definition_version, + listing_digest=listing_digest, ) self.log.debug( @@ -4927,23 +4986,33 @@ def _get_feature_flag_result( except QuotaLimitError as e: self.log.warning(f"[FEATURE FLAGS] Quota limit exceeded: {e}") feature_flag_error = FeatureFlagError.QUOTA_LIMITED - flag_result = self._get_stale_flag_fallback(distinct_id, key) + flag_result = self._get_stale_flag_fallback( + distinct_id, key, listing_digest + ) except RequestsTimeout as e: self.log.warning(f"[FEATURE FLAGS] Request timed out: {e}") feature_flag_error = FeatureFlagError.TIMEOUT - flag_result = self._get_stale_flag_fallback(distinct_id, key) + flag_result = self._get_stale_flag_fallback( + distinct_id, key, listing_digest + ) except RequestsConnectionError as e: self.log.warning(f"[FEATURE FLAGS] Connection error: {e}") feature_flag_error = FeatureFlagError.CONNECTION_ERROR - flag_result = self._get_stale_flag_fallback(distinct_id, key) + flag_result = self._get_stale_flag_fallback( + distinct_id, key, listing_digest + ) except APIError as e: self.log.warning(f"[FEATURE FLAGS] API error: {e}") feature_flag_error = FeatureFlagError.api_error(e.status) - flag_result = self._get_stale_flag_fallback(distinct_id, key) + flag_result = self._get_stale_flag_fallback( + distinct_id, key, listing_digest + ) except Exception as e: self.log.exception(f"[FEATURE FLAGS] Unable to get flag remotely: {e}") feature_flag_error = FeatureFlagError.UNKNOWN_ERROR - flag_result = self._get_stale_flag_fallback(distinct_id, key) + flag_result = self._get_stale_flag_fallback( + distinct_id, key, listing_digest + ) if send_feature_flag_events: # Locally-evaluated flags carry has_experiment in the stored definition; @@ -5002,6 +5071,8 @@ def get_feature_flag_result( send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[FeatureFlagResult]: """ Get a FeatureFlagResult object which contains the flag result and payload for a key by evaluating locally or remotely @@ -5030,6 +5101,10 @@ def get_feature_flag_result( send_feature_flag_events: Whether to send feature flag events. disable_geoip: Whether to disable GeoIP for this request. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Returns: Optional[FeatureFlagResult]: The evaluated result, including a healthy @@ -5046,6 +5121,8 @@ def get_feature_flag_result( send_feature_flag_events=send_feature_flag_events, disable_geoip=disable_geoip, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) def get_feature_flag( @@ -5060,6 +5137,8 @@ def get_feature_flag( send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[FlagValue]: """ Get multivariate feature flag value for a user. @@ -5078,6 +5157,10 @@ def get_feature_flag( send_feature_flag_events: Whether to send feature flag events. disable_geoip: Whether to disable GeoIP for this request. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Examples: ```python @@ -5111,6 +5194,8 @@ def get_feature_flag( send_feature_flag_events=send_feature_flag_events, disable_geoip=disable_geoip, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) return feature_flag_result.get_value() if feature_flag_result else None @@ -5122,6 +5207,9 @@ def _locally_evaluate_flag( person_properties: dict[str, str], group_properties: dict[str, dict[str, Any]], device_id: Optional[str] = None, + *, + person_keys_known_absent: Optional[list[str]] = None, + group_keys_known_absent: Optional[dict[str, list[str]]] = None, ) -> tuple[Optional[FlagValue], _LocalEvaluationSnapshot]: """Return the local value and its definitions for consistent payload lookup.""" if self.feature_flags is None and self.personal_api_key: @@ -5132,6 +5220,16 @@ def _locally_evaluate_flag( if snapshot["flags"]: flag = snapshot["flags_by_key"].get(key) if flag: + person_properties, group_properties = ( + self._properties_for_local_evaluation( + distinct_id, + person_properties, + group_properties, + snapshot, + person_keys_known_absent, + group_keys_known_absent, + ) + ) try: response = self._compute_flag_locally( flag, @@ -5166,6 +5264,8 @@ def get_feature_flag_payload( send_feature_flag_events: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[object]: """ Get the payload for a feature flag. @@ -5185,6 +5285,10 @@ def get_feature_flag_payload( send_feature_flag_events: Deprecated. Use get_feature_flag() instead if you need events. disable_geoip: Whether to disable GeoIP for this request. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Returns: The payload associated with the matched feature flag value, or None. @@ -5231,6 +5335,8 @@ def get_feature_flag_payload( send_feature_flag_events=send_feature_flag_events, disable_geoip=disable_geoip, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) return feature_flag_result.payload if feature_flag_result else None @@ -5243,6 +5349,8 @@ def _get_feature_flag_details_from_server( group_properties: dict[str, dict[str, Any]], disable_geoip: Optional[bool], device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[list[str]] = None, + group_property_keys_known_absent: Optional[dict[str, list[str]]] = None, ) -> tuple[Optional[FeatureFlag], Optional[str], Optional[int], bool, bool]: """ Calls /flags and returns the flag details, request id, evaluated at timestamp, @@ -5258,6 +5366,8 @@ def _get_feature_flag_details_from_server( disable_geoip, flag_keys_to_evaluate=[key], device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) request_id = resp_data.get("requestId") evaluated_at = resp_data.get("evaluatedAt") @@ -5458,6 +5568,8 @@ def get_all_flags( disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> Optional[dict[str, Union[bool, str]]]: """ Get all feature flags for a user. @@ -5472,6 +5584,10 @@ def get_all_flags( flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Examples: ```python @@ -5490,6 +5606,8 @@ def get_all_flags( disable_geoip=disable_geoip, flag_keys_to_evaluate=flag_keys_to_evaluate, device_id=device_id, + person_property_keys_known_absent=person_property_keys_known_absent, + group_property_keys_known_absent=group_property_keys_known_absent, ) return response["featureFlags"] @@ -5505,6 +5623,8 @@ def get_all_flags_and_payloads( disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> FlagsAndPayloads: """ Get all feature flags and their payloads for a user. @@ -5519,6 +5639,10 @@ def get_all_flags_and_payloads( flag_keys_to_evaluate: A list of specific flag keys to evaluate. If provided, only these flags will be evaluated, improving performance. device_id: The device ID for this request. + person_property_keys_known_absent: Person property keys known to be absent. + See ``evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. See ``evaluate_flags``. Examples: ```python @@ -5528,6 +5652,9 @@ def get_all_flags_and_payloads( Category: Feature flags """ + person_keys_known_absent, group_keys_known_absent = _validate_known_absent_keys( + person_property_keys_known_absent, group_property_keys_known_absent + ) if self.disabled: return {"featureFlags": None, "featureFlagPayloads": None} @@ -5543,16 +5670,15 @@ def get_all_flags_and_payloads( groups = groups or {} - local_person_properties = self._person_properties_for_local_evaluation( - distinct_id, person_properties - ) response, fallback_to_flags, _ = self._get_all_flags_and_payloads_locally( distinct_id, groups=groups, - person_properties=local_person_properties, + person_properties=person_properties, group_properties=group_properties, flag_keys_to_evaluate=flag_keys_to_evaluate, device_id=device_id, + person_keys_known_absent=person_keys_known_absent, + group_keys_known_absent=group_keys_known_absent, ) if fallback_to_flags and not only_evaluate_locally: @@ -5565,6 +5691,8 @@ def get_all_flags_and_payloads( disable_geoip=disable_geoip, flag_keys_to_evaluate=flag_keys_to_evaluate, device_id=device_id, + person_property_keys_known_absent=person_keys_known_absent, + group_property_keys_known_absent=group_keys_known_absent, ) remote_response = to_flags_and_payloads(decide_response) # A key the server marked failed keeps its locally computed value @@ -5616,6 +5744,8 @@ def evaluate_flags( disable_geoip: Optional[bool] = None, flag_keys: Optional[List[str]] = None, device_id: Optional[str] = None, + person_property_keys_known_absent: Optional[Iterable[str]] = None, + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None, ) -> FeatureFlagEvaluations: """Evaluate all feature flags for a user in a single call and return a :class:`FeatureFlagEvaluations` snapshot. Branch on ``.is_enabled()`` / @@ -5649,6 +5779,17 @@ def evaluate_flags( device_id: Optional device ID override. If not provided, falls back to the context device_id (which may be set via tracing headers). Used by experience-continuity flags to match users across distinct_id changes. + person_property_keys_known_absent: Person property keys the caller knows are + absent for this person. Local evaluation treats a listed key as absent, + even when ``person_properties`` supplies a value for it: ``is_not_set`` + and the negated operators match, and every other operator does not, with + no remote fallback. A listed ``$feature_enrollment/`` means not + enrolled. Keys starting with ``__posthog_person_metadata__`` are ignored. + Sent to ``/flags`` on remote evaluation. At most 1000 keys, counting + duplicates; a longer list raises ``ValueError`` and nothing is evaluated. + group_property_keys_known_absent: Group property keys known to be absent, + keyed by group type. A key applies only to its own group type. Same + rules and per-group-type limit as ``person_property_keys_known_absent``. Returns: A :class:`FeatureFlagEvaluations` snapshot. @@ -5668,6 +5809,9 @@ def evaluate_flags( Feature flags """ host = self._get_feature_flag_evaluations_host() + person_keys_known_absent, group_keys_known_absent = _validate_known_absent_keys( + person_property_keys_known_absent, group_property_keys_known_absent + ) if distinct_id is None: distinct_id = get_context_distinct_id() @@ -5711,18 +5855,17 @@ def evaluate_flags( locally_evaluated_keys: set[str] = set() unresolved: Dict[str, UnresolvedFlagReason] = {} # Try local evaluation first when the poller has loaded definitions. - local_person_properties = self._person_properties_for_local_evaluation( - distinct_id, person_properties - ) local_result, fallback_to_server, definition_snapshot = ( self._get_all_flags_and_payloads_locally( distinct_id, groups=dict(groups), - person_properties=local_person_properties, + person_properties=person_properties, group_properties=group_properties, flag_keys_to_evaluate=flag_keys, device_id=device_id, unresolved=unresolved, + person_keys_known_absent=person_keys_known_absent, + group_keys_known_absent=group_keys_known_absent, ) ) @@ -5767,6 +5910,8 @@ def evaluate_flags( disable_geoip=disable_geoip, flag_keys_to_evaluate=flag_keys, device_id=device_id, + person_property_keys_known_absent=person_keys_known_absent, + group_property_keys_known_absent=group_keys_known_absent, ) request_id = response.get("requestId") raw_evaluated_at = response.get("evaluatedAt") @@ -5836,10 +5981,9 @@ def _get_all_flags_and_payloads_locally( flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, unresolved: Optional[Dict[str, UnresolvedFlagReason]] = None, + person_keys_known_absent: Optional[list[str]] = None, + group_keys_known_absent: Optional[dict[str, list[str]]] = None, ) -> tuple[FlagsAndPayloads, bool, _LocalEvaluationSnapshot]: - person_properties = person_properties or {} - group_properties = group_properties or {} - if self.feature_flags is None and self.personal_api_key: self.load_feature_flags() @@ -5849,6 +5993,14 @@ def _get_all_flags_and_payloads_locally( snapshot = self._local_evaluation_snapshot() # If loading in previous line failed if snapshot["flags"]: + person_properties, group_properties = self._properties_for_local_evaluation( + distinct_id, + person_properties, + group_properties, + snapshot, + person_keys_known_absent, + group_keys_known_absent, + ) # Filter flags based on flag_keys_to_evaluate if provided flags_to_process = snapshot["flags"] if flag_keys_to_evaluate: @@ -6077,10 +6229,25 @@ def get_feature_flag_keys_by_evaluation_runtime( ).matches(wanted) ] - def _person_properties_for_local_evaluation(self, distinct_id, person_properties): + def _properties_for_local_evaluation( + self, + distinct_id, + person_properties, + group_properties, + snapshot: _LocalEvaluationSnapshot, + person_property_keys_known_absent=None, + group_property_keys_known_absent=None, + ): + """Mark listed keys with the group types of the definitions that evaluate them.""" local_person_properties = dict(person_properties or {}) local_person_properties.setdefault("distinct_id", distinct_id) - return local_person_properties + return _mark_known_absent_properties( + local_person_properties, + group_properties or {}, + person_property_keys_known_absent, + group_property_keys_known_absent, + snapshot["group_type_mapping"], + ) def _add_local_person_and_group_properties( self, groups, person_properties, group_properties diff --git a/posthog/feature_flags.py b/posthog/feature_flags.py index 6a2e98693..5a296ffab 100644 --- a/posthog/feature_flags.py +++ b/posthog/feature_flags.py @@ -1,16 +1,18 @@ import calendar import datetime import hashlib +import itertools import json import logging import math import numbers import re import warnings +from collections.abc import Iterable, Mapping from decimal import Decimal from enum import Enum from functools import lru_cache as _lru_cache -from typing import NamedTuple, NoReturn, Optional +from typing import Any, NamedTuple, NoReturn, Optional from posthog import utils as utils from posthog.types import FlagValue, UnresolvedFlagReason @@ -29,6 +31,164 @@ NONE_VALUES_ALLOWED_OPERATORS = ["is_not"] +# The flags service rejects longer known-absent key lists with HTTP 400. +_MAX_KNOWN_ABSENT_KEYS = 1000 +_PERSON_METADATA_KEY_PREFIX = "__posthog_person_metadata__" + +# For a known-absent key these operators match, and every other operator does not. +_KNOWN_ABSENT_MATCHING_OPERATORS = frozenset( + ( + "is_not_set", + "is_not", + "not_icontains", + "not_starts_with", + "not_ends_with", + "not_regex", + ) +) + + +_NOT_SUPPLIED = object() + + +class _KnownAbsent: + """Value of a property the caller listed as known absent, in the property maps + used for local evaluation. + + Only a filter on the listing's own properties reads the key as absent: a + ``person`` filter for a person listing, and a ``group`` filter of the same + group type for a group listing. A ``group`` filter without a group type reads + the condition's group type, whose properties are the map it is evaluated + against, at the top level of a condition and in its cohorts alike. Any other + filter reads the value the listing replaced, as if the key were not listed. + """ + + __slots__ = ("filter_type", "group_type_index", "replaced_value") + + def __init__( + self, + filter_type: str, + group_type_index: Optional[str], + replaced_value: Any, + ): + self.filter_type = filter_type + self.group_type_index = group_type_index + self.replaced_value = replaced_value + + def applies_to(self, prop) -> bool: + if prop.get("type") != self.filter_type: + return False + if self.filter_type == "person": + return True + filter_group_type_index = prop.get("group_type_index") + if filter_group_type_index is None: + return True + return self.group_type_index is not None and self.group_type_index == str( + filter_group_type_index + ) + + def __repr__(self) -> str: + return "" + + +def _supplied_value(property_values, key, prop) -> Any: + """Return the value local evaluation reads for ``prop``: a ``_KnownAbsent`` + when the listing applies to it, else the supplied value or ``_NOT_SUPPLIED``.""" + value = property_values.get(key, _NOT_SUPPLIED) + if isinstance(value, _KnownAbsent) and not value.applies_to(prop): + return value.replaced_value + return value + + +def _known_absent_key_list(keys, field: str) -> Optional[list[str]]: + if keys is None: + return None + # A mapping is iterable, so check for it to catch a property map passed by + # mistake. A dict's .keys() view is not a mapping and is accepted. + if isinstance(keys, (str, bytes, bytearray, Mapping)) or not isinstance( + keys, Iterable + ): + raise TypeError(f"{field} must be a collection of strings") + # Read one key past the limit so an unbounded iterable can't exhaust memory. + key_list = list(itertools.islice(keys, _MAX_KNOWN_ABSENT_KEYS + 1)) + if len(key_list) > _MAX_KNOWN_ABSENT_KEYS: + raise ValueError( + f"{field} allows at most {_MAX_KNOWN_ABSENT_KEYS} keys, got more" + ) + if not all(isinstance(key, str) for key in key_list): + raise TypeError(f"{field} must contain only strings") + return key_list or None + + +def _validate_known_absent_keys( + person_property_keys_known_absent: Optional[Iterable[str]], + group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]], +) -> tuple[Optional[list[str]], Optional[dict[str, list[str]]]]: + """Check the caller's known-absent keys against the flags service limits. + + Returns them as lists, with ``None`` for anything empty. Raises ``TypeError`` + for a wrong type and ``ValueError`` for a list over the limit, so nothing is + evaluated or sent. Lists are never truncated. + """ + person_keys = _known_absent_key_list( + person_property_keys_known_absent, "person_property_keys_known_absent" + ) + if group_property_keys_known_absent is None: + return person_keys, None + if not isinstance(group_property_keys_known_absent, Mapping): + raise TypeError( + "group_property_keys_known_absent must map group types to collections of strings" + ) + group_keys: dict[str, list[str]] = {} + for group_type, keys in group_property_keys_known_absent.items(): + if not isinstance(group_type, str) or keys is None: + raise TypeError( + "group_property_keys_known_absent must map group types to collections of strings" + ) + key_list = _known_absent_key_list( + keys, f"group_property_keys_known_absent[{group_type!r}]" + ) + if key_list: + group_keys[group_type] = key_list + return person_keys, group_keys or None + + +def _mark_known_absent_properties( + person_properties: dict[str, Any], + group_properties: dict[str, dict[str, Any]], + person_property_keys_known_absent: Optional[list[str]], + group_property_keys_known_absent: Optional[dict[str, list[str]]], + group_type_mapping: Optional[Mapping[str, str]], +) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]: + """Return copies of the local evaluation property maps with each listed key + set to a ``_KnownAbsent`` that keeps the supplied or SDK-added value. + + Each key is marked once, so a repeated key can't wrap its own marker.""" + if person_property_keys_known_absent: + person_properties = dict(person_properties) + for key in dict.fromkeys(person_property_keys_known_absent): + # Known absence never hides a persons-table field. + if not key.startswith(_PERSON_METADATA_KEY_PREFIX): + person_properties[key] = _KnownAbsent( + "person", None, person_properties.get(key, _NOT_SUPPLIED) + ) + if group_property_keys_known_absent: + group_type_indexes = { + group_type: index + for index, group_type in (group_type_mapping or {}).items() + } + group_properties = dict(group_properties) + for group_type, keys in group_property_keys_known_absent.items(): + properties = dict(group_properties.get(group_type) or {}) + for key in dict.fromkeys(keys): + properties[key] = _KnownAbsent( + "group", + group_type_indexes.get(group_type), + properties.get(key, _NOT_SUPPLIED), + ) + group_properties[group_type] = properties + return person_properties, group_properties + def _warn_malformed_flag_dependency_once(flag_key, reason): """Emit a throttled warning for a malformed flag dependency condition. @@ -179,22 +339,32 @@ def _get_holdout_variant(flag, bucketing_value) -> Optional[str]: Mirrors the server's evaluation order: a held-out value never reaches the flag's release conditions, so callers check this before matching any condition. """ + percentage = _holdout_exclusion_percentage(flag) + if percentage is None: + return None + + # The server treats 100 as "everyone" without hashing, so a 100% holdout can't + # miss on a hash boundary. + if percentage != 100.0 and _holdout_hash(bucketing_value) > percentage / 100: + return None + + return f"holdout-{flag['filters']['holdout']['id']}" + + +def _holdout_exclusion_percentage(flag) -> Optional[float]: + """The flag's holdout exclusion percentage, or None without a holdout. + + The server clamps out-of-range percentages rather than rejecting them. + """ holdout = (flag.get("filters") or {}).get("holdout") if not holdout: return None exclusion_percentage = holdout.get("exclusion_percentage") - holdout_id = holdout.get("id") - if exclusion_percentage is None or holdout_id is None: + if exclusion_percentage is None or holdout.get("id") is None: return None - # The server clamps out-of-range percentages rather than rejecting them, and treats - # 100 as "everyone" without hashing, so a 100% holdout can't miss on a hash boundary. - percentage = min(max(float(exclusion_percentage), 0.0), 100.0) - if percentage != 100.0 and _holdout_hash(bucketing_value) > percentage / 100: - return None - - return f"holdout-{holdout_id}" + return min(max(float(exclusion_percentage), 0.0), 100.0) def get_matching_variant(flag, bucketing_value): @@ -243,6 +413,8 @@ def evaluate_flag_dependency( cohort_properties, device_id=None, property_matching_version: int = 1, + *, + _evaluation_context=None, ): """ Evaluate a flag dependency condition under local evaluation. @@ -253,6 +425,10 @@ def evaluate_flag_dependency( against the condition's expected value; ancestors influence it only through the referenced flag's own recursive evaluation. + The referenced flag is evaluated as if it were evaluated directly with the + top-level inputs in ``_evaluation_context``, using its own aggregation, property + context and bucketing identifier, as the flags service does. + Args: property: Flag property with type="flag" and dependency_chain flags_by_key: Dictionary of all flags by their key @@ -261,6 +437,9 @@ def evaluate_flag_dependency( properties: Person properties for evaluation cohort_properties: Cohort properties for evaluation device_id: The device ID for bucketing (optional) + _evaluation_context: The top-level inputs of the evaluation. Without it, + the referenced flag reads ``properties`` as person properties and no + groups. Returns: bool: Whether the referenced flag's evaluated value matches the @@ -297,14 +476,21 @@ def evaluate_flag_dependency( _assert_dependency_definitions_loaded( dependency_chain, flags_by_key, evaluation_cache ) + if _evaluation_context is None: + _evaluation_context = _FlagEvaluationContext( + distinct_id=distinct_id, + groups={}, + person_properties=properties, + group_properties={}, + group_type_mapping={}, + device_id=device_id, + ) _evaluate_dependency_chain( dependency_chain, flags_by_key, evaluation_cache, - distinct_id, - properties, + _evaluation_context, cohort_properties, - device_id, property_matching_version, ) @@ -381,10 +567,8 @@ def _evaluate_dependency_chain( dependency_chain, flags_by_key, evaluation_cache, - distinct_id, - properties, + _evaluation_context: "_FlagEvaluationContext", cohort_properties, - device_id, property_matching_version, ): # Evaluate and cache each flag in the chain; members already cached are @@ -396,10 +580,8 @@ def _evaluate_dependency_chain( dep_flag_key, flags_by_key, evaluation_cache, - distinct_id, - properties, + _evaluation_context, cohort_properties, - device_id, property_matching_version, ) @@ -408,16 +590,14 @@ def _evaluate_dependency( dep_flag_key, flags_by_key, evaluation_cache, - distinct_id, - properties, + _evaluation_context: "_FlagEvaluationContext", cohort_properties, - device_id, property_matching_version, ): dep_flag = flags_by_key[dep_flag_key] - # Same order as client._compute_flag_locally: an inactive flag is false - # whatever its experience continuity setting. + # Same order as _compute_flag_locally: an inactive flag is false whatever its + # experience continuity setting. if not dep_flag.get("active"): evaluation_cache[dep_flag_key] = False return @@ -429,30 +609,17 @@ def _evaluate_dependency( reason=UnresolvedFlagReason.UNRESOLVED_DEPENDENCY, ) - # Recursively evaluate the dependency + # Evaluate the dependency as if it were evaluated directly with the same + # inputs, so it reads its own aggregation's properties and bucketing value. try: - dep_flag_filters = dep_flag.get("filters") or {} - dep_aggregation_group_type_index = dep_flag_filters.get( - "aggregation_group_type_index" - ) - if dep_aggregation_group_type_index is not None: - # Group flags should continue bucketing by the group key - # from the current evaluation context. - dep_bucketing_value = distinct_id - else: - dep_bucketing_value = resolve_bucketing_value( - dep_flag, distinct_id, device_id - ) - dep_result = match_feature_flag_properties( + dep_result = _compute_flag_locally( dep_flag, - distinct_id, - properties, + _evaluation_context, cohort_properties=cohort_properties, flags_by_key=flags_by_key, - evaluation_cache=evaluation_cache, - device_id=device_id, property_matching_version=property_matching_version, - bucketing_value=dep_bucketing_value, + evaluation_cache=evaluation_cache, + warn_on_unknown_groups=False, ) evaluation_cache[dep_flag_key] = dep_result except RequiresServerEvaluation as e: @@ -529,6 +696,143 @@ def resolve_bucketing_value(flag, distinct_id, device_id=None): return distinct_id +class _FlagEvaluationContext(NamedTuple): + """The top-level inputs of a local flag evaluation. A flag dependency is + evaluated from them as if it were evaluated directly.""" + + distinct_id: Any + groups: Mapping[str, Any] + person_properties: dict[str, Any] + group_properties: dict[str, dict[str, Any]] + group_type_mapping: Mapping[str, str] + device_id: Optional[str] + + +def _compute_flag_locally( + flag, + _evaluation_context: _FlagEvaluationContext, + *, + cohort_properties, + flags_by_key, + property_matching_version: int, + evaluation_cache: dict[str, Optional[FlagValue]], + warn_on_unknown_groups: bool, +) -> FlagValue: + """Evaluate ``flag`` locally with its own aggregation, property context and + bucketing value.""" + if not flag.get("active"): + return False + + if flag.get("ensure_experience_continuity", False): + raise InconclusiveMatchError( + "Flag has experience continuity enabled", + reason=UnresolvedFlagReason.EXPERIENCE_CONTINUITY, + ) + + distinct_id = _evaluation_context.distinct_id + groups = _evaluation_context.groups + group_properties = _evaluation_context.group_properties + group_type_mapping = _evaluation_context.group_type_mapping + device_id = _evaluation_context.device_id + flag_filters = flag.get("filters") or {} + aggregation_group_type_index = flag_filters.get("aggregation_group_type_index") + + if aggregation_group_type_index is not None: + group_name = group_type_mapping.get(str(aggregation_group_type_index)) + + if not group_name: + log.warning( + f"[FEATURE FLAGS] Unknown group type index {aggregation_group_type_index} for feature flag {flag['key']}" + ) + # failover to `/flags` + raise InconclusiveMatchError( + "Flag has unknown group type index", + reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, + ) + + if not _is_usable_group_key(groups.get(group_name)): + # The server would hash an empty group key for the holdout, so a + # holdout that can exclude anyone needs the group key. + if (_holdout_exclusion_percentage(flag) or 0.0) > 0.0: + raise InconclusiveMatchError( + f"Group flag {flag['key']} has a holdout and no group key was passed", + reason=UnresolvedFlagReason.MISSING_CONTEXT, + ) + # Conditions aggregated by this group are skipped; the flag's person + # conditions still run. + message = f"[FEATURE FLAGS] Skipping group conditions of feature flag {flag['key']} without a group key" + if warn_on_unknown_groups: + log.warning(message) + else: + log.debug(message) + # Like the server, the flag-level identifier is then an empty string. + return match_feature_flag_properties( + flag, + distinct_id, + {}, + cohort_properties=cohort_properties, + flags_by_key=flags_by_key, + property_matching_version=property_matching_version, + evaluation_cache=evaluation_cache, + device_id=device_id, + bucketing_value="", + group_type_mapping=group_type_mapping, + groups=groups, + group_properties=group_properties, + _evaluation_context=_evaluation_context, + ) + + if group_name not in group_properties: + raise InconclusiveMatchError( + f"Flag has no group properties for group '{group_name}'", + reason=UnresolvedFlagReason.MISSING_CONTEXT, + ) + group_key = _group_key_to_string(groups[group_name]) + return match_feature_flag_properties( + flag, + group_key, + group_properties[group_name], + cohort_properties=cohort_properties, + flags_by_key=flags_by_key, + property_matching_version=property_matching_version, + evaluation_cache=evaluation_cache, + device_id=device_id, + bucketing_value=group_key, + group_type_mapping=group_type_mapping, + groups=groups, + group_properties=group_properties, + _evaluation_context=_evaluation_context, + ) + + try: + bucketing_value = resolve_bucketing_value(flag, distinct_id, device_id) + except InconclusiveMatchError as e: + # No condition is checked without a bucketing value, so a cause in + # the definition also applies and outranks missing_context. + e.reason = ( + _get_definition_unresolved_reason( + flag, flags_by_key, cohort_properties, group_type_mapping + ) + or e.reason + ) + raise + return match_feature_flag_properties( + flag, + distinct_id, + _evaluation_context.person_properties, + cohort_properties=cohort_properties, + flags_by_key=flags_by_key, + property_matching_version=property_matching_version, + evaluation_cache=evaluation_cache, + device_id=device_id, + bucketing_value=bucketing_value, + group_type_mapping=group_type_mapping, + groups=groups, + group_properties=group_properties, + _evaluation_context=_evaluation_context, + ) + + def match_feature_flag_properties( flag, distinct_id, @@ -543,6 +847,7 @@ def match_feature_flag_properties( groups=None, group_properties=None, property_matching_version: int = 1, + _evaluation_context=None, ) -> FlagValue: if bucketing_value is None: warnings.warn( @@ -556,7 +861,9 @@ def match_feature_flag_properties( flag_filters = flag.get("filters") or {} if flag_filters.get("feature_enrollment") is True: - return _match_feature_enrollment(flag, flag_filters, properties) + enrolled = _match_feature_enrollment(flag, flag_filters, properties) + if enrolled is not None: + return enrolled # Holdouts are evaluated before release conditions, so a held-out value is excluded # from the flag's targeting entirely rather than being bucketed into a variant. @@ -564,6 +871,16 @@ def match_feature_flag_properties( if holdout_variant is not None: return holdout_variant + if _evaluation_context is None: + _evaluation_context = _FlagEvaluationContext( + distinct_id=distinct_id, + groups=groups or {}, + person_properties=properties, + group_properties=group_properties or {}, + group_type_mapping=group_type_mapping or {}, + device_id=device_id, + ) + return _match_flag_conditions( flag, flag_filters, @@ -578,6 +895,7 @@ def match_feature_flag_properties( groups or {}, group_properties or {}, property_matching_version, + _evaluation_context, ) @@ -595,6 +913,7 @@ def _match_flag_conditions( groups, group_properties, property_matching_version, + _evaluation_context, ) -> FlagValue: flag_conditions = flag_filters.get("groups") or [] flag_aggregation = flag_filters.get("aggregation_group_type_index") @@ -620,6 +939,7 @@ def _match_flag_conditions( property_matching_version, flag_aggregation, valid_variant_keys, + _evaluation_context, ) except RequiresServerEvaluation as e: _enrich_server_evaluation_reason( @@ -667,41 +987,43 @@ def _get_condition_context( group_type_mapping, groups, group_properties, + _evaluation_context, ): - # Per-condition aggregation overrides only when the condition explicitly - # sets its own aggregation_group_type_index (mixed targeting). - # When absent, use the properties/bucketing already resolved by the caller. + """The properties and bucketing value a condition is matched with, or None + when the condition is skipped. + + A condition uses its own aggregation_group_type_index when it has the key, an + explicit null meaning the person, and the flag-level aggregation otherwise. + ``properties`` and ``bucketing_value`` are the flag-level aggregation's. + """ condition_aggregation = condition.get( "aggregation_group_type_index", flag_aggregation ) - # Mixed-override path: condition-level aggregation differs from flag-level. - # This assumes flag-level aggregation is None for mixed flags. - if condition_aggregation != flag_aggregation: - if condition_aggregation is not None: - group_name = group_type_mapping.get(str(condition_aggregation)) - if not group_name or group_name not in groups: - log.debug( - "Skipping group condition for flag '%s': group type index %s not available", - flag.get("key", ""), - condition_aggregation, - ) - return None - if group_name not in group_properties: - raise InconclusiveMatchError( - "Group properties were not passed", - reason=UnresolvedFlagReason.MISSING_CONTEXT, - ) - effective_properties = group_properties[group_name] - effective_bucketing = _group_key_to_string(groups[group_name]) - else: - effective_properties = properties - effective_bucketing = bucketing_value - else: - effective_properties = properties - effective_bucketing = bucketing_value + if condition_aggregation is None: + if flag_aggregation is None: + return properties, bucketing_value + # A person condition of a group flag reads the person, not the group. + return _evaluation_context.person_properties, resolve_bucketing_value( + flag, _evaluation_context.distinct_id, _evaluation_context.device_id + ) - return effective_properties, effective_bucketing + group_name = group_type_mapping.get(str(condition_aggregation)) + if not group_name or not _is_usable_group_key(groups.get(group_name)): + log.debug( + "Skipping group condition for flag '%s': group type index %s not available", + flag.get("key", ""), + condition_aggregation, + ) + return None + if condition_aggregation == flag_aggregation: + return properties, bucketing_value + if group_name not in group_properties: + raise InconclusiveMatchError( + "Group properties were not passed", + reason=UnresolvedFlagReason.MISSING_CONTEXT, + ) + return group_properties[group_name], _group_key_to_string(groups[group_name]) def _match_flag_condition( @@ -720,6 +1042,7 @@ def _match_flag_condition( property_matching_version, flag_aggregation, valid_variant_keys, + _evaluation_context, ): context = _get_condition_context( flag, @@ -730,6 +1053,7 @@ def _match_flag_condition( group_type_mapping, groups, group_properties, + _evaluation_context, ) if context is None: return ConditionMatch.NO_MATCH, None @@ -745,6 +1069,7 @@ def _match_flag_condition( bucketing_value=effective_bucketing, device_id=device_id, property_matching_version=property_matching_version, + _evaluation_context=_evaluation_context, ) if match_result == ConditionMatch.MATCH: variant_override = condition.get("variant") @@ -779,19 +1104,23 @@ def _get_valid_variant_keys(flag_filters): return [variant["key"] for variant in flag_variants] -def _match_feature_enrollment(flag, flag_filters, properties) -> bool: +def _match_feature_enrollment(flag, flag_filters, properties) -> Optional[bool]: + """Return the enrollment value, or None when the person is known not to be + enrolled and evaluation continues to holdouts and release conditions.""" enrollment_key = f"$feature_enrollment/{flag.get('key')}" if flag_filters.get("aggregation_group_type_index") is not None: raise InconclusiveMatchError( "Group flag has feature enrollment, which reads person properties", reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, ) - if enrollment_key not in properties: + enrollment = _supplied_value(properties, enrollment_key, {"type": "person"}) + if isinstance(enrollment, _KnownAbsent): + return None + if enrollment is _NOT_SUPPLIED: raise InconclusiveMatchError( f"Flag has feature enrollment and '{enrollment_key}' was not passed", reason=UnresolvedFlagReason.MISSING_CONTEXT, ) - enrollment = properties[enrollment_key] return enrollment is True or enrollment == "true" @@ -805,6 +1134,7 @@ def _match_condition_filter( *, device_id, property_matching_version: int, + _evaluation_context, ) -> bool: property_type = prop.get("type") if property_type == "cohort": @@ -817,6 +1147,7 @@ def _match_condition_filter( distinct_id, device_id=device_id, property_matching_version=property_matching_version, + _evaluation_context=_evaluation_context, ) if property_type == "flag": return evaluate_flag_dependency( @@ -828,6 +1159,7 @@ def _match_condition_filter( cohort_properties, device_id=device_id, property_matching_version=property_matching_version, + _evaluation_context=_evaluation_context, ) return match_property(prop, properties, property_matching_version) @@ -844,6 +1176,7 @@ def is_condition_match( bucketing_value, device_id=None, property_matching_version: int = 1, + _evaluation_context=None, ) -> ConditionMatch: rollout_percentage = condition.get("rollout_percentage") if len(condition.get("properties") or []) > 0: @@ -857,6 +1190,7 @@ def is_condition_match( evaluation_cache, device_id, property_matching_version, + _evaluation_context, ): return ConditionMatch.NO_MATCH @@ -883,6 +1217,7 @@ def _match_condition_properties( evaluation_cache, device_id, property_matching_version, + _evaluation_context, ) -> bool: # Filters in a condition have no defined order, so an inconclusive filter does # not stop the loop: a later filter can still rule the condition out or carry a @@ -900,6 +1235,7 @@ def _match_condition_properties( distinct_id, device_id=device_id, property_matching_version=property_matching_version, + _evaluation_context=_evaluation_context, ) except RequiresServerEvaluation as e: # Fall back to the server only when this is the first filter that could @@ -1011,6 +1347,14 @@ def _json_object_to_string(value: dict, reason: UnresolvedFlagReason) -> str: return "{" + ",".join(items) + "}" +def _is_usable_group_key(value) -> bool: + """A usable group key is a non-empty string or a number. Anything else, + including an omitted group type, counts as no group key.""" + if isinstance(value, str): + return value != "" + return isinstance(value, numbers.Number) and not isinstance(value, bool) + + def _group_key_to_string(value) -> str: if isinstance(value, str): return value @@ -1465,7 +1809,18 @@ def _match_property_value( reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, ) - if key not in property_values: + override_value = _supplied_value(property_values, key, property) + if isinstance(override_value, _KnownAbsent): + # Like the flags service, resolve without parsing, compiling or + # validating a present condition value. A null value reads as omitted. + if value is None and operator not in ("is_set", "is_not_set"): + raise InconclusiveMatchError( + f"Operator {operator} has no condition value", + reason=UnresolvedFlagReason.UNSUPPORTED_DEFINITION, + ) + return operator in _KNOWN_ABSENT_MATCHING_OPERATORS + + if override_value is _NOT_SUPPLIED: raise InconclusiveMatchError( "can't match properties without a given property value", reason=UnresolvedFlagReason.MISSING_CONTEXT, @@ -1474,8 +1829,6 @@ def _match_property_value( if operator in ("is_set", "is_not_set"): return operator == "is_set" - override_value = property_values[key] - if operator in NUMERIC_OPERATORS: return _match_numeric_property(operator, value, override_value) @@ -1655,6 +2008,8 @@ def match_cohort( distinct_id=None, device_id=None, property_matching_version: int = 1, + *, + _evaluation_context=None, ) -> bool: # Cohort properties are in the form of property groups like this: # { @@ -1690,6 +2045,7 @@ def match_cohort( distinct_id, device_id=device_id, property_matching_version=property_matching_version, + _evaluation_context=_evaluation_context, ) return not matches if operator == "not_in" else matches @@ -1708,6 +2064,8 @@ def match_property_group( distinct_id=None, device_id=None, property_matching_version: int = 1, + *, + _evaluation_context=None, ) -> bool: is_and, properties = _get_property_group_values(property_group) if not properties: @@ -1727,6 +2085,7 @@ def match_property_group( distinct_id, device_id, property_matching_version, + _evaluation_context, ) if effective_match != is_and: decisive_result = effective_match @@ -1776,6 +2135,7 @@ def _match_property_group_entry( distinct_id, device_id, property_matching_version, + _evaluation_context, ): if not isinstance(prop, dict): raise RequiresServerEvaluation("Cohort property group entry must be an object") @@ -1789,6 +2149,7 @@ def _match_property_group_entry( distinct_id, device_id=device_id, property_matching_version=property_matching_version, + _evaluation_context=_evaluation_context, ) negation = False else: @@ -1801,6 +2162,7 @@ def _match_property_group_entry( distinct_id, device_id=device_id, property_matching_version=property_matching_version, + _evaluation_context=_evaluation_context, ) negation = prop.get("negation", False) return matches != bool(negation) diff --git a/posthog/test/test_client.py b/posthog/test/test_client.py index 5381af3db..46a3d594a 100644 --- a/posthog/test/test_client.py +++ b/posthog/test/test_client.py @@ -230,7 +230,7 @@ def test_duplicate_client_warning_allows_intentional_multi_client_cases( def test_message_only_info_logs_include_posthog_prefix(self): self.client.flag_cache = mock.Mock() - self.client.flag_cache.get_stale_cached_flag.return_value = FeatureFlagResult( + self.client.flag_cache._get_stale_cached_flag.return_value = FeatureFlagResult( key="flag-key", enabled=True, variant=None, payload=None, reason=None ) diff --git a/posthog/test/test_evaluate_flags.py b/posthog/test/test_evaluate_flags.py index 89a8c71f0..b10c29722 100644 --- a/posthog/test/test_evaluate_flags.py +++ b/posthog/test/test_evaluate_flags.py @@ -68,7 +68,7 @@ def test_empty_flag_keys_returns_empty_without_evaluation_work(self): self.client, "_add_local_person_and_group_properties" ) as add_local_properties, mock.patch.object( - self.client, "_person_properties_for_local_evaluation" + self.client, "_properties_for_local_evaluation" ) as local_person_properties, mock.patch.object( self.client, "_get_all_flags_and_payloads_locally" diff --git a/posthog/test/test_experiment_exposure.py b/posthog/test/test_experiment_exposure.py index 6148aa460..c3cb07e55 100644 --- a/posthog/test/test_experiment_exposure.py +++ b/posthog/test/test_experiment_exposure.py @@ -1040,7 +1040,7 @@ def test_a_stale_cached_value_sends_no_exposure(client): # value instead. That value did not come from the record, even though it is equal. cache = mock.Mock() cache._set_cached_remote_flag.side_effect = RuntimeError("cache unavailable") - cache.get_stale_cached_flag.return_value = FeatureFlagResult( + cache._get_stale_cached_flag.return_value = FeatureFlagResult( key=FLAG, enabled=True, variant="annual", payload=None, reason=None ) client.flag_cache = cache @@ -1049,7 +1049,7 @@ def test_a_stale_cached_value_sends_no_exposure(client): result = client.get_feature_flag_result(FLAG, DISTINCT_ID) assert result is not None and result.get_value() == "annual" - cache.get_stale_cached_flag.assert_called_once() + cache._get_stale_cached_flag.assert_called_once() [called] = events assert called.name == FLAG_CALLED # The stale value is not attributed to the record's rule or variant. diff --git a/posthog/test/test_feature_flags.py b/posthog/test/test_feature_flags.py index ac249134a..aa3863273 100644 --- a/posthog/test/test_feature_flags.py +++ b/posthog/test/test_feature_flags.py @@ -20,6 +20,8 @@ _UNHANDLED_OPERATOR_MESSAGE, InconclusiveMatchError, RequiresServerEvaluation, + _compute_flag_locally, + _FlagEvaluationContext, _get_definition_unresolved_reason, _pick_unresolved_reason, match_cohort, @@ -183,10 +185,12 @@ def test_numeric_group_keys_use_server_representation(self, mixed, patch_flags): @parameterized.expand([(False,), (True,)]) @mock.patch("posthog.client.flags") - def test_unsupported_group_keys_require_remote_evaluation(self, mixed, patch_flags): + def test_non_finite_number_group_keys_require_remote_evaluation( + self, mixed, patch_flags + ): self.set_group_flag(mixed, rollout=100) patch_flags.return_value = {"featureFlags": {"group-beta": "remote"}} - for group_key in (True, False, None, [], {}, float("inf"), float("nan")): + for group_key in (float("inf"), float("nan")): with self.subTest(group_key=group_key): self.assertIsNone( self.client.get_feature_flag( @@ -217,6 +221,510 @@ def test_unsupported_group_keys_require_remote_evaluation(self, mixed, patch_fla patch_flags.reset_mock() +# A usable group key is a non-empty string or a number; any other value counts as +# no group key (sdk-specs#250). +UNUSABLE_GROUP_KEYS = [ + ("empty_string", ""), + ("none", None), + ("true", True), + ("false", False), + ("list", []), + ("dict", {}), +] + + +class TestUnusableGroupKeys(unittest.TestCase): + def setUp(self): + self.client = Client(FAKE_TEST_API_KEY, send=False) + self.client.group_type_mapping = {"0": "company"} + self.group_flag = { + "id": 1, + "key": "group-beta", + "active": True, + "filters": { + "aggregation_group_type_index": 0, + "groups": [{"properties": [], "rollout_percentage": 100}], + }, + } + self.mixed_flag = { + "id": 2, + "key": "mixed-flag", + "active": True, + "filters": { + "groups": [ + { + "aggregation_group_type_index": 0, + "properties": [], + "rollout_percentage": 100, + }, + { + "properties": [ + { + "key": "email", + "value": "a@example.com", + "operator": "exact", + "type": "person", + } + ], + "rollout_percentage": 100, + }, + ] + }, + } + self.dependent_flag = { + "id": 3, + "key": "depends-on-group", + "active": True, + "filters": { + "groups": [ + { + "properties": [ + { + "key": "group-beta", + "operator": "flag_evaluates_to", + "value": False, + "type": "flag", + "dependency_chain": ["group-beta"], + } + ], + "rollout_percentage": 100, + } + ] + }, + } + self.client.feature_flags = [ + self.group_flag, + self.mixed_flag, + self.dependent_flag, + ] + + def tearDown(self): + self.client.shutdown() + + @parameterized.expand(UNUSABLE_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_group_flag_is_false_without_remote_evaluation( + self, _name, group_key, patch_flags + ): + patch_flags.return_value = {"featureFlags": {"group-beta": "remote"}} + groups = {"company": group_key} + group_properties = {"company": {"plan": "enterprise"}} + # Resolves the mixed flag's person condition, so the bulk calls need no + # server fallback for other flags. + person_properties = {"email": "b@example.com"} + for only_evaluate_locally in (True, False): + with self.subTest(only_evaluate_locally=only_evaluate_locally): + self.assertIs( + self.client.get_feature_flag( + "group-beta", + "user-1", + groups=groups, + group_properties=group_properties, + only_evaluate_locally=only_evaluate_locally, + send_feature_flag_events=False, + ), + False, + ) + flags = self.client.evaluate_flags( + "user-1", + groups=groups, + person_properties=person_properties, + group_properties=group_properties, + only_evaluate_locally=only_evaluate_locally, + ) + self.assertIs(flags.get_flag("group-beta"), False) + all_flags = self.client.get_all_flags( + "user-1", + groups=groups, + person_properties=person_properties, + group_properties=group_properties, + only_evaluate_locally=only_evaluate_locally, + ) + self.assertIs(all_flags["group-beta"], False) + patch_flags.assert_not_called() + + @parameterized.expand(UNUSABLE_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_mixed_flag_skips_group_condition(self, _name, group_key, patch_flags): + groups = {"company": group_key} + for email, expected in (("a@example.com", True), ("b@example.com", False)): + with self.subTest(email=email): + self.assertIs( + self.client.get_feature_flag( + "mixed-flag", + "user-1", + groups=groups, + person_properties={"email": email}, + group_properties={"company": {}}, + send_feature_flag_events=False, + ), + expected, + ) + flags = self.client.evaluate_flags( + "user-1", + groups=groups, + person_properties={"email": email}, + group_properties={"company": {}}, + ) + self.assertIs(flags.get_flag("mixed-flag"), expected) + patch_flags.assert_not_called() + + @parameterized.expand(UNUSABLE_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_group_dependency_is_false(self, _name, group_key, patch_flags): + self.assertIs( + self.client.get_feature_flag( + "depends-on-group", + "user-1", + groups={"company": group_key}, + group_properties={"company": {}}, + send_feature_flag_events=False, + ), + True, + ) + patch_flags.assert_not_called() + + @parameterized.expand(UNUSABLE_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_compute_flag_locally_returns_false(self, _name, group_key, patch_flags): + context = _FlagEvaluationContext( + distinct_id="user-1", + groups={"company": group_key}, + person_properties={"email": "b@example.com"}, + group_properties={"company": {}}, + group_type_mapping={"0": "company"}, + device_id=None, + ) + flags_by_key = {flag["key"]: flag for flag in self.client.feature_flags} + for flag in (self.group_flag, self.mixed_flag): + with self.subTest(flag=flag["key"]): + self.assertIs( + _compute_flag_locally( + flag, + context, + cohort_properties={}, + flags_by_key=flags_by_key, + property_matching_version=1, + evaluation_cache={}, + warn_on_unknown_groups=False, + ), + False, + ) + patch_flags.assert_not_called() + + @parameterized.expand(UNUSABLE_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_capture_with_feature_flags_does_not_raise( + self, _name, group_key, patch_flags + ): + with mock.patch.object(self.client, "_enqueue") as enqueue: + self.client.capture( + "event", + distinct_id="user-1", + groups={"company": group_key}, + send_feature_flags={"only_evaluate_locally": True}, + ) + properties = enqueue.call_args.kwargs["flag_properties"] + self.assertIs(properties["$feature/group-beta"], False) + self.assertIs(properties["$feature/depends-on-group"], True) + patch_flags.assert_not_called() + + @mock.patch("posthog.client.flags") + def test_usable_group_keys_still_evaluate(self, patch_flags): + patch_flags.return_value = {"featureFlags": {"group-beta": "remote"}} + for group_key in ("acme", 42, 0): + with self.subTest(group_key=group_key): + self.assertIs( + self.client.get_feature_flag( + "group-beta", + "user-1", + groups={"company": group_key}, + group_properties={"company": {}}, + send_feature_flag_events=False, + ), + True, + ) + patch_flags.assert_not_called() + # A usable key without the group properties the flag needs is still + # inconclusive and falls back to the server. + group_with_property = { + **self.group_flag, + "filters": { + "aggregation_group_type_index": 0, + "groups": [ + { + "properties": [ + { + "key": "plan", + "value": "enterprise", + "operator": "exact", + "type": "group", + "group_type_index": 0, + } + ], + "rollout_percentage": 100, + } + ], + }, + } + self.client.feature_flags = [group_with_property] + self.assertEqual( + self.client.get_feature_flag( + "group-beta", + "user-1", + groups={"company": "acme"}, + group_properties={"company": {"name": "Acme"}}, + send_feature_flag_events=False, + ), + "remote", + ) + patch_flags.assert_called_once() + + +def _plan_is_pro_condition(**condition): + return { + "properties": [ + {"key": "plan", "value": "pro", "operator": "exact", "type": "person"} + ], + "rollout_percentage": 100, + **condition, + } + + +def _company_flag(key, conditions, **filters): + return { + "id": 1, + "key": key, + "active": True, + "filters": {"aggregation_group_type_index": 0, "groups": conditions, **filters}, + } + + +# Each condition uses its own aggregation, falling back to the flag-level one, and +# only a condition aggregated by a group without a usable key is skipped (sdk-specs#250). +class TestGroupConditionsWithoutGroupKey(unittest.TestCase): + MISSING_GROUP_KEYS = [("omitted", None), ("empty_string", {"company": ""})] + + def setUp(self): + self.client = Client(FAKE_TEST_API_KEY, send=False) + self.client.group_type_mapping = {"0": "company"} + self.client.feature_flags = [ + _company_flag( + "person-condition", + [_plan_is_pro_condition(aggregation_group_type_index=None)], + ), + _company_flag( + "group-then-person", + [ + {"properties": [], "rollout_percentage": 100}, + _plan_is_pro_condition(aggregation_group_type_index=None), + ], + ), + _company_flag( + "group-only", [{"properties": [], "rollout_percentage": 100}] + ), + { + "id": 2, + "key": "depends-on-person-condition", + "active": True, + "filters": { + "groups": [ + { + "properties": [ + { + "key": "person-condition", + "operator": "flag_evaluates_to", + "value": True, + "type": "flag", + "dependency_chain": ["person-condition"], + } + ], + "rollout_percentage": 100, + } + ] + }, + }, + ] + + def tearDown(self): + self.client.shutdown() + + def evaluate(self, key, groups, plan): + kwargs = {"groups": groups} if groups is not None else {} + value = self.client.get_feature_flag( + key, + "user-1", + person_properties={"plan": plan}, + send_feature_flag_events=False, + **kwargs, + ) + flags = self.client.evaluate_flags( + "user-1", person_properties={"plan": plan}, **kwargs + ) + self.assertIs(flags.get_flag(key), value) + self.assertEqual(dict(flags.unresolved_flags), {}) + return value + + @parameterized.expand(MISSING_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_person_condition_of_group_flag_still_runs( + self, _name, groups, patch_flags + ): + for key in ("person-condition", "group-then-person"): + with self.subTest(key=key): + self.assertIs(self.evaluate(key, groups, "pro"), True) + self.assertIs(self.evaluate(key, groups, "free"), False) + patch_flags.assert_not_called() + + @parameterized.expand(MISSING_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_dependency_on_person_condition_of_group_flag( + self, _name, groups, patch_flags + ): + key = "depends-on-person-condition" + self.assertIs(self.evaluate(key, groups, "pro"), True) + self.assertIs(self.evaluate(key, groups, "free"), False) + patch_flags.assert_not_called() + + @parameterized.expand(MISSING_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_group_only_flag_is_false(self, _name, groups, patch_flags): + self.assertIs(self.evaluate("group-only", groups, "pro"), False) + patch_flags.assert_not_called() + + @parameterized.expand([*MISSING_GROUP_KEYS, ("usable", {"company": "acme"})]) + @mock.patch("posthog.client.flags") + def test_person_condition_buckets_on_distinct_id(self, _name, groups, patch_flags): + self.client.feature_flags = [ + _company_flag( + "person-rollout", + [ + { + "aggregation_group_type_index": None, + "properties": [], + "rollout_percentage": 50, + } + ], + ) + ] + kwargs = {"groups": groups} if groups is not None else {} + # "user-0" hashes below 50% for this flag, "user-1" above it. The empty + # and "acme" group keys both hash above it. + for distinct_id, expected in (("user-0", True), ("user-1", False)): + with self.subTest(distinct_id=distinct_id): + self.assertIs( + self.client.get_feature_flag( + "person-rollout", + distinct_id, + group_properties={"company": {}}, + send_feature_flag_events=False, + **kwargs, + ), + expected, + ) + patch_flags.assert_not_called() + + @mock.patch("posthog.client.flags") + def test_person_condition_reads_person_properties_with_group_key(self, patch_flags): + for plan, expected in (("pro", True), ("free", False)): + with self.subTest(plan=plan): + self.assertIs( + self.client.get_feature_flag( + "person-condition", + "user-1", + groups={"company": "acme"}, + person_properties={"plan": plan}, + group_properties={"company": {"plan": "enterprise"}}, + send_feature_flag_events=False, + ), + expected, + ) + patch_flags.assert_not_called() + + +class TestGroupFlagHoldoutWithoutGroupKey(unittest.TestCase): + def setUp(self): + self.client = Client(FAKE_TEST_API_KEY, send=False) + self.client.group_type_mapping = {"0": "company"} + + def tearDown(self): + self.client.shutdown() + + def set_holdout_flag(self, exclusion_percentage): + self.client.feature_flags = [ + _company_flag( + "held-out", + [{"properties": [], "rollout_percentage": 100}], + holdout={"id": 727, "exclusion_percentage": exclusion_percentage}, + ) + ] + + @parameterized.expand(TestGroupConditionsWithoutGroupKey.MISSING_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_holdout_without_group_key_is_missing_context( + self, _name, groups, patch_flags + ): + self.set_holdout_flag(50) + kwargs = {"groups": groups} if groups is not None else {} + patch_flags.return_value = {"featureFlags": {"held-out": "remote"}} + + self.assertIsNone( + self.client.get_feature_flag( + "held-out", + "user-1", + only_evaluate_locally=True, + send_feature_flag_events=False, + **kwargs, + ) + ) + flags = self.client.evaluate_flags( + "user-1", only_evaluate_locally=True, **kwargs + ) + self.assertEqual( + dict(flags.unresolved_flags), + {"held-out": UnresolvedFlagReason.MISSING_CONTEXT}, + ) + patch_flags.assert_not_called() + + self.assertEqual( + self.client.get_feature_flag( + "held-out", "user-1", send_feature_flag_events=False, **kwargs + ), + "remote", + ) + patch_flags.assert_called_once() + + @mock.patch("posthog.client.flags") + def test_holdout_with_group_key_is_evaluated_locally(self, patch_flags): + self.set_holdout_flag(100) + self.assertEqual( + self.client.get_feature_flag( + "held-out", + "user-1", + groups={"company": "acme"}, + group_properties={"company": {}}, + send_feature_flag_events=False, + ), + "holdout-727", + ) + patch_flags.assert_not_called() + + @parameterized.expand(TestGroupConditionsWithoutGroupKey.MISSING_GROUP_KEYS) + @mock.patch("posthog.client.flags") + def test_zero_percent_holdout_without_group_key_is_false( + self, _name, groups, patch_flags + ): + self.set_holdout_flag(0) + kwargs = {"groups": groups} if groups is not None else {} + self.assertIs( + self.client.get_feature_flag( + "held-out", "user-1", send_feature_flag_events=False, **kwargs + ), + False, + ) + patch_flags.assert_not_called() + + class TestNumericOrderingLocalEvaluation(unittest.TestCase): def setUp(self): self.client = Client(FAKE_TEST_API_KEY) diff --git a/posthog/test/test_feature_flags_known_absent.py b/posthog/test/test_feature_flags_known_absent.py new file mode 100644 index 000000000..2a4cc1246 --- /dev/null +++ b/posthog/test/test_feature_flags_known_absent.py @@ -0,0 +1,1374 @@ +"""Known-absent property keys in local evaluation and the /flags request body.""" + +import itertools +import json +import time +import unittest +from unittest import mock + +import pytest +from parameterized import parameterized + +from posthog import AsyncPosthog +from posthog.client import Client +from posthog.request import GetResponse, RequestsTimeout +from posthog.feature_flags import ( + InconclusiveMatchError, + _mark_known_absent_properties, + match_cohort, +) +from posthog.test.test_utils import FAKE_TEST_API_KEY, FakeRedis +from posthog.types import UnresolvedFlagReason +from posthog.utils import RedisFlagCache + +pytestmark = [ + pytest.mark.filterwarnings( + r"ignore:`(feature_enabled|get_feature_flag|get_feature_flag_payload)` is deprecated:DeprecationWarning" + ), + pytest.mark.filterwarnings( + r"ignore:`send_feature_flags` is deprecated:DeprecationWarning" + ), +] + +REMOTE_VALUE = "remote-value" + + +def _flag(key, properties, **filters): + return { + "id": 1, + "key": key, + "active": True, + "filters": { + "groups": [{"properties": properties, "rollout_percentage": 100}], + **filters, + }, + } + + +def _person_filter(operator, value=None, key="plan"): + prop = {"key": key, "operator": operator, "type": "person"} + if value is not None: + prop["value"] = value + return prop + + +def _person_metadata_filter(operator, value=None, key="created_at"): + return {**_person_filter(operator, value, key=key), "type": "person_metadata"} + + +def _group_filter(operator, value=None, key="tier", group_type_index=0): + return { + **_person_filter(operator, value, key=key), + "type": "group", + "group_type_index": group_type_index, + } + + +def _group_filter_without_index(operator, value=None, key="tier", null_index=False): + prop = _group_filter(operator, value, key=key) + if null_index: + prop["group_type_index"] = None + else: + del prop["group_type_index"] + return prop + + +def _depends_on(key, value=True): + return { + "key": key, + "operator": "flag_evaluates_to", + "value": value, + "type": "flag", + "dependency_chain": [key], + } + + +class TestKnownAbsentLocalEvaluation(unittest.TestCase): + def setUp(self): + self.client = Client(FAKE_TEST_API_KEY, secret_key="test") + self.client.capture = mock.Mock() + self.client.group_type_mapping = {"0": "organization", "1": "project"} + flags_patch = mock.patch("posthog.client.flags") + self.flags = flags_patch.start() + self.addCleanup(flags_patch.stop) + self.flags.return_value = { + "featureFlags": {"flag": REMOTE_VALUE, "beta-feature": REMOTE_VALUE} + } + + def evaluate(self, flag, **kwargs): + self.client.feature_flags = [flag] + return self.client.get_feature_flag(flag["key"], "user-1", **kwargs) + + def assert_local(self, flag, expected, **kwargs): + self.assertEqual(self.evaluate(flag, **kwargs), expected) + self.flags.assert_not_called() + + def assert_remote(self, flag, **kwargs): + self.assertEqual(self.evaluate(flag, **kwargs), REMOTE_VALUE) + self.assertEqual(self.flags.call_count, 1) + + def assert_unresolved_locally(self, flag): + self.client.feature_flags = [flag] + snapshot = self.client.evaluate_flags( + "user-1", + person_property_keys_known_absent=["plan"], + only_evaluate_locally=True, + ) + self.assertIsNone(snapshot.get_flag("flag")) + self.assertEqual( + snapshot.unresolved_flags, + {"flag": UnresolvedFlagReason.UNSUPPORTED_DEFINITION}, + ) + self.flags.assert_not_called() + + @parameterized.expand( + [ + ("is_not_set", None, True), + ("is_set", None, False), + ("exact", "pro", False), + ("exact", ["pro", "free"], False), + ("is_not", "pro", True), + ("icontains", "pro", False), + ("not_icontains", "pro", True), + ("starts_with", "pro", False), + ("not_starts_with", "pro", True), + ("ends_with", "pro", False), + ("not_ends_with", "pro", True), + ("regex", "^pro", False), + ("not_regex", "^pro", True), + ("gt", "10", False), + ("gte", "10", False), + ("lt", "10", False), + ("lte", "10", False), + ("is_date_before", "2025-01-01T10:00:00Z", False), + ("is_date_after", "2025-01-01T10:00:00Z", False), + ("semver_eq", "1.2.3", False), + ("semver_neq", "1.2.3", False), + ("semver_gt", "1.2.3", False), + ("semver_tilde", "1.2.3", False), + ] + ) + def test_listed_key_resolves_operator_locally(self, operator, value, expected): + flag = _flag("flag", [_person_filter(operator, value)]) + self.assert_local(flag, expected, person_property_keys_known_absent=["plan"]) + + def test_listed_key_overrides_a_supplied_value(self): + flag = _flag("flag", [_person_filter("is_not_set")]) + self.assert_local( + flag, + True, + person_properties={"plan": "pro"}, + person_property_keys_known_absent=["plan"], + ) + + def test_listed_key_overrides_the_sdk_added_distinct_id(self): + flag = _flag("flag", [_person_filter("is_not_set", key="distinct_id")]) + self.assert_local(flag, True, person_property_keys_known_absent=["distinct_id"]) + + def test_omitted_key_that_is_not_listed_stays_inconclusive(self): + flag = _flag("flag", [_person_filter("is_not_set")]) + self.assert_remote(flag, person_property_keys_known_absent=["region"]) + body = self.flags.call_args.kwargs + self.assertEqual(body["person_property_keys_known_absent"], ["region"]) + + def test_person_metadata_key_is_ignored(self): + flag = _flag( + "flag", + [_person_filter("is_set", key="__posthog_person_metadata__created_at")], + ) + self.assert_local( + flag, + True, + person_properties={"__posthog_person_metadata__created_at": "2024"}, + person_property_keys_known_absent=["__posthog_person_metadata__created_at"], + ) + + @parameterized.expand( + [ + ("icontains_multi", ["pro"]), + ("not_icontains_multi", ["pro"]), + ("between", [1, 2]), + ("not_between", [1, 2]), + ("some_future_operator", "pro"), + ] + ) + def test_unimplemented_operator_on_listed_key_still_falls_back( + self, operator, value + ): + flag = _flag("flag", [_person_filter(operator, value)]) + self.assert_unresolved_locally(flag) + self.assert_remote(flag, person_property_keys_known_absent=["plan"]) + + @parameterized.expand( + [ + ("not_regex invalid", "not_regex", "[", True), + ("regex invalid", "regex", "[", False), + ("not_regex non-portable", "not_regex", r"\p{L}", True), + ("regex non-portable", "regex", r"\p{L}", False), + ("not_regex inline flag", "not_regex", "(?i)enterprise", True), + ("regex inline flag", "regex", "(?i)enterprise", False), + ("not_regex word boundary", "not_regex", r"\bpro\b", True), + ("gt", "gt", "not-a-number", False), + ("gte", "gte", "not-a-number", False), + ("lt", "lt", "not-a-number", False), + ("lte", "lte", "not-a-number", False), + ("semver_eq", "semver_eq", "not-a-version", False), + ("semver_neq", "semver_neq", "not-a-version", False), + ("semver_gt", "semver_gt", "not-a-version", False), + ("semver_tilde", "semver_tilde", "not-a-version", False), + ("semver_caret", "semver_caret", "not-a-version", False), + ("semver_wildcard", "semver_wildcard", "not-a-version", False), + ("is_date_before", "is_date_before", "not-a-date", False), + ("is_date_after", "is_date_after", "not-a-date", False), + ] + ) + def test_listed_key_resolves_without_reading_the_condition_value( + self, _name, operator, value, expected + ): + flag = _flag("flag", [_person_filter(operator, value)]) + self.client.feature_flags = [flag] + snapshot = self.client.evaluate_flags( + "user-1", + person_property_keys_known_absent=["plan"], + only_evaluate_locally=True, + ) + self.assertIs(snapshot.get_flag("flag"), expected) + self.assertEqual(snapshot.unresolved_flags, {}) + + self.assert_local(flag, expected, person_property_keys_known_absent=["plan"]) + + @parameterized.expand( + [ + ("is_not omitted", "is_not", False), + ("is_not null", "is_not", True), + ("exact null", "exact", True), + ("gt null", "gt", True), + ("not_regex omitted", "not_regex", False), + ("regex null", "regex", True), + ("semver_gt null", "semver_gt", True), + ("is_date_after omitted", "is_date_after", False), + ] + ) + def test_listed_key_with_omitted_or_null_value_stays_inconclusive( + self, _name, operator, explicit_null + ): + prop = _person_filter(operator) + if explicit_null: + prop["value"] = None + flag = _flag("flag", [prop]) + self.assert_unresolved_locally(flag) + self.assert_remote(flag, person_property_keys_known_absent=["plan"]) + + @parameterized.expand([("is_not_set", True), ("is_set", False)]) + def test_listed_key_with_null_value_resolves_presence_operator( + self, operator, expected + ): + prop = {**_person_filter(operator), "value": None} + flag = _flag("flag", [prop]) + self.assert_local(flag, expected, person_property_keys_known_absent=["plan"]) + + @parameterized.expand( + [ + ("is_not_set", None), + ("is_set", None), + ("is_date_before", "2024-01-01T00:00:00Z"), + ("is_date_after", "2024-01-01T00:00:00Z"), + ] + ) + def test_listed_key_does_not_resolve_a_person_metadata_filter( + self, operator, value + ): + flag = _flag( + "flag", [_person_metadata_filter(operator, value, key="created_at")] + ) + self.assert_remote(flag, person_property_keys_known_absent=["created_at"]) + + @parameterized.expand( + [ + ("is_not_set", None, False), + ("is_set", None, True), + ("is_date_before", "2024-01-01T00:00:00Z", True), + ("is_date_after", "2024-01-01T00:00:00Z", False), + ] + ) + def test_person_metadata_filter_on_listed_key_reads_the_supplied_value( + self, operator, value, expected + ): + flag = _flag( + "flag", [_person_metadata_filter(operator, value, key="created_at")] + ) + self.assert_local( + flag, + expected, + person_properties={"created_at": "2020-01-01T00:00:00Z"}, + person_property_keys_known_absent=["created_at"], + ) + + def test_duplicate_person_key_still_reads_the_supplied_value_outside_its_scope( + self, + ): + flag = _flag( + "flag", [_person_metadata_filter("is_set", None, key="created_at")] + ) + self.assert_local( + flag, + True, + person_properties={"created_at": "2020-01-01T00:00:00Z"}, + person_property_keys_known_absent=["created_at", "created_at"], + ) + + def test_duplicate_group_key_still_reads_the_supplied_value_outside_its_scope( + self, + ): + flag = _flag( + "flag", + [_group_filter("is_set", key="tier", group_type_index=1)], + aggregation_group_type_index=0, + ) + self.assert_local( + flag, + True, + groups={"organization": "org-1"}, + group_properties={"organization": {"tier": "gold"}}, + group_property_keys_known_absent={"organization": ["tier", "tier"]}, + ) + + @parameterized.expand( + [ + ("is_not_set", None), + ("is_date_before", "2024-01-01T00:00:00Z"), + ("is_date_after", "2024-01-01T00:00:00Z"), + ] + ) + def test_listed_key_does_not_resolve_a_person_metadata_cohort_leaf( + self, operator, value + ): + self.client.cohorts = { + "5": { + "type": "AND", + "values": [_person_metadata_filter(operator, value, key="created_at")], + } + } + flag = _flag("flag", [{"key": "id", "value": 5, "type": "cohort"}]) + self.assert_remote(flag, person_property_keys_known_absent=["created_at"]) + + def test_person_keys_do_not_resolve_a_group_filter_in_a_person_flag(self): + flag = _flag("flag", [_group_filter("is_not_set", key="tier")]) + self.assert_remote(flag, person_property_keys_known_absent=["tier"]) + + def test_group_keys_do_not_resolve_a_person_filter_in_a_group_flag(self): + flag = _flag( + "flag", [_person_filter("is_not_set")], aggregation_group_type_index=0 + ) + self.assert_remote( + flag, + groups={"organization": "org-1"}, + group_property_keys_known_absent={"organization": ["plan"]}, + ) + + def test_group_keys_do_not_resolve_a_person_cohort_leaf_in_a_group_flag(self): + self.client.cohorts = { + "5": {"type": "AND", "values": [_person_filter("is_not_set")]} + } + flag = _flag( + "flag", + [{"key": "id", "value": 5, "type": "cohort"}], + aggregation_group_type_index=0, + ) + self.assert_remote( + flag, + groups={"organization": "org-1"}, + group_property_keys_known_absent={"organization": ["plan"]}, + ) + + def test_group_keys_do_not_resolve_a_filter_for_another_group_type(self): + flag = _flag( + "flag", + [_group_filter("is_not_set", key="tier", group_type_index=1)], + aggregation_group_type_index=0, + ) + self.assert_remote( + flag, + groups={"organization": "org-1"}, + group_property_keys_known_absent={"organization": ["tier"]}, + ) + + def test_group_key_applies_only_to_its_group_type(self): + flag = _flag( + "flag", + [_group_filter("is_not_set", key="tier")], + aggregation_group_type_index=0, + ) + groups = {"organization": "org-1", "project": "proj-1"} + self.assert_remote( + flag, + groups=groups, + group_property_keys_known_absent={"project": ["tier"]}, + ) + self.assertEqual( + self.flags.call_args.kwargs["group_property_keys_known_absent"], + {"project": ["tier"]}, + ) + + self.flags.reset_mock() + self.assert_local( + flag, + True, + groups=groups, + group_properties={"organization": {"tier": "gold"}}, + group_property_keys_known_absent={"organization": ["tier"]}, + ) + + @parameterized.expand( + [ + ("exact", "enterprise", "tier", False, False), + ("is_not_set", None, "tier", False, True), + ("is_not_set", None, "tier", True, True), + ("is_set", None, "$group_key", False, False), + ("is_set", None, "$group_key", True, False), + ] + ) + def test_group_filter_without_index_reads_the_condition_group_type( + self, operator, value, key, null_index, expected + ): + flag = _flag( + "flag", + [_group_filter_without_index(operator, value, key, null_index)], + aggregation_group_type_index=0, + ) + self.assert_local( + flag, + expected, + groups={"organization": "acme"}, + group_properties={"organization": {"tier": "enterprise"}}, + group_property_keys_known_absent={"organization": [key]}, + ) + + def test_group_filter_without_index_reads_the_condition_level_group_type(self): + flag = { + "id": 1, + "key": "flag", + "active": True, + "filters": { + "aggregation_group_type_index": None, + "groups": [ + { + "properties": [_group_filter_without_index("is_not_set")], + "rollout_percentage": 100, + "aggregation_group_type_index": 0, + } + ], + }, + } + self.assert_local( + flag, + True, + groups={"organization": "acme"}, + group_properties={"organization": {"tier": "enterprise"}}, + group_property_keys_known_absent={"organization": ["tier"]}, + ) + + def test_group_filter_without_index_ignores_keys_of_another_group_type(self): + flag = _flag( + "flag", + [_group_filter_without_index("is_not_set")], + aggregation_group_type_index=0, + ) + self.assert_local( + flag, + False, + groups={"organization": "acme", "project": "proj-1"}, + group_properties={"organization": {"tier": "enterprise"}}, + group_property_keys_known_absent={"project": ["tier"]}, + ) + + @parameterized.expand( + [ + ("omitted_index", None, False), + ("null_index", None, True), + ("same_index", 0, None), + ] + ) + def test_group_cohort_leaf_reads_the_condition_group_type( + self, _name, group_type_index, null_index + ): + leaf = ( + _group_filter("exact", "enterprise", group_type_index=group_type_index) + if group_type_index is not None + else _group_filter_without_index("exact", "enterprise", "tier", null_index) + ) + self.client.cohorts = {"5": {"type": "AND", "values": [leaf]}} + flag = _flag( + "flag", + [{"key": "id", "value": 5, "type": "cohort"}], + aggregation_group_type_index=0, + ) + self.assert_local( + flag, + False, + groups={"organization": "acme"}, + group_properties={"organization": {"tier": "enterprise"}}, + group_property_keys_known_absent={"organization": ["tier"]}, + ) + + def test_group_cohort_leaf_with_another_index_ignores_the_condition_keys(self): + self.client.cohorts = { + "5": { + "type": "AND", + "values": [_group_filter("exact", "enterprise", group_type_index=1)], + } + } + flag = _flag( + "flag", + [{"key": "id", "value": 5, "type": "cohort"}], + aggregation_group_type_index=0, + ) + self.assert_local( + flag, + True, + groups={"organization": "acme"}, + group_properties={"organization": {"tier": "enterprise"}}, + group_property_keys_known_absent={"organization": ["tier"]}, + ) + + def test_group_key_overrides_the_sdk_added_group_key(self): + flag = _flag( + "flag", + [_group_filter("is_set", key="$group_key")], + aggregation_group_type_index=0, + ) + self.assert_local( + flag, + False, + groups={"organization": "org-1"}, + group_property_keys_known_absent={"organization": ["$group_key"]}, + ) + + def test_person_keys_do_not_apply_to_group_properties(self): + flag = _flag( + "flag", + [_group_filter("is_not_set", key="tier")], + aggregation_group_type_index=0, + ) + self.assert_remote( + flag, + groups={"organization": "org-1"}, + person_property_keys_known_absent=["tier"], + ) + + @parameterized.expand([(False, True), (True, False)]) + def test_cohort_leaf_uses_known_absence_before_negation(self, negation, expected): + self.client.cohorts = { + "5": { + "type": "AND", + "values": [ + { + "key": "plan", + "operator": "is_not_set", + "type": "person", + "negation": negation, + } + ], + } + } + flag = _flag("flag", [{"key": "id", "value": 5, "type": "cohort"}]) + self.assert_local(flag, expected, person_property_keys_known_absent=["plan"]) + + @parameterized.expand([(False,), (True,)]) + def test_cohort_leaf_unsupported_operator_falls_back_before_known_absence( + self, negation + ): + cohort = { + "type": "AND", + "values": [ + { + "key": "plan", + "operator": "not_between", + "value": [1, 2], + "type": "person", + "negation": negation, + } + ], + } + cohort_filter = {"key": "id", "value": 5, "type": "cohort"} + listed_person_properties, _ = _mark_known_absent_properties( + {}, {}, ["plan"], None, None + ) + with self.assertRaises(InconclusiveMatchError) as ctx: + match_cohort(cohort_filter, listed_person_properties, {"5": cohort}) + self.assertEqual( + ctx.exception.reason, UnresolvedFlagReason.UNSUPPORTED_DEFINITION + ) + + self.client.cohorts = {"5": cohort} + flag = _flag("flag", [cohort_filter]) + self.assert_remote(flag, person_property_keys_known_absent=["plan"]) + + def test_flag_dependency_uses_the_same_listing(self): + dependency = _flag("dependency", [_person_filter("is_not_set")]) + dependency["id"] = 2 + dependent = _flag( + "flag", + [ + { + "key": "dependency", + "operator": "flag_evaluates_to", + "value": True, + "type": "flag", + "dependency_chain": ["dependency"], + } + ], + ) + self.client.feature_flags = [dependency, dependent] + value = self.client.get_feature_flag( + "flag", "user-1", person_property_keys_known_absent=["plan"] + ) + self.assertIs(value, True) + self.flags.assert_not_called() + + @parameterized.expand( + [ + ( + "group dependency of a person flag", + None, + [_group_filter("is_not_set", key="tier")], + 0, + {"person_property_keys_known_absent": ["tier"]}, + ), + ( + "person dependency of a group flag", + 0, + [_person_filter("is_not_set")], + None, + {"group_property_keys_known_absent": {"organization": ["plan"]}}, + ), + ( + "dependency on another group type", + 0, + [_group_filter("is_not_set", key="tier", group_type_index=1)], + 1, + {"group_property_keys_known_absent": {"organization": ["tier"]}}, + ), + ] + ) + def test_flag_dependency_does_not_read_keys_of_another_aggregation( + self, + _name, + parent_aggregation, + dependency_properties, + dependency_aggregation, + listing, + ): + dependency = _flag( + "dependency", + dependency_properties, + aggregation_group_type_index=dependency_aggregation, + ) + dependency["id"] = 2 + dependent = _flag( + "flag", + [ + { + "key": "dependency", + "operator": "flag_evaluates_to", + "value": True, + "type": "flag", + "dependency_chain": ["dependency"], + } + ], + aggregation_group_type_index=parent_aggregation, + ) + self.client.feature_flags = [dependency, dependent] + value = self.client.get_feature_flag( + "flag", + "user-1", + groups={"organization": "org-1", "project": "proj-1"}, + **listing, + ) + self.assertEqual(value, REMOTE_VALUE) + self.assertEqual(self.flags.call_count, 1) + + def evaluate_dependency_pair(self, parent, child, **kwargs): + """Evaluate the parent directly and through the child's dependency, with + the same inputs, in each local entry point.""" + self.client.feature_flags = [parent, child] + direct = self.client.get_feature_flag(parent["key"], "user-1", **kwargs) + through_dependency = self.client.get_feature_flag( + child["key"], "user-1", **kwargs + ) + snapshot = self.client.evaluate_flags( + "user-1", only_evaluate_locally=True, **kwargs + ) + self.assertEqual(snapshot.get_flag(child["key"]), through_dependency) + self.assertEqual(snapshot.unresolved_flags, {}) + self.flags.assert_not_called() + return direct, through_dependency + + def test_dependency_is_evaluated_with_its_own_aggregation(self): + parent = _flag( + "org-parent", + [_group_filter("exact", "us", key="region")], + aggregation_group_type_index=0, + ) + child = _flag("person-child", [_depends_on("org-parent")]) + child["id"] = 2 + + direct, through_dependency = self.evaluate_dependency_pair( + parent, + child, + groups={"organization": "acme"}, + person_properties={"region": "us"}, + group_properties={"organization": {"region": "eu"}}, + ) + self.assertIs(direct, False) + self.assertIs(through_dependency, False) + + direct, through_dependency = self.evaluate_dependency_pair( + parent, + child, + groups={"organization": "acme"}, + person_properties={"region": "eu"}, + group_properties={"organization": {"region": "us"}}, + ) + self.assertIs(direct, True) + self.assertIs(through_dependency, True) + + def test_group_dependency_without_its_group_resolves_as_false(self): + parent = _flag( + "org-parent", + [_group_filter("is_not_set")], + aggregation_group_type_index=0, + ) + child = _flag("person-child", [_depends_on("org-parent")]) + child["id"] = 2 + + direct, through_dependency = self.evaluate_dependency_pair( + parent, + child, + group_property_keys_known_absent={"organization": ["tier"]}, + ) + self.assertIs(direct, False) + self.assertIs(through_dependency, False) + + def test_group_dependency_is_bucketed_by_the_group_key(self): + # "user-1" hashes into the 50% rollout of "org-parent", "org-0" does not + # and "org-1" does. + parent = { + "id": 1, + "key": "org-parent", + "active": True, + "filters": { + "aggregation_group_type_index": 0, + "groups": [{"properties": [], "rollout_percentage": 50}], + }, + } + child = _flag("person-child", [_depends_on("org-parent")]) + child["id"] = 2 + + for group_key, expected in (("org-0", False), ("org-1", True)): + direct, through_dependency = self.evaluate_dependency_pair( + parent, child, groups={"organization": group_key} + ) + self.assertIs(direct, expected) + self.assertIs(through_dependency, expected) + + def test_person_dependency_of_a_group_flag_reads_person_context(self): + # "user-1" hashes into the 50% rollout of "person-parent", "org-0" does not. + parent = _flag("person-parent", [_person_filter("exact", "us", key="region")]) + parent["filters"]["groups"][0]["rollout_percentage"] = 50 + child = _flag( + "org-child", + [_depends_on("person-parent")], + aggregation_group_type_index=0, + ) + child["id"] = 2 + + direct, through_dependency = self.evaluate_dependency_pair( + parent, + child, + groups={"organization": "org-0"}, + person_properties={"region": "us"}, + group_properties={"organization": {"region": "eu"}}, + ) + self.assertIs(direct, True) + self.assertIs(through_dependency, True) + + def test_listed_enrollment_key_continues_to_release_conditions(self): + flag = _flag("beta-feature", [], feature_enrollment=True) + self.assert_local( + flag, + True, + person_properties={"$feature_enrollment/beta-feature": True}, + person_property_keys_known_absent=["$feature_enrollment/beta-feature"], + ) + + def test_listed_enrollment_key_continues_to_holdouts(self): + flag = _flag( + "beta-feature", + [], + feature_enrollment=True, + holdout={"id": 1, "exclusion_percentage": 100}, + ) + self.assert_local( + flag, + "holdout-1", + person_property_keys_known_absent=["$feature_enrollment/beta-feature"], + ) + + def test_listed_enrollment_key_still_reports_unsupported_group_enrollment(self): + flag = _flag( + "beta-feature", + [], + feature_enrollment=True, + aggregation_group_type_index=0, + ) + self.assert_remote( + flag, + groups={"organization": "org-1"}, + person_property_keys_known_absent=["$feature_enrollment/beta-feature"], + ) + + def test_evaluate_flags_and_all_flags_honor_listing(self): + self.client.feature_flags = [_flag("flag", [_person_filter("is_not_set")])] + snapshot = self.client.evaluate_flags( + "user-1", + person_properties={"plan": "pro"}, + person_property_keys_known_absent=["plan"], + only_evaluate_locally=True, + ) + self.assertIs(snapshot.is_enabled("flag"), True) + self.assertEqual( + self.client.get_all_flags( + "user-1", person_property_keys_known_absent=["plan"] + ), + {"flag": True}, + ) + self.flags.assert_not_called() + + +_COLD_START_DEFINITIONS = { + "flags": [ + _flag( + "org-tier-flag", + [_group_filter("is_not_set")], + aggregation_group_type_index=0, + ), + { + **_flag( + "org-key-flag", + [_group_filter("is_set", key="$group_key")], + aggregation_group_type_index=0, + ), + "id": 2, + }, + ], + "group_type_mapping": {"0": "organization"}, + "cohorts": {}, +} + + +class TestKnownAbsentColdStart(unittest.TestCase): + """A client that never called load_feature_flags() loads definitions on the + first evaluation and must mark group keys with the loaded group types.""" + + def setUp(self): + self.client = Client( + FAKE_TEST_API_KEY, + secret_key="phx_test", + send=False, + enable_local_evaluation=False, + ) + self.client.capture = mock.Mock() + get_patch = mock.patch( + "posthog.client.get", + return_value=GetResponse(data=_COLD_START_DEFINITIONS), + ) + flags_patch = mock.patch( + "posthog.client.flags", + side_effect=AssertionError("unexpected /flags call"), + ) + get_patch.start() + self.flags = flags_patch.start() + self.addCleanup(get_patch.stop) + self.addCleanup(flags_patch.stop) + self.addCleanup(self.client.shutdown) + self.assertIsNone(self.client.feature_flags) + + _kwargs = { + "groups": {"organization": "org-1"}, + "group_properties": {"organization": {"tier": "gold"}}, + "group_property_keys_known_absent": {"organization": ["tier", "$group_key"]}, + } + + def test_evaluate_flags_marks_group_keys_after_lazy_load(self): + snapshot = self.client.evaluate_flags( + "user-1", only_evaluate_locally=True, **self._kwargs + ) + self.assertIs(snapshot.get_flag("org-tier-flag"), True) + self.assertIs(snapshot.get_flag("org-key-flag"), False) + self.assertEqual(snapshot.unresolved_flags, {}) + + def test_get_feature_flag_marks_group_keys_after_lazy_load(self): + self.assertIs( + self.client.get_feature_flag("org-tier-flag", "user-1", **self._kwargs), + True, + ) + self.flags.assert_not_called() + + def test_get_all_flags_marks_group_keys_after_lazy_load(self): + self.assertEqual( + self.client.get_all_flags("user-1", **self._kwargs), + {"org-tier-flag": True, "org-key-flag": False}, + ) + self.flags.assert_not_called() + + +class TestKnownAbsentRemoteBody(unittest.TestCase): + def setUp(self): + self.client = Client(FAKE_TEST_API_KEY) + self.client.capture = mock.Mock() + flags_patch = mock.patch("posthog.client.flags") + self.flags = flags_patch.start() + self.addCleanup(flags_patch.stop) + self.flags.return_value = {"featureFlags": {"flag": True}} + + def test_fallback_sends_listed_keys(self): + self.client.get_feature_flag( + "flag", + "user-1", + groups={"organization": "org-1"}, + person_property_keys_known_absent=["plan"], + group_property_keys_known_absent={"organization": ["tier"]}, + ) + body = self.flags.call_args.kwargs + self.assertEqual(body["person_property_keys_known_absent"], ["plan"]) + self.assertEqual( + body["group_property_keys_known_absent"], {"organization": ["tier"]} + ) + + @parameterized.expand( + [ + ("not provided", {}), + ( + "empty", + { + "person_property_keys_known_absent": [], + "group_property_keys_known_absent": {"organization": []}, + }, + ), + ] + ) + def test_omits_fields_without_listed_keys(self, _name, kwargs): + self.client.get_feature_flag("flag", "user-1", **kwargs) + body = self.flags.call_args.kwargs + self.assertNotIn("person_property_keys_known_absent", body) + self.assertNotIn("group_property_keys_known_absent", body) + + def test_every_remote_entry_point_sends_listed_keys(self): + kwargs = {"person_property_keys_known_absent": ["plan"]} + calls = [ + lambda: self.client.evaluate_flags("user-1", **kwargs), + lambda: self.client.get_all_flags_and_payloads("user-1", **kwargs), + lambda: self.client.get_feature_flag_result("flag", "user-1", **kwargs), + lambda: self.client.get_feature_flag_payload("flag", "user-1", **kwargs), + lambda: self.client.feature_enabled("flag", "user-1", **kwargs), + lambda: self.client.get_feature_variants("user-1", **kwargs), + lambda: self.client.get_flags_decision("user-1", **kwargs), + ] + for call in calls: + self.flags.reset_mock() + call() + self.assertEqual( + self.flags.call_args.kwargs["person_property_keys_known_absent"], + ["plan"], + ) + + def test_send_feature_flags_options_send_listed_keys(self): + client = Client(FAKE_TEST_API_KEY, send=False) + client.capture( + "event", + distinct_id="user-1", + send_feature_flags={ + "only_evaluate_locally": False, + "person_property_keys_known_absent": ["plan"], + }, + ) + self.assertEqual( + self.flags.call_args.kwargs["person_property_keys_known_absent"], ["plan"] + ) + + @parameterized.expand( + [ + ("person", {"person_property_keys_known_absent": ["plan"] * 1001}), + ( + "group", + {"group_property_keys_known_absent": {"organization": ["t"] * 1001}}, + ), + ] + ) + def test_over_limit_raises_without_a_request(self, _name, kwargs): + for call in ( + lambda: self.client.get_feature_flag("flag", "user-1", **kwargs), + lambda: self.client.evaluate_flags("user-1", **kwargs), + lambda: self.client.get_all_flags("user-1", **kwargs), + lambda: self.client.get_flags_decision("user-1", **kwargs), + ): + with self.assertRaisesRegex(ValueError, "at most 1000 keys"): + call() + self.flags.assert_not_called() + + def test_send_feature_flags_over_limit_raises_without_a_request(self): + client = Client(FAKE_TEST_API_KEY, send=False, debug=True) + with self.assertRaisesRegex(ValueError, "at most 1000 keys"): + client.capture( + "event", + distinct_id="user-1", + send_feature_flags={ + "only_evaluate_locally": False, + "person_property_keys_known_absent": ["plan"] * 1001, + }, + ) + self.flags.assert_not_called() + + def test_send_feature_flags_over_limit_drops_event_with_default_settings(self): + client = Client(FAKE_TEST_API_KEY) + with mock.patch.object(client, "_enqueue") as enqueue: + result = client.capture( + "event", + distinct_id="user-1", + send_feature_flags={ + "only_evaluate_locally": False, + "person_property_keys_known_absent": ["plan"] * 1001, + }, + ) + self.assertIsNone(result) + enqueue.assert_not_called() + self.flags.assert_not_called() + + def test_unbounded_iterable_raises_without_a_request(self): + with self.assertRaisesRegex(ValueError, "at most 1000 keys"): + self.client.get_flags_decision( + "user-1", person_property_keys_known_absent=itertools.repeat("plan") + ) + self.flags.assert_not_called() + + def test_get_flags_decision_sends_iterator_inputs(self): + self.client.get_flags_decision( + "user-1", + groups={"organization": "org-1"}, + person_property_keys_known_absent=iter(["plan"]), + group_property_keys_known_absent={"organization": iter(["tier"])}, + ) + body = self.flags.call_args.kwargs + self.assertEqual(body["person_property_keys_known_absent"], ["plan"]) + self.assertEqual( + body["group_property_keys_known_absent"], {"organization": ["tier"]} + ) + + def test_limit_counts_duplicates_and_is_per_group_type(self): + self.client.get_feature_flag( + "flag", + "user-1", + person_property_keys_known_absent=["plan"] * 1000, + group_property_keys_known_absent={ + "organization": ["t"] * 1000, + "project": ["t"] * 1000, + }, + ) + body = self.flags.call_args.kwargs + self.assertEqual(len(body["person_property_keys_known_absent"]), 1000) + self.assertEqual(len(body["group_property_keys_known_absent"]["project"]), 1000) + + @parameterized.expand( + [ + ("string", {"person_property_keys_known_absent": "plan"}), + ("non-string key", {"person_property_keys_known_absent": [1]}), + ("group list", {"group_property_keys_known_absent": ["tier"]}), + ("non-string group type", {"group_property_keys_known_absent": {1: ["t"]}}), + ("None group keys", {"group_property_keys_known_absent": {"org": None}}), + ("bytes", {"person_property_keys_known_absent": b"plan"}), + ("bytearray", {"person_property_keys_known_absent": bytearray()}), + ("person dict", {"person_property_keys_known_absent": {"plan": "pro"}}), + ("empty person dict", {"person_property_keys_known_absent": {}}), + ( + "group dict", + {"group_property_keys_known_absent": {"org": {"tier": "gold"}}}, + ), + ( + "group bytearray", + {"group_property_keys_known_absent": {"org": bytearray(b"t")}}, + ), + ] + ) + def test_wrong_type_raises_without_a_request(self, _name, kwargs): + with self.assertRaises(TypeError): + self.client.get_feature_flag("flag", "user-1", **kwargs) + self.flags.assert_not_called() + + def test_dict_keys_view_is_accepted(self): + self.client.get_feature_flag( + "flag", + "user-1", + person_property_keys_known_absent={"plan": "pro"}.keys(), + group_property_keys_known_absent={"org": {"tier": "gold"}.keys()}, + ) + body = self.flags.call_args.kwargs + self.assertEqual(body["person_property_keys_known_absent"], ["plan"]) + self.assertEqual(body["group_property_keys_known_absent"], {"org": ["tier"]}) + + +class TestKnownAbsentFallbackCache(unittest.TestCase): + """The outage fallback cache keeps results apart by the listed keys, since a + listing can change a flag's value.""" + + def setUp(self): + self.client = Client( + FAKE_TEST_API_KEY, + secret_key="test", + flag_fallback_cache_url="memory://local/?ttl=300&size=100", + ) + self.client.capture = mock.Mock() + self.client.group_type_mapping = {"0": "organization"} + flags_patch = mock.patch("posthog.client.flags") + self.flags = flags_patch.start() + self.addCleanup(flags_patch.stop) + self.flags.side_effect = RequestsTimeout("flags unavailable") + + def evaluate(self, **kwargs): + return self.client.get_feature_flag("flag", "user-1", **kwargs) + + _person_flag = _flag("flag", [_person_filter("is_not_set")]) + _group_flag = _flag( + "flag", [_group_filter("is_not_set")], aggregation_group_type_index=0 + ) + _groups = {"organization": "org-1"} + + def test_person_listing_result_is_not_served_to_an_unlisted_call(self): + self.client.feature_flags = [self._person_flag] + self.assertIs(self.evaluate(person_property_keys_known_absent=["plan"]), True) + self.assertIsNone(self.evaluate()) + + def test_unlisted_result_is_not_served_to_a_person_listing_call(self): + # An unimplemented operator stays inconclusive even for a listed key. + self.client.feature_flags = [_flag("flag", [_person_filter("between", [1, 2])])] + self.flags.side_effect = None + self.flags.return_value = {"featureFlags": {"flag": REMOTE_VALUE}} + self.assertEqual(self.evaluate(), REMOTE_VALUE) + self.flags.side_effect = RequestsTimeout("flags unavailable") + self.assertIsNone(self.evaluate(person_property_keys_known_absent=["plan"])) + + def test_group_listing_result_is_not_served_to_an_unlisted_call(self): + self.client.feature_flags = [self._group_flag] + self.assertIs( + self.evaluate( + groups=self._groups, + group_property_keys_known_absent={"organization": ["tier"]}, + ), + True, + ) + self.assertIsNone(self.evaluate(groups=self._groups)) + + def test_equivalent_listings_share_a_cached_result(self): + # An unimplemented operator stays inconclusive, so both calls go remote. + self.client.feature_flags = [_flag("flag", [_person_filter("between", [1, 2])])] + self.flags.side_effect = None + self.flags.return_value = {"featureFlags": {"flag": REMOTE_VALUE}} + self.assertEqual( + self.evaluate( + groups=self._groups, + person_property_keys_known_absent=["plan", "region"], + group_property_keys_known_absent={ + "organization": ["tier", "size"], + "project": ["name"], + }, + ), + REMOTE_VALUE, + ) + self.flags.side_effect = RequestsTimeout("flags unavailable") + self.assertEqual( + self.evaluate( + groups=self._groups, + person_property_keys_known_absent=["region", "plan", "plan"], + group_property_keys_known_absent={ + "project": ["name"], + "organization": ["size", "tier", "tier"], + }, + ), + REMOTE_VALUE, + ) + self.assertEqual(self.flags.call_count, 2) + + def test_listed_result_is_not_served_for_a_flag_named_like_its_cache_entry(self): + self.client.feature_flags = [self._person_flag] + self.assertIs(self.evaluate(person_property_keys_known_absent=["plan"]), True) + literal_key = "flag:known_absent:" + Client._known_absent_listing_digest( + ["plan"], None + ) + self.assertIsNone(self.client.get_feature_flag(literal_key, "user-1")) + + def _use_redis_cache(self): + self.client.flag_cache = RedisFlagCache(FakeRedis()) + # Loaded definitions keep the client from fetching (and fencing) on read. + self.client.feature_flags = [] + return self.client.flag_cache + + def _cached_entry_count(self): + cache = self.client.flag_cache + if isinstance(cache, RedisFlagCache): + return len([key for key in cache.redis.store if key != cache.version_key]) + return sum(len(user_flags) for user_flags in cache.cache.values()) + + @parameterized.expand([("memory",), ("redis",)]) + def test_distinct_listings_keep_at_most_two_entries_per_flag_and_user( + self, backend + ): + if backend == "redis": + self._use_redis_cache() + self.client.feature_flags = [] + self.flags.side_effect = None + self.flags.return_value = {"featureFlags": {"flag": REMOTE_VALUE}} + self.assertEqual(self.evaluate(), REMOTE_VALUE) + self.flags.side_effect = RequestsTimeout("flags unavailable") + self.client.feature_flags = [self._person_flag] + for index in range(2000): + self.assertIs( + self.evaluate(person_property_keys_known_absent=["plan", f"k{index}"]), + True, + ) + # One unlisted and one listed entry. + self.assertEqual(self._cached_entry_count(), 2) + # Only the latest listing keeps a fallback, and the unlisted one stays. + self.client.feature_flags = [] + self.assertIs( + self.evaluate(person_property_keys_known_absent=["k1999", "plan"]), True + ) + self.assertIsNone( + self.evaluate(person_property_keys_known_absent=["plan", "k0"]) + ) + self.assertEqual(self.evaluate(), REMOTE_VALUE) + + def test_redis_listed_entry_is_outside_the_unlisted_namespace(self): + cache = self._use_redis_cache() + self.client.feature_flags = [self._person_flag] + self.assertIs(self.evaluate(person_property_keys_known_absent=["plan"]), True) + [listed_key] = [key for key in cache.redis.store if key != cache.version_key] + self.assertFalse(listed_key.startswith(cache.key_prefix)) + # SDK versions that ignore the listing digest read only unlisted keys. + self.assertIsNone( + RedisFlagCache(cache.redis).get_stale_cached_flag("user-1", "flag") + ) + + @parameterized.expand([("_known_absent:user-1",), ("known_absent:user-1",)]) + def test_redis_distinct_id_named_like_the_listed_namespace_stays_apart( + self, colliding_id + ): + cache = self._use_redis_cache() + self.client.feature_flags = [self._person_flag] + self.assertIs(self.evaluate(person_property_keys_known_absent=["plan"]), True) + self.assertNotIn(cache._get_cache_key(colliding_id, "flag"), cache.redis.store) + self.client.feature_flags = [] + self.flags.side_effect = None + self.flags.return_value = {"featureFlags": {"flag": REMOTE_VALUE}} + self.assertEqual( + self.client.get_feature_flag("flag", colliding_id), REMOTE_VALUE + ) + self.flags.side_effect = RequestsTimeout("flags unavailable") + self.assertIs(self.evaluate(person_property_keys_known_absent=["plan"]), True) + self.assertIsNone(self.evaluate()) + + def test_redis_clear_and_invalidation_reach_listed_entries(self): + cache = self._use_redis_cache() + self.client.feature_flags = [self._person_flag] + self.assertIs(self.evaluate(person_property_keys_known_absent=["plan"]), True) + cache.invalidate_version(self.client.flag_definition_version) + self.assertEqual(self._cached_entry_count(), 0) + self.assertIs(self.evaluate(person_property_keys_known_absent=["plan"]), True) + cache.clear() + self.assertEqual(self._cached_entry_count(), 0) + + @parameterized.expand([("memory",), ("redis",)]) + def test_different_listing_gets_no_fallback(self, backend): + if backend == "redis": + self._use_redis_cache() + self.client.feature_flags = [self._person_flag] + self.assertIs(self.evaluate(person_property_keys_known_absent=["plan"]), True) + self.client.feature_flags = [] + self.assertIsNone( + self.evaluate(person_property_keys_known_absent=["plan", "region"]) + ) + self.assertIsNone(self.evaluate()) + self.assertIs(self.evaluate(person_property_keys_known_absent=["plan"]), True) + + @parameterized.expand([("memory",), ("redis",)]) + def test_unlisted_call_gets_its_fallback(self, backend): + if backend == "redis": + self._use_redis_cache() + self.client.feature_flags = [] + self.flags.side_effect = None + self.flags.return_value = {"featureFlags": {"flag": REMOTE_VALUE}} + self.assertEqual(self.evaluate(), REMOTE_VALUE) + self.assertEqual(self._cached_entry_count(), 1) + self.flags.side_effect = RequestsTimeout("flags unavailable") + self.assertEqual(self.evaluate(), REMOTE_VALUE) + self.assertIsNone(self.evaluate(person_property_keys_known_absent=["plan"])) + + def test_redis_entry_without_a_listing_digest_reads_as_unlisted(self): + cache = self._use_redis_cache() + # The entry shape written by SDK versions before listing digests. + cache.redis.set( + cache._get_cache_key("user-1", "flag"), + json.dumps( + { + "flag_result": { + "key": "flag", + "enabled": True, + "variant": REMOTE_VALUE, + "payload": None, + "reason": None, + }, + "flag_version": self.client.flag_definition_version, + "timestamp": time.time(), + "flag_result_type": "FeatureFlagResult", + "flag_result_schema_version": 1, + } + ), + ) + self.assertEqual(self.evaluate(), REMOTE_VALUE) + self.assertIsNone(self.evaluate(person_property_keys_known_absent=["plan"])) + + +@pytest.mark.asyncio +async def test_async_evaluate_flags_sends_listed_keys(): + client = AsyncPosthog(FAKE_TEST_API_KEY, send=False) + with mock.patch( + "posthog.async_client._async_flags", + new=mock.AsyncMock(return_value={"flags": {}}), + ) as async_flags: + await client.evaluate_flags( + "user-1", + person_property_keys_known_absent=["plan"], + group_property_keys_known_absent={"organization": ["tier"], "x": []}, + ) + await client.evaluate_flags("user-1") + first, second = async_flags.call_args_list + assert first.kwargs["person_property_keys_known_absent"] == ["plan"] + assert first.kwargs["group_property_keys_known_absent"] == { + "organization": ["tier"] + } + assert "person_property_keys_known_absent" not in second.kwargs + assert "group_property_keys_known_absent" not in second.kwargs + await client.shutdown() + + +@pytest.mark.asyncio +async def test_async_evaluate_flags_rejects_over_limit_lists(): + client = AsyncPosthog(FAKE_TEST_API_KEY, send=False) + with mock.patch( + "posthog.async_client._async_flags", new=mock.AsyncMock() + ) as async_flags: + with pytest.raises(ValueError, match="at most 1000 keys"): + await client.evaluate_flags( + "user-1", person_property_keys_known_absent=["plan"] * 1001 + ) + async_flags.assert_not_called() + await client.shutdown() diff --git a/posthog/test/test_property_matching_version.py b/posthog/test/test_property_matching_version.py index f6f1f8774..02f635bb4 100644 --- a/posthog/test/test_property_matching_version.py +++ b/posthog/test/test_property_matching_version.py @@ -222,9 +222,9 @@ def test_failed_or_not_modified_refresh_preserves_version(client, refresh): def test_in_flight_full_evaluation_keeps_matching_snapshot(client): client._update_flag_state(definitions(1)) - from posthog import client as client_module + from posthog import feature_flags as feature_flags_module - original = client_module.match_feature_flag_properties + original = feature_flags_module.match_feature_flag_properties calls = 0 def reload_during_evaluation(*args, **kwargs): @@ -235,7 +235,7 @@ def reload_during_evaluation(*args, **kwargs): return original(*args, **kwargs) with mock.patch( - "posthog.client.match_feature_flag_properties", + "posthog.feature_flags.match_feature_flag_properties", side_effect=reload_during_evaluation, ): result, fallback, _ = client._get_all_flags_and_payloads_locally( @@ -308,8 +308,8 @@ def refresh_after_matching(*args, **kwargs): ), mock.patch.object( client.flag_cache, - "set_cached_flag", - wraps=client.flag_cache.set_cached_flag, + "_set_cached_flag", + wraps=client.flag_cache._set_cached_flag, ) as cache_write, ): if api == "result": @@ -476,16 +476,16 @@ def test_lazy_loading_caches_first_local_result_for_outage_fallback( def test_in_flight_result_is_not_cached_in_new_generation(client): client._update_flag_state(definitions(1)) - from posthog import client as client_module + from posthog import feature_flags as feature_flags_module - original = client_module.match_feature_flag_properties + original = feature_flags_module.match_feature_flag_properties def reload_during_evaluation(*args, **kwargs): client._update_flag_state(definitions(2)) return original(*args, **kwargs) with mock.patch( - "posthog.client.match_feature_flag_properties", + "posthog.feature_flags.match_feature_flag_properties", side_effect=reload_during_evaluation, ): assert evaluate(client) is True diff --git a/posthog/test/test_redis_flag_cache_snapshot.py b/posthog/test/test_redis_flag_cache_snapshot.py index 5cf67052a..319e2e13c 100644 --- a/posthog/test/test_redis_flag_cache_snapshot.py +++ b/posthog/test/test_redis_flag_cache_snapshot.py @@ -144,16 +144,16 @@ def test_old_worker_write_is_not_accepted_by_current_worker(workers, change): def test_refresh_during_evaluation_cannot_relabel_result(workers, change): client = workers() load(client, definitions(1)) - from posthog import client as client_module + from posthog import feature_flags as feature_flags_module - original = client_module.match_feature_flag_properties + original = feature_flags_module.match_feature_flag_properties def refresh(*args, **kwargs): load(client, changed_definitions(change)) return original(*args, **kwargs) with mock.patch( - "posthog.client.match_feature_flag_properties", side_effect=refresh + "posthog.feature_flags.match_feature_flag_properties", side_effect=refresh ): assert evaluate(client).get_value() is True assert fallback(client) is None diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py index ab5a759aa..d00e91412 100644 --- a/posthog/test/test_utils.py +++ b/posthog/test/test_utils.py @@ -933,6 +933,7 @@ def test_stale_cache_passes_current_time_and_max_age(self): class StrictEntry: flag_result = "stale-result" flag_definition_version = 1 + _listing_digest = None def is_stale_but_usable(self, current_time, max_stale_age=3600): assert current_time == 1234 @@ -1036,6 +1037,19 @@ def test_default_cache_settings(self): assert default_cache.key_prefix == "posthog:flags:" assert default_cache.version_key == "posthog:flags:version" + def test_listed_cache_key_is_outside_the_unlisted_prefix(self): + for key_prefix in ("test:flags:", "test_flags_", "x"): + cache = utils.RedisFlagCache(self.redis, key_prefix=key_prefix) + listed_key = cache._get_cache_key("user", "beta", "digest") + assert not listed_key.startswith(key_prefix) + assert cache._get_cache_key("user", "beta").startswith(key_prefix) + assert ( + utils.RedisFlagCache(self.redis, key_prefix="")._get_cache_key( + "user", "beta", "digest" + ) + is None + ) + def test_cache_key_and_serialization(self): assert self.cache._get_cache_key("user123", "beta") == "test:flags:user123:beta" @@ -1362,20 +1376,26 @@ def test_snapshot_cleanup_only_deletes_matching_observed_entries(self): ) original_scan = self.redis.scan - def scan_page(*args, **kwargs): - assert len(self.redis.scan_calls) < 2, "scan restarted after final page" - return original_scan(*args, **kwargs) + def scan_page(cursor, match=None, count=None): + unlisted_scans = [ + call for call in self.redis.scan_calls if call[1] == "test:flags:*" + ] + assert match != "test:flags:*" or len(unlisted_scans) < 2, ( + "scan restarted after final page" + ) + return original_scan(cursor, match=match, count=count) with ( mock.patch.object(self.redis, "get", wraps=self.redis.get) as get, mock.patch.object(self.redis, "scan", side_effect=scan_page) as scan, ): self.cache._invalidate_snapshot("snapshot-a") - assert scan.call_count == 2 + assert scan.call_count == 3 assert last_key not in self.redis.store assert self.redis.scan_calls == [ (0, "test:flags:*", 100), (1, "test:flags:*", 100), + (0, "test:flags_known_absent:*", 100), ] assert self.cache._get_cache_key("user", "old") not in self.redis.store assert len(self.redis.store) == 5 @@ -1475,6 +1495,7 @@ def test_invalidate_version(self): assert self.redis.scan_calls == [ (0, "test:flags:*", 100), (1, "test:flags:*", 100), + (0, "test:flags_known_absent:*", 100), ] assert old_key not in self.redis.store assert invalid_key not in self.redis.store @@ -1506,5 +1527,6 @@ def test_clear(self): assert self.redis.scan_calls == [ (0, "test:flags:*", 100), (1, "test:flags:*", 100), + (0, "test:flags_known_absent:*", 100), ] assert self.redis.store == {"other:key": "value"} diff --git a/posthog/types.py b/posthog/types.py index 9335274e5..f474c7f88 100644 --- a/posthog/types.py +++ b/posthog/types.py @@ -68,6 +68,10 @@ class SendFeatureFlagsOptions(TypedDict, total=False): group_properties: Group properties to use for feature flag evaluation specific to this event. Format: { group_type_name: { group_properties } } flag_keys_filter: Optional list of flag keys to evaluate and attach. + person_property_keys_known_absent: Person property keys known to be + absent. See ``Client.evaluate_flags``. + group_property_keys_known_absent: Group property keys known to be + absent, keyed by group type. See ``Client.evaluate_flags``. """ should_send: bool @@ -75,6 +79,8 @@ class SendFeatureFlagsOptions(TypedDict, total=False): person_properties: Optional[dict[str, Any]] group_properties: Optional[dict[str, dict[str, Any]]] flag_keys_filter: Optional[list[str]] + person_property_keys_known_absent: Optional[list[str]] + group_property_keys_known_absent: Optional[dict[str, list[str]]] class FeatureFlagEvaluationRuntime(str, Enum): diff --git a/posthog/utils.py b/posthog/utils.py index a734fa2d3..e6cc08675 100644 --- a/posthog/utils.py +++ b/posthog/utils.py @@ -327,6 +327,7 @@ def __setitem__(self, key, value): CACHE_KEY_PREFIX = "posthog:flags:" _FEATURE_FLAG_RESULT_TYPE = "FeatureFlagResult" _FEATURE_FLAG_RESULT_SCHEMA_VERSION = 1 +_KNOWN_ABSENT_LISTING = "known_absent" class FlagCacheEntry: @@ -336,6 +337,9 @@ def __init__(self, flag_result, flag_definition_version, timestamp=None): self.timestamp = timestamp or time.time() self._snapshot_fingerprint: Optional[str] = None self._is_remote = False + # Digest of the known-absent listing the result was evaluated with. + # None means an unlisted evaluation. + self._listing_digest: Optional[str] = None def is_valid(self, current_time, ttl, current_flag_version): time_valid = (current_time - self.timestamp) < ttl @@ -356,10 +360,19 @@ def __init__(self, max_size=CACHE_MAX_SIZE, default_ttl=CACHE_TTL): self._write_lock = threading.Lock() def _set_cached_remote_flag( - self, distinct_id, flag_key, flag_result, flag_definition_version + self, + distinct_id, + flag_key, + flag_result, + flag_definition_version, + listing_digest=None, ): - self.set_cached_flag( - distinct_id, flag_key, flag_result, flag_definition_version + self._set_cached_flag( + distinct_id, + flag_key, + flag_result, + flag_definition_version, + listing_digest=listing_digest, ) def _advance_generation(self, version, fingerprint=None): @@ -370,6 +383,15 @@ def _advance_generation(self, version, fingerprint=None): def _is_version_current(self, version): return self._minimum_version is None or version >= self._minimum_version + @staticmethod + def _entry_key(flag_key, listing_digest): + # Listed results share one slot per user and flag, so a new listing + # replaces the old one. A tuple key never equals a string flag key, + # so a listed write never replaces the unlisted fallback. + if listing_digest is None: + return flag_key + return (flag_key, _KNOWN_ABSENT_LISTING) + def get_cached_flag(self, distinct_id, flag_key, current_flag_version): current_time = time.time() @@ -390,6 +412,13 @@ def get_cached_flag(self, distinct_id, flag_key, current_flag_version): return None def get_stale_cached_flag(self, distinct_id, flag_key, max_stale_age=None): + return self._get_stale_cached_flag( + distinct_id, flag_key, max_stale_age=max_stale_age + ) + + def _get_stale_cached_flag( + self, distinct_id, flag_key, max_stale_age=None, listing_digest=None + ): if max_stale_age is None: max_stale_age = CACHE_STALE_TTL @@ -399,8 +428,8 @@ def get_stale_cached_flag(self, distinct_id, flag_key, max_stale_age=None): if user_flags is None: return None - entry = user_flags.get(flag_key) - if entry is None: + entry = user_flags.get(self._entry_key(flag_key, listing_digest)) + if entry is None or entry._listing_digest != listing_digest: return None if self._is_version_current( @@ -412,6 +441,18 @@ def get_stale_cached_flag(self, distinct_id, flag_key, max_stale_age=None): def set_cached_flag( self, distinct_id, flag_key, flag_result, flag_definition_version + ): + self._set_cached_flag( + distinct_id, flag_key, flag_result, flag_definition_version + ) + + def _set_cached_flag( + self, + distinct_id, + flag_key, + flag_result, + flag_definition_version, + listing_digest=None, ): with self._write_lock: if not self._is_version_current(flag_definition_version): @@ -431,9 +472,9 @@ def set_cached_flag( if self._is_version_current(entry.flag_definition_version) } - # Store the flag result entry = FlagCacheEntry(flag_result, flag_definition_version) - self.cache[distinct_id][flag_key] = entry + entry._listing_digest = listing_digest + self.cache[distinct_id][self._entry_key(flag_key, listing_digest)] = entry self.access_times[distinct_id] = current_time def invalidate_version(self, old_version): @@ -497,6 +538,15 @@ def __init__( self.stale_ttl = stale_ttl self.key_prefix = key_prefix self.version_key = f"{key_prefix}version" + # Listed results live outside the key_prefix namespace, so SDK versions + # that ignore the listing digest never read them as unlisted results. + # Changing the prefix's last character keeps the two disjoint. + self._listed_key_prefix = ( + f"{key_prefix[:-1]}{'-' if key_prefix[-1] == '_' else '_'}" + f"{_KNOWN_ABSENT_LISTING}:" + if key_prefix + else None + ) self._snapshot = None self._minimum_version = None self._write_lock = threading.Lock() @@ -520,8 +570,19 @@ def _is_entry_current(self, entry): def _is_version_current(self, version): return self._minimum_version is None or version >= self._minimum_version - def _get_cache_key(self, distinct_id, flag_key): - return f"{self.key_prefix}{distinct_id}:{flag_key}" + def _get_cache_key(self, distinct_id, flag_key, listing_digest=None): + if listing_digest is None: + return f"{self.key_prefix}{distinct_id}:{flag_key}" + if self._listed_key_prefix is None: + return None + # One listed slot per user and flag: a new listing replaces the old one. + return f"{self._listed_key_prefix}{distinct_id}:{flag_key}" + + def _key_patterns(self): + patterns = [f"{self.key_prefix}*"] + if self._listed_key_prefix is not None: + patterns.append(f"{self._listed_key_prefix}*") + return patterns def _serialize_entry( self, @@ -530,6 +591,7 @@ def _serialize_entry( timestamp=None, fingerprint=None, is_remote=False, + listing_digest=None, ): if timestamp is None: timestamp = time.time() @@ -546,6 +608,8 @@ def _serialize_entry( entry["snapshot_fingerprint"] = fingerprint if is_remote: entry["evaluation_source"] = "remote" + if listing_digest is not None: + entry["known_absent_listing_digest"] = listing_digest if isinstance(flag_result, _FeatureFlagResult): # Additive metadata keeps the existing entry shape readable by older SDKs. entry["flag_result_type"] = _FEATURE_FLAG_RESULT_TYPE @@ -570,6 +634,7 @@ def _deserialize_entry(self, data): ) result._snapshot_fingerprint = entry.get("snapshot_fingerprint") result._is_remote = entry.get("evaluation_source") == "remote" + result._listing_digest = entry.get("known_absent_listing_digest") return result except (json.JSONDecodeError, KeyError, TypeError, ValueError): # If deserialization fails, treat as cache miss @@ -600,17 +665,27 @@ def get_cached_flag(self, distinct_id, flag_key, current_flag_version): return None def get_stale_cached_flag(self, distinct_id, flag_key, max_stale_age=None): + return self._get_stale_cached_flag( + distinct_id, flag_key, max_stale_age=max_stale_age + ) + + def _get_stale_cached_flag( + self, distinct_id, flag_key, max_stale_age=None, listing_digest=None + ): try: if max_stale_age is None: max_stale_age = self.stale_ttl - cache_key = self._get_cache_key(distinct_id, flag_key) + cache_key = self._get_cache_key(distinct_id, flag_key, listing_digest) + if cache_key is None: + return None data = self.redis.get(cache_key) if data: entry = self._deserialize_entry(data) if ( entry + and entry._listing_digest == listing_digest and self._is_entry_current(entry) and entry.is_stale_but_usable(time.time(), max_stale_age) ): @@ -629,10 +704,20 @@ def set_cached_flag( ) def _set_cached_remote_flag( - self, distinct_id, flag_key, flag_result, flag_definition_version + self, + distinct_id, + flag_key, + flag_result, + flag_definition_version, + listing_digest=None, ): self._set_cached_flag( - distinct_id, flag_key, flag_result, flag_definition_version, is_remote=True + distinct_id, + flag_key, + flag_result, + flag_definition_version, + is_remote=True, + listing_digest=listing_digest, ) def _set_cached_flag( @@ -642,9 +727,12 @@ def _set_cached_flag( flag_result, flag_definition_version, is_remote=False, + listing_digest=None, ): try: - cache_key = self._get_cache_key(distinct_id, flag_key) + cache_key = self._get_cache_key(distinct_id, flag_key, listing_digest) + if cache_key is None: + return # Capture provenance before any blocking work. Never stamp an old # evaluation with the fingerprint installed by a concurrent refresh. snapshot = self._snapshot @@ -658,6 +746,7 @@ def _set_cached_flag( flag_definition_version, fingerprint=fingerprint, is_remote=is_remote, + listing_digest=listing_digest, ) # Serialize writes so an old in-flight SETEX cannot overwrite a newer @@ -678,15 +767,14 @@ def invalidate_version(self, old_version): try: # For Redis, scan for keys with old version and delete them. This could # be expensive with many keys, but it's necessary for correctness. - cursor = 0 - pattern = f"{self.key_prefix}*" - - while True: - cursor, keys = self.redis.scan(cursor, match=pattern, count=100) - self._delete_keys_with_version(keys, old_version) + for pattern in self._key_patterns(): + cursor = 0 + while True: + cursor, keys = self.redis.scan(cursor, match=pattern, count=100) + self._delete_keys_with_version(keys, old_version) - if cursor == 0: - break + if cursor == 0: + break except Exception: # Redis error - silently fail @@ -698,8 +786,9 @@ def _invalidate_snapshot(self, fingerprint): if not fingerprint or fingerprint.startswith("remote-only:"): return try: - for key in self.redis.scan_iter(match=f"{self.key_prefix}*", count=100): - self._delete_snapshot_entry(key, fingerprint) + for pattern in self._key_patterns(): + for key in self.redis.scan_iter(match=pattern, count=100): + self._delete_snapshot_entry(key, fingerprint) except Exception: # This cannot revoke later stale-worker writes or reach an offline # Redis. Snapshot-aware readers still enforce their local fences. @@ -749,16 +838,15 @@ def _key_has_version(self, key, old_version): def clear(self): try: - # Delete all keys matching our pattern - cursor = 0 - pattern = f"{self.key_prefix}*" - - while True: - cursor, keys = self.redis.scan(cursor, match=pattern, count=100) - if keys: - self.redis.delete(*keys) - if cursor == 0: - break + # Delete all keys matching our patterns + for pattern in self._key_patterns(): + cursor = 0 + while True: + cursor, keys = self.redis.scan(cursor, match=pattern, count=100) + if keys: + self.redis.delete(*keys) + if cursor == 0: + break except Exception: # Redis error - silently fail pass diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index 9891e9fa5..3228e0f33 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -1260,8 +1260,10 @@ attribute posthog.types.FlagsResponse.requestId: str attribute posthog.types.LegacyFlagMetadata.payload: Any attribute posthog.types.SendFeatureFlagsOptions.flag_keys_filter: Optional[list[str]] attribute posthog.types.SendFeatureFlagsOptions.group_properties: Optional[dict[str, dict[str, Any]]] +attribute posthog.types.SendFeatureFlagsOptions.group_property_keys_known_absent: Optional[dict[str, list[str]]] attribute posthog.types.SendFeatureFlagsOptions.only_evaluate_locally: Optional[bool] attribute posthog.types.SendFeatureFlagsOptions.person_properties: Optional[dict[str, Any]] +attribute posthog.types.SendFeatureFlagsOptions.person_property_keys_known_absent: Optional[list[str]] attribute posthog.types.SendFeatureFlagsOptions.should_send: bool attribute posthog.types.UnresolvedFlagReason.EXPERIENCE_CONTINUITY = 'experience_continuity' attribute posthog.types.UnresolvedFlagReason.MISSING_CONTEXT = 'missing_context' @@ -1567,7 +1569,7 @@ function posthog.contexts.set_context_device_id(device_id: str) -> None function posthog.contexts.set_context_option(key: str, value: Any) -> None function posthog.contexts.set_context_session(session_id: str) -> None function posthog.contexts.tag(key: str, value: Any) -> None -function posthog.evaluate_flags(distinct_id: Optional[ID_TYPES] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys: Optional[list[str]] = None, device_id: Optional[str] = None) -> FeatureFlagEvaluations +function posthog.evaluate_flags(distinct_id: Optional[ID_TYPES] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys: Optional[list[str]] = None, device_id: Optional[str] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> FeatureFlagEvaluations function posthog.exception_utils.attach_code_variables_to_frames(all_exceptions, exc_info, mask_patterns, ignore_patterns, mask_url_credentials=True, detect_secrets=DEFAULT_CODE_VARIABLES_DETECT_SECRETS) function posthog.exception_utils.construct_artificial_traceback(e) function posthog.exception_utils.event_hint_with_exc_info(exc_info=None) @@ -1600,15 +1602,15 @@ function posthog.exception_utils.to_string(value) function posthog.exception_utils.to_timestamp(value) function posthog.exception_utils.try_attach_code_variables_to_frames(all_exceptions, exc_info, mask_patterns, ignore_patterns, mask_url_credentials=True, detect_secrets=DEFAULT_CODE_VARIABLES_DETECT_SECRETS) function posthog.exception_utils.walk_exception_chain(exc_info) -function posthog.feature_enabled(key: str, distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[bool] +function posthog.feature_enabled(key: str, distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[bool] function posthog.feature_flag_definitions() -function posthog.feature_flags.evaluate_flag_dependency(property, flags_by_key, evaluation_cache, distinct_id, properties, cohort_properties, device_id=None, property_matching_version: int = 1) +function posthog.feature_flags.evaluate_flag_dependency(property, flags_by_key, evaluation_cache, distinct_id, properties, cohort_properties, device_id=None, property_matching_version: int = 1, *, _evaluation_context=None) function posthog.feature_flags.get_matching_variant(flag, bucketing_value) -function posthog.feature_flags.is_condition_match(feature_flag, distinct_id, condition, properties, cohort_properties, flags_by_key=None, evaluation_cache=None, *, bucketing_value, device_id=None, property_matching_version: int = 1) -> ConditionMatch -function posthog.feature_flags.match_cohort(property, property_values, cohort_properties, flags_by_key=None, evaluation_cache=None, distinct_id=None, device_id=None, property_matching_version: int = 1) -> bool -function posthog.feature_flags.match_feature_flag_properties(flag, distinct_id, properties, *, cohort_properties=None, flags_by_key=None, evaluation_cache=None, device_id=None, bucketing_value=None, group_type_mapping=None, groups=None, group_properties=None, property_matching_version: int = 1) -> FlagValue +function posthog.feature_flags.is_condition_match(feature_flag, distinct_id, condition, properties, cohort_properties, flags_by_key=None, evaluation_cache=None, *, bucketing_value, device_id=None, property_matching_version: int = 1, _evaluation_context=None) -> ConditionMatch +function posthog.feature_flags.match_cohort(property, property_values, cohort_properties, flags_by_key=None, evaluation_cache=None, distinct_id=None, device_id=None, property_matching_version: int = 1, *, _evaluation_context=None) -> bool +function posthog.feature_flags.match_feature_flag_properties(flag, distinct_id, properties, *, cohort_properties=None, flags_by_key=None, evaluation_cache=None, device_id=None, bucketing_value=None, group_type_mapping=None, groups=None, group_properties=None, property_matching_version: int = 1, _evaluation_context=None) -> FlagValue function posthog.feature_flags.match_property(property, property_values, property_matching_version: int = 1) -> bool -function posthog.feature_flags.match_property_group(property_group, property_values, cohort_properties, flags_by_key=None, evaluation_cache=None, distinct_id=None, device_id=None, property_matching_version: int = 1) -> bool +function posthog.feature_flags.match_property_group(property_group, property_values, cohort_properties, flags_by_key=None, evaluation_cache=None, distinct_id=None, device_id=None, property_matching_version: int = 1, *, _evaluation_context=None) -> bool function posthog.feature_flags.matches_dependency_value(expected_value, actual_value) function posthog.feature_flags.parse_datetime(value: str) -> datetime.datetime function posthog.feature_flags.parse_semver(value: str) -> tuple @@ -1617,14 +1619,14 @@ function posthog.feature_flags.resolve_bucketing_value(flag, distinct_id, device function posthog.feature_flags.variant_lookup_table(feature_flag) function posthog.flush(timeout_seconds: Optional[float] = 10) -> None function posthog.get_active_span() -> Optional[Span] -function posthog.get_all_flags(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, flag_keys_to_evaluate: Optional[list[str]] = None) -> Optional[dict[str, FlagValue]] -function posthog.get_all_flags_and_payloads(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, flag_keys_to_evaluate: Optional[list[str]] = None) -> FlagsAndPayloads +function posthog.get_all_flags(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, flag_keys_to_evaluate: Optional[list[str]] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[dict[str, FlagValue]] +function posthog.get_all_flags_and_payloads(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, flag_keys_to_evaluate: Optional[list[str]] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> FlagsAndPayloads function posthog.get_context_options() -> Dict[str, Any] -function posthog.get_feature_flag(key: str, distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[FlagValue] +function posthog.get_feature_flag(key: str, distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[FlagValue] function posthog.get_feature_flag_evaluation_runtime(key: str) -> Optional[FeatureFlagEvaluationRuntime] function posthog.get_feature_flag_keys_by_evaluation_runtime(evaluation_runtime: Union[FeatureFlagEvaluationRuntime, str]) -> list[str] -function posthog.get_feature_flag_payload(key: str, distinct_id: ID_TYPES, match_value: Optional[FlagValue] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[object] -function posthog.get_feature_flag_result(key: str, distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[FeatureFlagResult] +function posthog.get_feature_flag_payload(key: str, distinct_id: ID_TYPES, match_value: Optional[FlagValue] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[object] +function posthog.get_feature_flag_result(key: str, distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[FeatureFlagResult] function posthog.get_remote_config_payload(key: str) function posthog.get_tags() -> Dict[str, Any] function posthog.group_identify(group_type: str, group_key: str, properties: Optional[Dict[str, Any]] = None, timestamp: Optional[Union[datetime.datetime, str]] = None, uuid: Optional[str] = None, disable_geoip: Optional[bool] = None, distinct_id: Optional[ID_TYPES] = None, options: Optional[Dict[str, Any]] = None) -> Optional[str] @@ -1862,7 +1864,7 @@ method posthog.async_client.AsyncClient.capture_ai(event: str, **kwargs: Unpack[ method posthog.async_client.AsyncClient.capture_ai_immediate(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str] method posthog.async_client.AsyncClient.capture_exception(exception: Optional[ExceptionArg] = None, *, level: Optional[str] = None, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str] method posthog.async_client.AsyncClient.capture_immediate(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str] -method posthog.async_client.AsyncClient.evaluate_flags(distinct_id: Optional[ID_TYPES] = None, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys: Optional[list[str]] = None, device_id: Optional[str] = None) -> FeatureFlagEvaluations +method posthog.async_client.AsyncClient.evaluate_flags(distinct_id: Optional[ID_TYPES] = None, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys: Optional[list[str]] = None, device_id: Optional[str] = None, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> FeatureFlagEvaluations method posthog.async_client.AsyncClient.flush(timeout_seconds: Optional[float] = 10) -> None method posthog.async_client.AsyncClient.get_remote_config_payload(key: str) -> Optional[Any] method posthog.async_client.AsyncClient.group_identify(group_type: str, group_key: str, properties: Optional[Dict[str, Any]] = None, timestamp: Optional[Union[datetime, str]] = None, uuid: Optional[Union[str, UUID]] = None, disable_geoip: Optional[bool] = None, distinct_id: Optional[ID_TYPES] = None, options: Optional[Dict[str, Any]] = None) -> Optional[str] @@ -1877,23 +1879,23 @@ method posthog.client.Client.alias(previous_id: ID_TYPES, distinct_id: Optional[ method posthog.client.Client.capture(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str] method posthog.client.Client.capture_ai(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str] method posthog.client.Client.capture_exception(exception: Optional[ExceptionArg], *, level: Optional[str] = None, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[str] -method posthog.client.Client.evaluate_flags(distinct_id: Optional[ID_TYPES] = None, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys: Optional[List[str]] = None, device_id: Optional[str] = None) -> FeatureFlagEvaluations -method posthog.client.Client.feature_enabled(key: str, distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[bool] +method posthog.client.Client.evaluate_flags(distinct_id: Optional[ID_TYPES] = None, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys: Optional[List[str]] = None, device_id: Optional[str] = None, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> FeatureFlagEvaluations +method posthog.client.Client.feature_enabled(key: str, distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[bool] method posthog.client.Client.feature_flag_definitions() method posthog.client.Client.flush(timeout_seconds: Optional[float] = 10) -> None method posthog.client.Client.get_active_span() -> Optional[Span] -method posthog.client.Client.get_all_flags(distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> Optional[dict[str, Union[bool, str]]] -method posthog.client.Client.get_all_flags_and_payloads(distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> FlagsAndPayloads +method posthog.client.Client.get_all_flags(distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[dict[str, Union[bool, str]]] +method posthog.client.Client.get_all_flags_and_payloads(distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> FlagsAndPayloads method posthog.client.Client.get_context_options() -> Dict[str, Any] -method posthog.client.Client.get_feature_flag(key: str, distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[FlagValue] +method posthog.client.Client.get_feature_flag(key: str, distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[FlagValue] method posthog.client.Client.get_feature_flag_evaluation_runtime(key: str) -> Optional[FeatureFlagEvaluationRuntime] method posthog.client.Client.get_feature_flag_keys_by_evaluation_runtime(evaluation_runtime: Union[FeatureFlagEvaluationRuntime, str]) -> list[str] -method posthog.client.Client.get_feature_flag_payload(key: str, distinct_id: ID_TYPES, *, match_value: Optional[FlagValue] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[object] -method posthog.client.Client.get_feature_flag_result(key: str, distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None) -> Optional[FeatureFlagResult] -method posthog.client.Client.get_feature_flags_and_payloads(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> FlagsAndPayloads -method posthog.client.Client.get_feature_payloads(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> dict[str, Optional[str]] -method posthog.client.Client.get_feature_variants(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> dict[str, Union[bool, str]] -method posthog.client.Client.get_flags_decision(distinct_id: Optional[ID_TYPES] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None) -> FlagsResponse +method posthog.client.Client.get_feature_flag_payload(key: str, distinct_id: ID_TYPES, *, match_value: Optional[FlagValue] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = False, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[object] +method posthog.client.Client.get_feature_flag_result(key: str, distinct_id: ID_TYPES, *, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, only_evaluate_locally: bool = False, send_feature_flag_events: bool = True, disable_geoip: Optional[bool] = None, device_id: Optional[str] = None, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> Optional[FeatureFlagResult] +method posthog.client.Client.get_feature_flags_and_payloads(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> FlagsAndPayloads +method posthog.client.Client.get_feature_payloads(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> dict[str, Optional[str]] +method posthog.client.Client.get_feature_variants(distinct_id: ID_TYPES, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> dict[str, Union[bool, str]] +method posthog.client.Client.get_flags_decision(distinct_id: Optional[ID_TYPES] = None, groups: Optional[Mapping[str, Union[str, int]]] = None, person_properties: Optional[Dict[str, Any]] = None, group_properties: Optional[Dict[str, Dict[str, Any]]] = None, disable_geoip: Optional[bool] = None, flag_keys_to_evaluate: Optional[list[str]] = None, device_id: Optional[str] = None, *, person_property_keys_known_absent: Optional[Iterable[str]] = None, group_property_keys_known_absent: Optional[Mapping[str, Iterable[str]]] = None) -> FlagsResponse method posthog.client.Client.get_remote_config_payload(key: str) method posthog.client.Client.get_tags() -> Dict[str, Any] method posthog.client.Client.group_identify(group_type: str, group_key: str, properties: Optional[Dict[str, Any]] = None, timestamp: Optional[Union[datetime, str]] = None, uuid: Optional[Union[str, UUID]] = None, disable_geoip: Optional[bool] = None, distinct_id: Optional[ID_TYPES] = None, options: Optional[Dict[str, Any]] = None) -> Optional[str] diff --git a/sdk_compliance_adapter/CONTRIBUTING.md b/sdk_compliance_adapter/CONTRIBUTING.md index e98cd7497..7b841176b 100644 --- a/sdk_compliance_adapter/CONTRIBUTING.md +++ b/sdk_compliance_adapter/CONTRIBUTING.md @@ -4,7 +4,7 @@ This package contains the PostHog Python SDK compliance adapter used with the Po ## Running tests -Tests run automatically in CI via GitHub Actions against harness **1.26.0**. The compliance job runs once for each capture compression (gzip, deflate and zstd). Each run opts into the local-evaluation suite and fails on compliance regressions. +Tests run automatically in CI via GitHub Actions against harness **1.34.0**. The compliance job runs once for each capture compression (gzip, deflate and zstd). Each run opts into the local-evaluation suite and fails on compliance regressions. Run adapter protocol tests from the repository root in an activated virtual environment: @@ -44,7 +44,7 @@ docker run -d --name sdk-adapter --network test-network -p 8080:8080 posthog-pyt docker run --rm \ --name test-harness \ --network test-network \ - ghcr.io/posthog/sdk-test-harness:1.26.0 \ + ghcr.io/posthog/sdk-test-harness:1.34.0@sha256:43f75861fbcf5bc6c3d35511caa2be2d55274054c6071ebeb943aca0bcd0633a \ run --adapter-url http://sdk-adapter:8080 --mock-url http://test-harness:8081 # Cleanup diff --git a/sdk_compliance_adapter/README.md b/sdk_compliance_adapter/README.md index 703f5873a..deec73a91 100644 --- a/sdk_compliance_adapter/README.md +++ b/sdk_compliance_adapter/README.md @@ -59,6 +59,14 @@ explicit property matching; it does not change the SDK's default matching mode. enabled, forced remote calls use a separate definitions-free SDK Client so they cannot accidentally resolve from local rules. Legacy remote responses and flag-called events are preserved. Reset disposes both Clients. +- The adapter also advertises `feature_flags_known_absent_v1`. `/get_feature_flag` + passes optional `person_property_keys_known_absent` and + `group_property_keys_known_absent` to the SDK unchanged, including empty or + over-limit lists, so the SDK's own validation is tested. A rejected list + returns HTTP 500 with the SDK's error. With `allow_remote_fallback: true` it + calls the SDK's default getter on the Client with local definitions, which + evaluates locally and falls back to `/flags` when inconclusive. That mode + conflicts with `force_remote: true` and `only_evaluate_locally: true` (HTTP 400). The adapter is sequential (it does not advertise parallel-test support). diff --git a/sdk_compliance_adapter/adapter.py b/sdk_compliance_adapter/adapter.py index 18d36976c..c3d690b6d 100644 --- a/sdk_compliance_adapter/adapter.py +++ b/sdk_compliance_adapter/adapter.py @@ -318,6 +318,7 @@ def health(): "fail_open", "encoding_" + compression_name(), "feature_flags_local_evaluation_v1", + "feature_flags_known_absent_v1", # Remote /flags requests send ?v=4 and read the v4 flag record. "flags_response_v4", # The legacy payload accessor is exposed on /get_feature_flag_payload. @@ -632,14 +633,33 @@ def get_feature_flag(): person_properties = data.get("person_properties") groups = data.get("groups") group_properties = data.get("group_properties") + # Passed through unchanged so the SDK's own validation is exercised. + known_absent = { + name: data[name] + for name in ( + "person_property_keys_known_absent", + "group_property_keys_known_absent", + ) + if name in data + } disable_geoip = data.get("disable_geoip") only_evaluate_locally = data.get("only_evaluate_locally", False) - force_remote = data.get("force_remote", not only_evaluate_locally) + allow_remote_fallback = data.get("allow_remote_fallback", False) + force_remote = data.get( + "force_remote", not only_evaluate_locally and not allow_remote_fallback + ) if only_evaluate_locally and force_remote: return jsonify( {"error": "only_evaluate_locally conflicts with force_remote"} ), 400 + if allow_remote_fallback and (only_evaluate_locally or force_remote): + return jsonify( + { + "error": "allow_remote_fallback conflicts with force_remote " + "and only_evaluate_locally" + } + ), 400 if not key: return jsonify({"error": "key is required"}), 400 if not distinct_id: @@ -655,6 +675,7 @@ def get_feature_flag(): disable_geoip=disable_geoip, only_evaluate_locally=True, send_feature_flag_events=False, + **known_absent, ) # The real local-only SDK API returns None for inconclusive results; # a conclusive false is a FeatureFlagResult, not a cache miss. @@ -665,16 +686,32 @@ def get_feature_flag(): locally_evaluated=conclusive, ) - client = (state.remote_client or state.client) if force_remote else state.client - value = client.get_feature_flag( - key, - distinct_id, - person_properties=person_properties, - groups=groups, - group_properties=group_properties, - disable_geoip=disable_geoip, - only_evaluate_locally=not force_remote, - ) + if allow_remote_fallback: + # The default getter: local evaluation, then /flags when inconclusive. + client = state.client + value = client.get_feature_flag( + key, + distinct_id, + person_properties=person_properties, + groups=groups, + group_properties=group_properties, + disable_geoip=disable_geoip, + **known_absent, + ) + else: + client = ( + (state.remote_client or state.client) if force_remote else state.client + ) + value = client.get_feature_flag( + key, + distinct_id, + person_properties=person_properties, + groups=groups, + group_properties=group_properties, + disable_geoip=disable_geoip, + only_evaluate_locally=not force_remote, + **known_absent, + ) # Ensure the SDK's side-effect $feature_flag_called event is sent before # the adapter action returns. Otherwise the harness may reset mock-server diff --git a/sdk_compliance_adapter/docker-compose.yml b/sdk_compliance_adapter/docker-compose.yml index 23a8bd6cc..d02ab8639 100644 --- a/sdk_compliance_adapter/docker-compose.yml +++ b/sdk_compliance_adapter/docker-compose.yml @@ -16,7 +16,7 @@ services: # Test harness test-harness: - image: ghcr.io/posthog/sdk-test-harness:1.26.0 + image: ghcr.io/posthog/sdk-test-harness:1.34.0@sha256:43f75861fbcf5bc6c3d35511caa2be2d55274054c6071ebeb943aca0bcd0633a command: ["run", "--adapter-url", "http://sdk-adapter:8080", "--mock-url", "http://test-harness:8081"] networks: - test-network diff --git a/sdk_compliance_adapter/test_adapter.py b/sdk_compliance_adapter/test_adapter.py index 6c12e86ee..01d1d36f8 100644 --- a/sdk_compliance_adapter/test_adapter.py +++ b/sdk_compliance_adapter/test_adapter.py @@ -88,6 +88,7 @@ def test_health_and_init_use_one_codec(adapter, monkeypatch, env_value, codec): monkeypatch.setenv("COMPRESSION", env_value) capabilities = adapter.app.test_client().get("/health").json["capabilities"] assert "feature_flags_local_evaluation_v1" in capabilities + assert "feature_flags_known_absent_v1" in capabilities assert { "capture_v1", "capture_ai_v1", @@ -296,6 +297,103 @@ def test_rejects_conflicting_evaluation_modes(adapter, route): assert response.status_code == 400 +def test_known_absent_keys_resolve_locally(adapter, monkeypatch): + client = initialize(adapter) + monkeypatch.setattr( + posthog.client, "get", Mock(return_value=GetResponse(data=definitions())) + ) + client.post("/reload_feature_flag_definitions", json={}) + remote = Mock(side_effect=AssertionError("Local-only must never request /flags")) + monkeypatch.setattr(adapter.state.client, "_get_flags_decision", remote) + response = client.post( + "/get_feature_flag", + json={ + "key": "flag", + "distinct_id": "user", + "person_properties": {"plan": "banana"}, + "person_property_keys_known_absent": ["plan"], + "only_evaluate_locally": True, + }, + ) + assert response.json == { + "success": True, + "value": False, + "locally_evaluated": True, + } + remote.assert_not_called() + + +def test_allow_remote_fallback_sends_known_absent_keys(adapter, monkeypatch): + client = initialize(adapter) + monkeypatch.setattr( + posthog.client, "get", Mock(return_value=GetResponse(data=definitions())) + ) + client.post("/reload_feature_flag_definitions", json={}) + remote = Mock( + return_value=posthog.client.normalize_flags_response( + {"featureFlags": {"flag": True}} + ) + ) + monkeypatch.setattr(adapter.state.client, "_get_flags_decision", remote) + monkeypatch.setattr( + adapter.state.remote_client, + "_get_flags_decision", + Mock(side_effect=AssertionError("Fallback must use the local client")), + ) + monkeypatch.setattr(adapter.state.client, "capture", Mock()) + response = client.post( + "/get_feature_flag", + json={ + "key": "flag", + "distinct_id": "user", + "person_property_keys_known_absent": ["region"], + "group_property_keys_known_absent": {"organization": ["tier"]}, + "allow_remote_fallback": True, + }, + ) + assert response.json == {"success": True, "value": True} + remote.assert_called_once() + assert remote.call_args.kwargs["person_property_keys_known_absent"] == ["region"] + assert remote.call_args.kwargs["group_property_keys_known_absent"] == { + "organization": ["tier"] + } + + +def test_over_limit_known_absent_keys_are_rejected_by_the_sdk(adapter, monkeypatch): + client = initialize(adapter) + remote = Mock(side_effect=AssertionError("Over-limit lists must not be sent")) + monkeypatch.setattr(adapter.state.client, "_get_flags_decision", remote) + response = client.post( + "/get_feature_flag", + json={ + "key": "flag", + "distinct_id": "user", + "person_property_keys_known_absent": ["plan"] * 1001, + "allow_remote_fallback": True, + }, + ) + assert response.status_code == 500 + assert "at most 1000" in response.json["error"] + remote.assert_not_called() + + +@pytest.mark.parametrize( + "mode", [{"force_remote": True}, {"only_evaluate_locally": True}] +) +def test_allow_remote_fallback_conflicts_with_other_modes(adapter, mode): + client = initialize(adapter) + response = client.post( + "/get_feature_flag", + json={ + "key": "flag", + "distinct_id": "user", + "allow_remote_fallback": True, + **mode, + }, + ) + assert response.status_code == 400 + + @pytest.mark.parametrize("timeout", [0, -1, 30001, True, "100", None]) def test_reload_validates_deadline(adapter, timeout): client = initialize(adapter)