From 6dad30fa50c7230951c19cb08abee5e811768ca0 Mon Sep 17 00:00:00 2001 From: Lourens de Jager Date: Thu, 19 Nov 2026 23:51:40 +0000 Subject: [PATCH 1/4] chore: evaluate client-side rules and rollouts Ports .NET's ServerSideEvaluation, ClientSideRule and Conditions so a flag deferred to the client resolves from its rules: - Rules are OR'd and the first match wins, with reason "Matched rule ''.". Conditions within a rule are AND'd and short-circuit. No match gives false with "Did not match any rules.". - context-attribute-is-one-of and is-not-one-of compare keys and values case-insensitively, and treat non-string attributes as absent. - percentage-by-context buckets with a pure-Python MurmurHash3 x86_32 over "evaluationKey:targetingKey". A missing targeting key matches only at 100. - Unrecognised condition types never match. Rules and conditions are parsed into typed objects. A field of the wrong type reads as absent, so it raises ParseError when its flag is evaluated and costs only that flag. Tests cover the 114 shared rollout vectors, wrong-typed fields and non-string context attributes. The specification fixtures cover the rest. Co-Authored-By: Claude Opus 5.5 --- .../_v4/_json_utils.py | 6 + .../_v4/client_side_evaluation_context.py | 13 + .../_v4/client_side_rule.py | 42 ++ .../_v4/conditions/__init__.py | 1 + .../_v4/conditions/client_side_condition.py | 19 + .../_v4/conditions/condition_type_names.py | 9 + ...ntext_attribute_is_not_one_of_condition.py | 26 ++ .../context_attribute_is_one_of_condition.py | 25 ++ .../_v4/conditions/context_attributes.py | 50 +++ .../percentage_by_context_condition.py | 47 +++ .../_v4/conditions/percentage_rollout.py | 69 ++++ .../_v4/conditions/unknown_condition.py | 29 ++ .../_v4/evaluation_reasons.py | 13 + .../_v4/parse_server_side_evaluation.py | 73 +++- .../_v4/server_side_evaluation.py | 43 +- .../v4/conditions/test_percentage_rollout.py | 374 ++++++++++++++++++ tests/v4/test_client_side_evaluation.py | 173 ++++++++ tests/v4/test_parse_server_side_evaluation.py | 13 +- tests/v4/test_server_side_evaluation.py | 14 +- 19 files changed, 1020 insertions(+), 19 deletions(-) create mode 100644 src/octopus_openfeature_provider/_v4/client_side_evaluation_context.py create mode 100644 src/octopus_openfeature_provider/_v4/client_side_rule.py create mode 100644 src/octopus_openfeature_provider/_v4/conditions/__init__.py create mode 100644 src/octopus_openfeature_provider/_v4/conditions/client_side_condition.py create mode 100644 src/octopus_openfeature_provider/_v4/conditions/condition_type_names.py create mode 100644 src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_not_one_of_condition.py create mode 100644 src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_one_of_condition.py create mode 100644 src/octopus_openfeature_provider/_v4/conditions/context_attributes.py create mode 100644 src/octopus_openfeature_provider/_v4/conditions/percentage_by_context_condition.py create mode 100644 src/octopus_openfeature_provider/_v4/conditions/percentage_rollout.py create mode 100644 src/octopus_openfeature_provider/_v4/conditions/unknown_condition.py create mode 100644 src/octopus_openfeature_provider/_v4/evaluation_reasons.py create mode 100644 tests/v4/conditions/test_percentage_rollout.py create mode 100644 tests/v4/test_client_side_evaluation.py diff --git a/src/octopus_openfeature_provider/_v4/_json_utils.py b/src/octopus_openfeature_provider/_v4/_json_utils.py index b3a9170..e712747 100644 --- a/src/octopus_openfeature_provider/_v4/_json_utils.py +++ b/src/octopus_openfeature_provider/_v4/_json_utils.py @@ -13,6 +13,12 @@ def as_bool(value: object) -> bool | None: return value if isinstance(value, bool) else None +def as_int(value: object) -> int | None: + # bool is a subclass of int, but true isn't a JSON integer. A float such as + # 50.0 isn't either, as .NET would reject it. + return value if isinstance(value, int) and not isinstance(value, bool) else None + + def as_list(value: object) -> list[object] | None: return value if isinstance(value, list) else None diff --git a/src/octopus_openfeature_provider/_v4/client_side_evaluation_context.py b/src/octopus_openfeature_provider/_v4/client_side_evaluation_context.py new file mode 100644 index 0000000..794afd5 --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/client_side_evaluation_context.py @@ -0,0 +1,13 @@ +"""What a flag's rules and conditions are evaluated against.""" + +from dataclasses import dataclass + +from openfeature.evaluation_context import EvaluationContext + + +@dataclass(frozen=True, slots=True) +class ClientSideEvaluationContext: + # The key percentage-by-context buckets against. + evaluation_key: str + # The caller's context, or None if they supplied none. + open_feature_context: EvaluationContext | None diff --git a/src/octopus_openfeature_provider/_v4/client_side_rule.py b/src/octopus_openfeature_provider/_v4/client_side_rule.py new file mode 100644 index 0000000..7972af6 --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/client_side_rule.py @@ -0,0 +1,42 @@ +"""A named rule the provider evaluates on the client side.""" + +from dataclasses import dataclass + +from openfeature.exception import ParseError + +from octopus_openfeature_provider._v4.client_side_evaluation_context import ( + ClientSideEvaluationContext, +) +from octopus_openfeature_provider._v4.conditions.client_side_condition import ( + ClientSideCondition, +) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ClientSideRule: + """Matches when every one of its conditions matches. + + A field that was missing or of the wrong type in the response is None, and a + condition that wasn't a JSON object is None in ``conditions``. + """ + + name: str | None + conditions: tuple[ClientSideCondition | None, ...] | None + + def matches(self, context: ClientSideEvaluationContext) -> bool: + # The server only defers a named rule carrying at least one condition, so + # anything else is a response it could not have sent. + if self.name is None: + raise ParseError("A rule has no name.") + + if not self.conditions: + raise ParseError(f"Rule '{self.name}' has no conditions.") + + for condition in self.conditions: + if condition is None: + raise ParseError(f"Rule '{self.name}' has a missing condition.") + + if not condition.matches(context): + return False + + return True diff --git a/src/octopus_openfeature_provider/_v4/conditions/__init__.py b/src/octopus_openfeature_provider/_v4/conditions/__init__.py new file mode 100644 index 0000000..fc10da7 --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/conditions/__init__.py @@ -0,0 +1 @@ +"""The conditions of a client-side rule.""" diff --git a/src/octopus_openfeature_provider/_v4/conditions/client_side_condition.py b/src/octopus_openfeature_provider/_v4/conditions/client_side_condition.py new file mode 100644 index 0000000..2b8ce8f --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/conditions/client_side_condition.py @@ -0,0 +1,19 @@ +"""The base type for a condition of a client-side rule.""" + +from abc import ABC, abstractmethod + +from octopus_openfeature_provider._v4.client_side_evaluation_context import ( + ClientSideEvaluationContext, +) + + +class ClientSideCondition(ABC): + __slots__ = () + + @abstractmethod + def matches(self, context: ClientSideEvaluationContext) -> bool: + """Whether this condition is met. + + A condition that did not arrive in a shape its type can evaluate raises + ``ParseError`` rather than reading a value it was not sent. + """ diff --git a/src/octopus_openfeature_provider/_v4/conditions/condition_type_names.py b/src/octopus_openfeature_provider/_v4/conditions/condition_type_names.py new file mode 100644 index 0000000..456bd9e --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/conditions/condition_type_names.py @@ -0,0 +1,9 @@ +"""The ``type`` discriminators of the client-side conditions. + +These mirror the values in the evaluations response, so they must not drift from +the server. +""" + +CONTEXT_ATTRIBUTE_IS_NOT_ONE_OF = "context-attribute-is-not-one-of" +CONTEXT_ATTRIBUTE_IS_ONE_OF = "context-attribute-is-one-of" +PERCENTAGE_BY_CONTEXT = "percentage-by-context" diff --git a/src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_not_one_of_condition.py b/src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_not_one_of_condition.py new file mode 100644 index 0000000..0c561da --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_not_one_of_condition.py @@ -0,0 +1,26 @@ +"""The ``context-attribute-is-not-one-of`` condition.""" + +from dataclasses import dataclass + +from octopus_openfeature_provider._v4.client_side_evaluation_context import ( + ClientSideEvaluationContext, +) +from octopus_openfeature_provider._v4.conditions.client_side_condition import ( + ClientSideCondition, +) +from octopus_openfeature_provider._v4.conditions.context_attributes import is_one_of + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ContextAttributeIsNotOneOfCondition(ClientSideCondition): + """Matches when the context attribute ``key`` is not one of ``values``. + + The exact negation of ``context-attribute-is-one-of``, so a missing attribute + matches. + """ + + key: str | None + values: tuple[str | None, ...] | None + + def matches(self, context: ClientSideEvaluationContext) -> bool: + return not is_one_of(context, self.key, self.values) diff --git a/src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_one_of_condition.py b/src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_one_of_condition.py new file mode 100644 index 0000000..9b6ad56 --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/conditions/context_attribute_is_one_of_condition.py @@ -0,0 +1,25 @@ +"""The ``context-attribute-is-one-of`` condition.""" + +from dataclasses import dataclass + +from octopus_openfeature_provider._v4.client_side_evaluation_context import ( + ClientSideEvaluationContext, +) +from octopus_openfeature_provider._v4.conditions.client_side_condition import ( + ClientSideCondition, +) +from octopus_openfeature_provider._v4.conditions.context_attributes import is_one_of + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ContextAttributeIsOneOfCondition(ClientSideCondition): + """Matches when the context attribute ``key`` is one of ``values``. + + A missing attribute does not match. + """ + + key: str | None + values: tuple[str | None, ...] | None + + def matches(self, context: ClientSideEvaluationContext) -> bool: + return is_one_of(context, self.key, self.values) diff --git a/src/octopus_openfeature_provider/_v4/conditions/context_attributes.py b/src/octopus_openfeature_provider/_v4/conditions/context_attributes.py new file mode 100644 index 0000000..097d34f --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/conditions/context_attributes.py @@ -0,0 +1,50 @@ +"""The attribute lookup shared by both attribute conditions.""" + +from openfeature.exception import ParseError + +from octopus_openfeature_provider._v4.client_side_evaluation_context import ( + ClientSideEvaluationContext, +) + + +def is_one_of( + context: ClientSideEvaluationContext, + key: str | None, + values: tuple[str | None, ...] | None, +) -> bool: + """Whether the context holds an attribute named ``key`` with one of ``values``. + + Keys and values compare case-insensitively, and a non-string attribute counts + as absent. The SDK passes the context un-flattened, so an attribute can be an + int, bool, float, datetime, sequence or mapping. Every attribute whose key + matches is checked, not just the first, as a context can hold several case + variants of one key. + + Raises: + ParseError: If the condition is missing its key or values. + """ + if key is None: + raise ParseError("A condition is missing a key.") + + if not values: + raise ParseError("A condition is missing values.") + + if any(value is None for value in values): + raise ParseError("A condition is missing a value.") + + open_feature_context = context.open_feature_context + if open_feature_context is None: + return False + + # Uppercased to stand in for .NET's OrdinalIgnoreCase, as the browser + # provider does. They agree on every ASCII input. + upper_key = key.upper() + upper_values = {value.upper() for value in values if value is not None} + + return any( + isinstance(attribute_key, str) + and attribute_key.upper() == upper_key + and isinstance(attribute, str) + and attribute.upper() in upper_values + for attribute_key, attribute in open_feature_context.attributes.items() + ) diff --git a/src/octopus_openfeature_provider/_v4/conditions/percentage_by_context_condition.py b/src/octopus_openfeature_provider/_v4/conditions/percentage_by_context_condition.py new file mode 100644 index 0000000..88d2e36 --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/conditions/percentage_by_context_condition.py @@ -0,0 +1,47 @@ +"""The ``percentage-by-context`` condition.""" + +from dataclasses import dataclass + +from openfeature.exception import ParseError + +from octopus_openfeature_provider._v4.client_side_evaluation_context import ( + ClientSideEvaluationContext, +) +from octopus_openfeature_provider._v4.conditions import percentage_rollout +from octopus_openfeature_provider._v4.conditions.client_side_condition import ( + ClientSideCondition, +) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class PercentageByContextCondition(ClientSideCondition): + """Matches when the targeting key falls within the ``percentage``% rollout.""" + + # 0 to 100. None when it was missing or not an integer, which stays + # distinguishable from an explicit 0, a legitimate "nobody". + percentage: int | None + + def matches(self, context: ClientSideEvaluationContext) -> bool: + percentage = self.percentage + if percentage is None: + raise ParseError("A condition is missing a percentage value.") + + # Rejected rather than clamped: reading 101 as "everyone" would turn a + # flag on off the back of a bad payload. + if not 0 <= percentage <= 100: + raise ParseError(f"A condition has a percentage of {percentage}.") + + open_feature_context = context.open_feature_context + targeting_key = ( + open_feature_context.targeting_key if open_feature_context else None + ) + + # Nothing to bucket, so only a full rollout matches, as the server treats + # an untenanted caller. Checked with isinstance as well, since a caller + # without a type checker can pass a targeting key that isn't a str. + if not targeting_key or not isinstance(targeting_key, str): + return percentage >= 100 + + return percentage_rollout.includes( + context.evaluation_key, targeting_key, percentage + ) diff --git a/src/octopus_openfeature_provider/_v4/conditions/percentage_rollout.py b/src/octopus_openfeature_provider/_v4/conditions/percentage_rollout.py new file mode 100644 index 0000000..699f739 --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/conditions/percentage_rollout.py @@ -0,0 +1,69 @@ +"""Buckets a targeting key into a percentage rollout. + +Hashing the flag's evaluation key together with the targeting key keeps a bucket +stable across evaluations, while giving each flag an independent spread of +targeting keys. Every provider library shares this bucketing, so a rollout lands +on the same users whichever one a product uses. +""" + +_MASK_32 = 0xFFFFFFFF +_C1 = 0xCC9E2D51 +_C2 = 0x1B873593 + + +def includes(evaluation_key: str, targeting_key: str, percentage: int) -> bool: + """Whether ``targeting_key`` falls within the first ``percentage`` percent of + targeting keys for the flag identified by ``evaluation_key``.""" + return get_normalized_number(evaluation_key, targeting_key) <= percentage + + +def get_normalized_number(evaluation_key: str, targeting_key: str) -> int: + """A deterministic bucket from 1 to 100 inclusive for the two keys. + + Separate from ``includes`` so the shared cross-library test vectors can + assert on the bucket itself. + """ + data = f"{evaluation_key}:{targeting_key}".encode() + return murmur3_x86_32(data) % 100 + 1 + + +def murmur3_x86_32(data: bytes, seed: int = 0) -> int: + """MurmurHash3 x86_32 of ``data``, as an unsigned 32-bit integer. + + Written out rather than taken from ``mmh3`` so the provider doesn't need a + native wheel. The blocks are read little-endian, as every provider does. + """ + hash_ = seed & _MASK_32 + block_end = len(data) - len(data) % 4 + + for start in range(0, block_end, 4): + k = int.from_bytes(data[start : start + 4], "little") + hash_ ^= _mix_k(k) + hash_ = _rotl32(hash_, 13) + hash_ = (hash_ * 5 + 0xE6546B64) & _MASK_32 + + tail = data[block_end:] + if tail: + hash_ ^= _mix_k(int.from_bytes(tail, "little")) + + hash_ ^= len(data) & _MASK_32 + return _fmix32(hash_) + + +def _mix_k(k: int) -> int: + k = (k * _C1) & _MASK_32 + k = _rotl32(k, 15) + return (k * _C2) & _MASK_32 + + +def _rotl32(value: int, shift: int) -> int: + return ((value << shift) | (value >> (32 - shift))) & _MASK_32 + + +def _fmix32(hash_: int) -> int: + hash_ ^= hash_ >> 16 + hash_ = (hash_ * 0x85EBCA6B) & _MASK_32 + hash_ ^= hash_ >> 13 + hash_ = (hash_ * 0xC2B2AE35) & _MASK_32 + hash_ ^= hash_ >> 16 + return hash_ diff --git a/src/octopus_openfeature_provider/_v4/conditions/unknown_condition.py b/src/octopus_openfeature_provider/_v4/conditions/unknown_condition.py new file mode 100644 index 0000000..040321d --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/conditions/unknown_condition.py @@ -0,0 +1,29 @@ +"""A condition whose ``type`` this version of the provider doesn't recognise.""" + +from dataclasses import dataclass + +from openfeature.exception import ParseError + +from octopus_openfeature_provider._v4.client_side_evaluation_context import ( + ClientSideEvaluationContext, +) +from octopus_openfeature_provider._v4.conditions.client_side_condition import ( + ClientSideCondition, +) + + +@dataclass(frozen=True, slots=True, kw_only=True) +class UnknownCondition(ClientSideCondition): + """Never matches, so a newer server's capability is treated as "not met" by + an older provider rather than failing the flag.""" + + # The unrecognised discriminator, or None if it was missing or not a string. + type: str | None + + def matches(self, context: ClientSideEvaluationContext) -> bool: + # No server version emits a condition without a type, so unlike an + # unrecognised type this is a response that could not have been sent. + if self.type is None: + raise ParseError("A condition is missing a type.") + + return False diff --git a/src/octopus_openfeature_provider/_v4/evaluation_reasons.py b/src/octopus_openfeature_provider/_v4/evaluation_reasons.py new file mode 100644 index 0000000..08708e7 --- /dev/null +++ b/src/octopus_openfeature_provider/_v4/evaluation_reasons.py @@ -0,0 +1,13 @@ +"""Reasons returned alongside a client-side evaluation. + +Both match the strings the Feature Flags service produces server-side, so a flag +reads the same whichever side resolved it. +""" + + +def matched_rule(rule_name: str) -> str: + return f"Matched rule '{rule_name}'." + + +def did_not_match_any_rules() -> str: + return "Did not match any rules." diff --git a/src/octopus_openfeature_provider/_v4/parse_server_side_evaluation.py b/src/octopus_openfeature_provider/_v4/parse_server_side_evaluation.py index 5290c8f..4964e3c 100644 --- a/src/octopus_openfeature_provider/_v4/parse_server_side_evaluation.py +++ b/src/octopus_openfeature_provider/_v4/parse_server_side_evaluation.py @@ -6,9 +6,27 @@ from octopus_openfeature_provider._v4._json_utils import ( as_bool, as_dict, + as_int, as_list, as_str, ) +from octopus_openfeature_provider._v4.client_side_rule import ClientSideRule +from octopus_openfeature_provider._v4.conditions import condition_type_names +from octopus_openfeature_provider._v4.conditions.client_side_condition import ( + ClientSideCondition, +) +from octopus_openfeature_provider._v4.conditions.context_attribute_is_not_one_of_condition import ( + ContextAttributeIsNotOneOfCondition, +) +from octopus_openfeature_provider._v4.conditions.context_attribute_is_one_of_condition import ( + ContextAttributeIsOneOfCondition, +) +from octopus_openfeature_provider._v4.conditions.percentage_by_context_condition import ( + PercentageByContextCondition, +) +from octopus_openfeature_provider._v4.conditions.unknown_condition import ( + UnknownCondition, +) from octopus_openfeature_provider._v4.server_side_evaluation import ( ServerSideEvaluation, ) @@ -52,7 +70,6 @@ def parse_evaluation(raw: object) -> ServerSideEvaluation | None: if slug is None: return None - # TODO: we probably want to parse the client side rules here later instead of plain list. rules = as_list(entry.get("rules")) return ServerSideEvaluation( @@ -60,5 +77,57 @@ def parse_evaluation(raw: object) -> ServerSideEvaluation | None: value=as_bool(entry.get("value")), reason=as_str(entry.get("reason")), evaluation_key=as_str(entry.get("evaluationKey")), - rules=tuple(rules) if rules is not None else None, + rules=tuple(parse_rule(rule) for rule in rules) if rules is not None else None, ) + + +def parse_rule(raw: object) -> ClientSideRule | None: + """Parse one client-side rule, or None if it isn't a JSON object.""" + rule = as_dict(raw) + if rule is None: + return None + + conditions = as_list(rule.get("conditions")) + + return ClientSideRule( + name=as_str(rule.get("name")), + conditions=tuple(parse_condition(condition) for condition in conditions) + if conditions is not None + else None, + ) + + +def parse_condition(raw: object) -> ClientSideCondition | None: + """Parse one condition of a client-side rule, or None if it isn't a JSON + object. + + An unrecognised or missing ``type`` parses to ``UnknownCondition`` rather + than failing, so a condition type introduced by a newer server degrades + safely on an older provider. + """ + condition = as_dict(raw) + if condition is None: + return None + + match condition_type := as_str(condition.get("type")): + case condition_type_names.PERCENTAGE_BY_CONTEXT: + return PercentageByContextCondition( + percentage=as_int(condition.get("percentage")) + ) + case condition_type_names.CONTEXT_ATTRIBUTE_IS_ONE_OF: + return ContextAttributeIsOneOfCondition( + key=as_str(condition.get("key")), + values=_parse_values(condition.get("values")), + ) + case condition_type_names.CONTEXT_ATTRIBUTE_IS_NOT_ONE_OF: + return ContextAttributeIsNotOneOfCondition( + key=as_str(condition.get("key")), + values=_parse_values(condition.get("values")), + ) + case _: + return UnknownCondition(type=condition_type) + + +def _parse_values(raw: object) -> tuple[str | None, ...] | None: + values = as_list(raw) + return tuple(as_str(value) for value in values) if values is not None else None diff --git a/src/octopus_openfeature_provider/_v4/server_side_evaluation.py b/src/octopus_openfeature_provider/_v4/server_side_evaluation.py index 1a12541..f772597 100644 --- a/src/octopus_openfeature_provider/_v4/server_side_evaluation.py +++ b/src/octopus_openfeature_provider/_v4/server_side_evaluation.py @@ -5,11 +5,18 @@ """ from dataclasses import dataclass +from typing import cast from openfeature.evaluation_context import EvaluationContext -from openfeature.exception import GeneralError, ParseError +from openfeature.exception import ParseError from openfeature.flag_evaluation import FlagResolutionDetails +from octopus_openfeature_provider._v4 import evaluation_reasons +from octopus_openfeature_provider._v4.client_side_evaluation_context import ( + ClientSideEvaluationContext, +) +from octopus_openfeature_provider._v4.client_side_rule import ClientSideRule + @dataclass(frozen=True, slots=True, kw_only=True) class ServerSideEvaluation: @@ -17,17 +24,21 @@ class ServerSideEvaluation: value: bool | None reason: str | None evaluation_key: str | None - # TODO: Hold ClientSideRule in this tuple once client-side rules are - # implemented. - rules: tuple[object, ...] | None + # A rule that wasn't a JSON object is None. + rules: tuple[ClientSideRule | None, ...] | None def evaluate( self, context: EvaluationContext | None ) -> FlagResolutionDetails[bool]: - """Resolve the flag. + """Resolve the flag, evaluating the client-side rules if the server left + any. + + The rules are OR'd and the first match wins. A flag deferred to the + client is enabled when a rule matches, and disabled when none do. - Raises ``ParseError`` for a flag in neither shape, which the OpenFeature - SDK turns into the caller's default value. + Raises ``ParseError`` for a flag in neither shape, or with a rule or + condition the server could not have sent, which the OpenFeature SDK turns + into the caller's default value. """ if self.value is not None: if self.reason is None: @@ -49,5 +60,19 @@ def evaluate( if not self.rules: raise ParseError("The flag defers to the client with no rules.") - # TODO: rule evaluation to be implemented. - raise GeneralError("Client-side rules are not supported yet.") + rule_context = ClientSideEvaluationContext(self.evaluation_key, context) + + for rule in self.rules: + if rule is None: + raise ParseError("The flag has a missing rule.") + + if rule.matches(rule_context): + # matches raises for a rule without a name, so it has one here. + name = cast("str", rule.name) + return FlagResolutionDetails( + value=True, reason=evaluation_reasons.matched_rule(name) + ) + + return FlagResolutionDetails( + value=False, reason=evaluation_reasons.did_not_match_any_rules() + ) diff --git a/tests/v4/conditions/test_percentage_rollout.py b/tests/v4/conditions/test_percentage_rollout.py new file mode 100644 index 0000000..860f554 --- /dev/null +++ b/tests/v4/conditions/test_percentage_rollout.py @@ -0,0 +1,374 @@ +import pytest + +from octopus_openfeature_provider._v4.conditions.percentage_rollout import ( + get_normalized_number, +) + +# These cases verify that get_normalized_number produces the same bucketing values +# as the equivalent implementations in the other Octopus OpenFeature provider +# libraries (.NET, Java, browser and Go). The expected values are derived from the +# reference MurmurHash3 little-endian algorithm and are duplicated verbatim across +# all libraries. DO NOT modify the input arguments or expected values. Doing so +# would mask a real divergence in evaluation behaviour between libraries and +# defeat the purpose of this test. +ROLLOUT_VECTORS: list[tuple[str, str, int]] = [ + ( + "ef70b4c0-1773-44a3-9b95-f239ae97d9db", + "780c4b16-a510-49fa-a2b2-bbd1c38dbe31", + 48, + ), + ( + "055665f0-fbb3-484e-8ef1-52125425b7b2", + "6a33c211-5af8-4c34-ba82-4d79846cb045", + 85, + ), + ( + "8e63257f-07f1-43b6-871f-4e8fcaa1718e", + "0a8dc2d9-fb7c-42a9-9bfd-200f65717c5f", + 47, + ), + ( + "b8a1abcd-1a69-46c7-8da4-f9fc3c6da5d7", + "30433819-7096-420f-9b9f-ff555504a5dd", + 79, + ), + ( + "277582f0-93f5-4c2c-888e-44f94ecc6c7f", + "3238dad5-c7d4-460e-868d-f8de4770a1e8", + 97, + ), + ("41f60be0-7cef-4aa3-aaed-cf4a4599a084", "user-0007", 41), + ("rollout", "fd7f2fc4-7ecc-46a0-9ee1-073bac59d6dd", 7), + ( + "83a52df2-49a6-47ec-89f1-b6106a2ca9a3", + "a43ec79d-db51-4371-8827-cb5e7beac345", + 90, + ), + ( + "7b89296c-6dcb-4c50-8857-7eb1924770d3", + "5932b247-0569-4069-9688-867975502818", + 60, + ), + ( + "7aeff54e-808c-46a6-9f49-2fba47a1fca7", + "48c16871-3872-4ddc-a828-c3dd26f30f0b", + 90, + ), + ( + "b08969ee-f0d8-45e3-b763-c84ebdde03f1", + "6b9bb2f6-535a-4e07-b6df-fce8112d9d11", + 68, + ), + ( + "5bc8fbbc-bde5-4099-8164-d8399f767c45", + "545c10b7-eb4d-4a28-a1a6-e4dc0b46adec", + 79, + ), + ( + "5d357ffe-4423-460d-9b0e-da407f5e8e61", + "2b263e0c-e7b2-4237-beb7-aa5d9f5ddbf2", + 93, + ), + ( + "8d62d777-8090-44bd-96a7-4dbe3e572e0f", + "b5e8480a-d3dd-4a47-b108-781d1e644773", + 60, + ), + ( + "688bf8ca-c418-4fcd-9db8-4aa91325af10", + "11eb4678-7889-4121-898d-83332035bce5", + 28, + ), + ( + "8623121d-e0bb-437a-9459-4d8b75673fca", + "dff8494d-3bb3-4b25-9f81-20c447f0e17e", + 76, + ), + ( + "c33f4584-b23b-41d8-893c-d01609de8895", + "48b0083a-3c39-4aba-9b9f-3e14c7608387", + 85, + ), + ("e008364f-306d-4b3d-bce8-0083255d4b38", "tenant-001", 84), + ( + "cc73abe9-9eba-409f-822a-87dc52e17fd9", + "3df9d4e4-bda3-42f7-9b7c-85bf909d05d8", + 11, + ), + ("2507759b-36af-471e-ad2e-f1c113d1e9e3", "a", 13), + ("d7f20e07-ed42-42ed-84bb-895c608099f6", "f97f4108-4e1a-4c75-942f-8ea30236beb7", 9), + ( + "48f165d5-7b00-47f4-b81e-f86f5c8cc1ab", + "8700cfed-571a-41b0-a32e-a7fbb2bec49f", + 18, + ), + ("46f7c9ea-b38c-445a-bad9-8a70a603e9e1", "user-0004", 32), + ( + "f7ae9466-2c20-48f7-9732-3b35156199d0", + "2d885f55-3d4e-42ba-a6b5-3b4cb3362773", + 82, + ), + ("7450bc56-6fc6-4ccb-95b5-582a736a9625", "user-0008", 97), + ("b39cfd4b-8abe-4d78-8520-10116895cea8", "b86759d1-3ba6-4a4a-839f-64bfbf5c8eed", 2), + ("4cdac1b3-1894-45b6-b00a-65ccd081a3d4", "org-001", 74), + ( + "6b0404f2-b094-40b8-ab01-a1c12a3a2107", + "d34923a2-4d4b-4d7e-a96d-7e83b47a99c9", + 93, + ), + ("fbc1af89-7d69-4938-84f7-18fd250c67f3", "org-003", 4), + ("8bb01460-217f-471c-be0a-e8fa1ceac2cc", "org-002", 37), + ("21636369-8b52-4b4a-97b7-50923ceb3ffd", "xxxxxxxxxxxxxx", 7), + ( + "bdd640fb-0667-4ad1-9c80-317fa3b1799d", + "c927b3d7-c9df-4be2-8065-5831f2396945", + 29, + ), + ( + "705e3831-2331-4265-babf-7430e9e4817a", + "87bb47cb-7f00-4264-8706-b39b55d9e4b8", + 15, + ), + ("bd023447-34aa-43ff-b278-e0a594ac807a", "tenant-002", 24), + ("cd28037c-1888-4b25-898c-cb7caf2a6a52", "user-0010", 51), + ("06a3f5be-62a9-401b-8279-530735b8cfae", "user-0003", 15), + ("eb85403c-7e8d-4475-9962-1895e98f559d", "xxxxxxxx", 71), + ( + "8dbb5b2a-6e20-4f8e-9001-a6625a1298a1", + "1a8d7c50-c0d3-4ac5-88a4-3616b02b0cd8", + 41, + ), + ("e60922ca-8aba-43ed-a4d9-4a354580711b", "7dfb4d2e-17f5-413e-ace3-8d733ed6ff1a", 2), + ("6513270e-269e-4d37-b2a7-4de452e6b438", "org-005", 65), + ( + "c393fd0e-1cc6-4be5-b836-46bf0324aac3", + "0ebd0956-dd97-4698-83c7-520f5783b05f", + 60, + ), + ("72e63ac7-a953-4322-9f70-d5dc2e675fc7", "xxxxxxxxx", 92), + ( + "07158ab7-95f3-4183-9b69-13cd87684f34", + "bc087a02-3415-49ca-a6cd-1c580bad0d02", + 79, + ), + ( + "21b8c26b-c023-43ab-95da-cb8f8c773fe6", + "c50c6475-83c3-4a03-b99d-b98358c913cb", + 59, + ), + ( + "e8d79f49-af6d-414c-8a6f-188a424e617b", + "2f3e9786-a457-4917-b52b-e67cdbd76923", + 70, + ), + ("377e6ff8-8e83-4961-ae84-3b2c7e96ba87", "tenant-005", 50), + ( + "02f16d3d-8f4c-49e7-992b-0703f7467ac9", + "e895eba8-39a6-4ad3-a3aa-7533875fd5a9", + 86, + ), + ("323d3ab0-f35c-48a9-bce5-e9d717208331", "tenant-003", 88), + ( + "d95bafc8-f2a4-427b-9cf4-bb99f4bea973", + "9aa4e5cd-db41-4f65-9532-f707456606fe", + 98, + ), + ( + "993955be-5888-4f39-937c-56af8c5187c1", + "76f939de-30a5-46cc-980d-e48610541d3f", + 32, + ), + ( + "d2e270f9-1fc6-4186-aebc-12938bfb2fcf", + "ecd4771a-15e0-4c75-9c36-af0e659ba9df", + 25, + ), + ( + "fe1b1434-3b10-4980-950c-aef9618a9261", + "6f5bb29e-1705-4cec-9f02-2d65cbbdc47d", + 66, + ), + ("dark-launch", "xxxxxxxxxxxx", 25), + ( + "0a3aee49-6666-4879-938d-da71e3658966", + "505f886a-8692-491e-a530-3537fa5dcfb4", + 13, + ), + ("db5b5fab-8f4d-4e27-9da1-494c73cf256d", "xxxxxxxxxx", 44), + ( + "3bb427c1-a1da-459d-aad1-245c92010b38", + "f10cc4f3-ae39-489a-81cf-e9d7627bffe1", + 76, + ), + ("374f469f-e3e0-4eda-9a6b-b5639dfcfbd4", "xxxxxxxxxxxxx", 58), + ( + "ee34cf80-4b49-41f1-b1b9-016371f4a4e4", + "2b57b54f-05fa-4c58-a83e-395b8e9a0d48", + 66, + ), + ( + "4dad2986-ce83-4960-aa06-e9ab85a0bcc1", + "9b58e9a0-ab47-4b99-a8b5-8dcf8187afc1", + 78, + ), + ("9af49740-96f5-40ee-9e25-02420ae59635", "user-0006", 6), + ( + "e539a78b-c8ef-4346-8b12-ae6ead581e57", + "7dfa7c26-d794-4374-8ad7-57b6173beda4", + 88, + ), + ( + "e3e70682-c209-4cac-a29f-6fbed82c07cd", + "ed146fe6-b963-4511-aa7b-4732d636b6ce", + 38, + ), + ( + "cd613e30-d8f1-4adf-91b7-584a2265b1f5", + "193988fd-b97b-4177-bb55-68426f35f0bb", + 97, + ), + ("10adf348-2c4b-4d89-9344-7cbaed90dafc", "xxxxxxxxxxx", 67), + ("32833106-536e-45df-80b2-d002cc92d33d", "abcd", 10), + ( + "c15521b1-b3dc-450a-9daa-37e51b591d75", + "a814e7ff-b207-453b-8167-7ccdeb6c1acc", + 41, + ), + ( + "de04cece-83e9-40e4-9c51-e692dc1729ca", + "6347afc2-8444-4e8e-8f6d-a0d8ed54c5d8", + 44, + ), + ("c12776e4-6dd4-41b2-abce-fab3a3b48c4a", "user-0002", 68), + ("d1f36a09-9d74-4646-b388-d25833183edb", "user-0005", 86), + ("85750621-02fb-4d4f-b57f-bc5af71a1bfc", "abcde", 30), + ("feature-toggle", "tenant-004", 57), + ("7b24b13f-17ba-4194-b6ae-4b1d3423bf15", "ab", 19), + ( + "e149bd09-0df5-4245-84b0-6badfa7576c5", + "201af639-f64b-4b83-8594-4e9cdac12538", + 25, + ), + ( + "5532e8ba-3083-449e-b945-e4b665c1d4b4", + "2f3adacf-3c50-4499-8960-90bdf5d7e2fd", + 39, + ), + ( + "8e91579a-21c3-439e-90c1-91728c541241", + "2ca20ef1-a0d9-47e9-8d6e-5c0baeb6ce87", + 71, + ), + ( + "c6601970-e9ff-441d-8899-3a14bb459fdf", + "c3565f1d-1bda-4d13-afc1-3e734ce48c7d", + 99, + ), + ("c963cfe0-afae-4a3b-b909-6a04e7d80068", "user-0009", 94), + ("ec7d4222-6f41-4481-8fde-580f122088a5", "user-0001", 6), + ("988a0c48-5979-41d1-b000-368d2534c02d", "org-004", 10), + ("bd0558b4-9828-4a61-883e-dd4112cc16df", "xxxxxxxxxxxxxxx", 7), + ( + "a689ee27-eec1-43b6-95a8-f48f39643825", + "097ac32f-0f04-4b42-9dcc-9e88dd29c0f4", + 21, + ), + ("9530fcd9-d6fd-4d9b-a203-2801b65c1c28", "abc", 9), + ( + "3e1c26d3-23ef-423e-a848-f808f54d35bf", + "f4e663c3-d0eb-4c6c-a8c2-bf7e6628ac93", + 32, + ), + ( + "75bd5125-db54-435f-9802-db897f041728", + "780c4b16-a510-49fa-a2b2-bbd1c38dbe31", + 64, + ), + ( + "8cd272e0-909e-4060-8425-07646bc9947a", + "6a33c211-5af8-4c34-ba82-4d79846cb045", + 23, + ), + ("experiment-a", "0a8dc2d9-fb7c-42a9-9bfd-200f65717c5f", 93), + ( + "eeee3183-69ca-47e7-9826-00e9111f4efd", + "30433819-7096-420f-9b9f-ff555504a5dd", + 76, + ), + ( + "b3fb08f3-4b48-438b-9e51-a921e8e6a305", + "3238dad5-c7d4-460e-868d-f8de4770a1e8", + 84, + ), + ("14a03569-d26b-4496-92e5-dfe8cb1855fe", "user-0007", 65), + ("9cecdeee-a156-4927-9ff6-3c0179e58218", "fd7f2fc4-7ecc-46a0-9ee1-073bac59d6dd", 2), + ( + "568cec2b-740a-4798-96f1-813481854f8a", + "a43ec79d-db51-4371-8827-cb5e7beac345", + 73, + ), + ( + "6018366c-f658-47a7-9ed3-4fe53a096533", + "5932b247-0569-4069-9688-867975502818", + 83, + ), + ( + "87751d4c-a850-4e2c-84dc-da6a797d76de", + "48c16871-3872-4ddc-a828-c3dd26f30f0b", + 38, + ), + ( + "4a37fa2d-f2d7-440f-8785-9faeecc3f80c", + "6b9bb2f6-535a-4e07-b6df-fce8112d9d11", + 68, + ), + ( + "a8d42934-33e7-48a0-a81f-9b0cbf4e7af6", + "545c10b7-eb4d-4a28-a1a6-e4dc0b46adec", + 34, + ), + ( + "9c6ab710-4a08-4720-8ede-24428a013fda", + "2b263e0c-e7b2-4237-beb7-aa5d9f5ddbf2", + 11, + ), + ( + "b406dd29-9b57-4d64-8490-5c0914c25b99", + "b5e8480a-d3dd-4a47-b108-781d1e644773", + 28, + ), + ("checkout-v2", "11eb4678-7889-4121-898d-83332035bce5", 21), + ( + "4462ebfc-5f91-4ef0-9cfb-ac6e7687a66e", + "dff8494d-3bb3-4b25-9f81-20c447f0e17e", + 43, + ), + ( + "63bf9de9-f33f-4a58-b698-0fbe5edcccc1", + "48b0083a-3c39-4aba-9b9f-3e14c7608387", + 11, + ), + ("test", "az", 1), + ("bucket", "j", 1), + ("test", "y", 100), + ("flag", "c", 100), + ("test-feature", "用户", 30), + ("test-feature", "مستخدم", 19), + ("test-feature", "ユーザー", 73), + ("test-feature", "🎉", 54), + ("test-feature", "café", 31), + ("test-feature", "naïve", 28), + ("rollout", "用户-001", 20), + ("experiment-a", "пользователь", 81), + ("test-feature", "사용자", 62), + ("dark-launch", "テナント-001", 8), +] + + +@pytest.mark.parametrize( + ("evaluation_key", "targeting_key", "expected"), ROLLOUT_VECTORS +) +def test_returns_the_shared_bucket( + evaluation_key: str, targeting_key: str, expected: int +) -> None: + assert get_normalized_number(evaluation_key, targeting_key) == expected diff --git a/tests/v4/test_client_side_evaluation.py b/tests/v4/test_client_side_evaluation.py new file mode 100644 index 0000000..ba5254a --- /dev/null +++ b/tests/v4/test_client_side_evaluation.py @@ -0,0 +1,173 @@ +"""Client-side evaluation cases the specification fixtures don't cover. + +The fixtures exercise missing and null fields, but not fields of the wrong type, +or context attributes that aren't strings. +""" + +from datetime import UTC, datetime + +import pytest +from openfeature.evaluation_context import EvaluationContext +from openfeature.exception import ErrorCode, ParseError + +from octopus_openfeature_provider._v4.parse_server_side_evaluation import ( + parse_evaluation, +) +from octopus_openfeature_provider._v4.server_side_evaluation import ( + ServerSideEvaluation, +) + + +def deferred_flag(*rules: object) -> ServerSideEvaluation: + evaluation = parse_evaluation( + {"slug": "my-feature", "evaluationKey": "evaluation-key", "rules": list(rules)} + ) + assert evaluation is not None + return evaluation + + +def rule_with(*conditions: object) -> dict[str, object]: + return {"name": "Beta ring", "conditions": list(conditions)} + + +def is_one_of(values: object) -> dict[str, object]: + return {"type": "context-attribute-is-one-of", "key": "ring", "values": values} + + +CONTEXT = EvaluationContext(targeting_key="user-1", attributes={"ring": "beta"}) + + +# Fields of the wrong type + + +@pytest.mark.parametrize( + ("rule", "expected_problem"), + [ + pytest.param(42, "The flag has a missing rule.", id="rule-is-a-number"), + pytest.param( + [rule_with(is_one_of(["beta"]))], + "The flag has a missing rule.", + id="rule-is-an-array", + ), + pytest.param( + {"name": 42, "conditions": [is_one_of(["beta"])]}, + "A rule has no name.", + id="rule-name-is-a-number", + ), + pytest.param( + {"name": "Beta ring", "conditions": is_one_of(["beta"])}, + "Rule 'Beta ring' has no conditions.", + id="conditions-is-an-object", + ), + pytest.param( + rule_with("context-attribute-is-one-of"), + "Rule 'Beta ring' has a missing condition.", + id="condition-is-a-string", + ), + pytest.param( + rule_with({"type": 42, "key": "ring", "values": ["beta"]}), + "A condition is missing a type.", + id="condition-type-is-a-number", + ), + pytest.param( + rule_with( + {"type": "context-attribute-is-one-of", "key": 42, "values": ["beta"]} + ), + "A condition is missing a key.", + id="key-is-a-number", + ), + pytest.param( + rule_with(is_one_of("beta")), + "A condition is missing values.", + id="values-is-a-string", + ), + pytest.param( + rule_with(is_one_of(["beta", 42])), + "A condition is missing a value.", + id="a-value-is-a-number", + ), + pytest.param( + rule_with({"type": "percentage-by-context", "percentage": "100"}), + "A condition is missing a percentage value.", + id="percentage-is-a-string", + ), + pytest.param( + rule_with({"type": "percentage-by-context", "percentage": 100.0}), + "A condition is missing a percentage value.", + id="percentage-is-a-float", + ), + pytest.param( + rule_with({"type": "percentage-by-context", "percentage": True}), + "A condition is missing a percentage value.", + id="percentage-is-a-bool", + ), + ], +) +def test_a_field_of_the_wrong_type_raises_a_parse_error( + rule: object, expected_problem: str +) -> None: + with pytest.raises(ParseError) as raised: + deferred_flag(rule).evaluate(CONTEXT) + + assert raised.value.error_code == ErrorCode.PARSE_ERROR + assert raised.value.error_message == expected_problem + + +# Context attributes that aren't strings + + +@pytest.mark.parametrize( + ("attribute", "values"), + [ + pytest.param(5, ["5"], id="int"), + pytest.param(True, ["true", "True"], id="bool"), + pytest.param(1.5, ["1.5"], id="float"), + pytest.param( + datetime(2026, 1, 1, tzinfo=UTC), + ["2026-01-01T00:00:00Z", "2026-01-01 00:00:00+00:00"], + id="datetime", + ), + pytest.param(["beta"], ["beta"], id="sequence"), + pytest.param({"ring": "beta"}, ["beta"], id="mapping"), + ], +) +def test_a_context_attribute_that_is_not_a_string_counts_as_absent( + attribute: object, values: list[str] +) -> None: + # Constructed without the type checker, as an untyped caller can. + context = EvaluationContext( + targeting_key="user-1", + attributes={"ring": attribute}, # type: ignore[dict-item] + ) + + is_one_of_result = deferred_flag(rule_with(is_one_of(values))).evaluate(context) + is_not_one_of_result = deferred_flag( + rule_with( + {"type": "context-attribute-is-not-one-of", "key": "ring", "values": values} + ) + ).evaluate(context) + + assert is_one_of_result.value is False + assert is_not_one_of_result.value is True + + +def test_a_non_string_attribute_does_not_hide_a_matching_case_variant() -> None: + context = EvaluationContext(attributes={"ring": 5, "RING": "beta"}) + + result = deferred_flag(rule_with(is_one_of(["beta"]))).evaluate(context) + + assert result.value is True + assert result.reason == "Matched rule 'Beta ring'." + + +@pytest.mark.parametrize("percentage", [99, 100]) +def test_a_targeting_key_that_is_not_a_string_counts_as_missing( + percentage: int, +) -> None: + context = EvaluationContext(targeting_key=42) # type: ignore[arg-type] + + result = deferred_flag( + rule_with({"type": "percentage-by-context", "percentage": percentage}) + ).evaluate(context) + + assert result.value is (percentage == 100) diff --git a/tests/v4/test_parse_server_side_evaluation.py b/tests/v4/test_parse_server_side_evaluation.py index 8e3bcf5..89cf991 100644 --- a/tests/v4/test_parse_server_side_evaluation.py +++ b/tests/v4/test_parse_server_side_evaluation.py @@ -2,6 +2,10 @@ from openfeature.evaluation_context import EvaluationContext from openfeature.exception import ParseError +from octopus_openfeature_provider._v4.client_side_rule import ClientSideRule +from octopus_openfeature_provider._v4.conditions.context_attribute_is_one_of_condition import ( + ContextAttributeIsOneOfCondition, +) from octopus_openfeature_provider._v4.parse_server_side_evaluation import ( InvalidManifestError, parse_evaluation, @@ -18,6 +22,11 @@ ], } +PARSED_RULE = ClientSideRule( + name="Beta ring", + conditions=(ContextAttributeIsOneOfCondition(key="ring", values=("beta",)),), +) + CONTEXT = EvaluationContext(targeting_key="user-1", attributes={"ring": "beta"}) @@ -50,7 +59,7 @@ def test_deferred_flag_parses_evaluation_key_and_rules() -> None: value=None, reason=None, evaluation_key="evaluation-key", - rules=(RULE,), + rules=(PARSED_RULE,), ) @@ -97,7 +106,7 @@ def test_deferred_flag_parses_evaluation_key_and_rules() -> None: value=None, reason=None, evaluation_key=None, - rules=(RULE,), + rules=(PARSED_RULE,), ), id="evaluation-key-is-a-number", ), diff --git a/tests/v4/test_server_side_evaluation.py b/tests/v4/test_server_side_evaluation.py index 92f8881..65bcfa5 100644 --- a/tests/v4/test_server_side_evaluation.py +++ b/tests/v4/test_server_side_evaluation.py @@ -2,16 +2,18 @@ from openfeature.evaluation_context import EvaluationContext from openfeature.exception import ErrorCode, ParseError +from octopus_openfeature_provider._v4.client_side_rule import ClientSideRule +from octopus_openfeature_provider._v4.conditions.context_attribute_is_one_of_condition import ( + ContextAttributeIsOneOfCondition, +) from octopus_openfeature_provider._v4.server_side_evaluation import ( ServerSideEvaluation, ) -RULE = { - "name": "Beta ring", - "conditions": [ - {"type": "context-attribute-is-one-of", "key": "ring", "values": ["beta"]} - ], -} +RULE = ClientSideRule( + name="Beta ring", + conditions=(ContextAttributeIsOneOfCondition(key="ring", values=("beta",)),), +) # Satisfies RULE, so a flag that failed to raise would visibly turn on. CONTEXT = EvaluationContext(targeting_key="user-1", attributes={"ring": "beta"}) From e3ef1999493b99c949f59ea59deab34bdea9989f Mon Sep 17 00:00:00 2001 From: Lourens de Jager Date: Fri, 20 Nov 2026 00:09:04 +0000 Subject: [PATCH 2/4] fix: compare non-ASCII context attributes as .NET does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit str.upper applies Unicode's full case mappings, so "Straße" matched "STRASSE", where .NET's OrdinalIgnoreCase and Java's equalsIgnoreCase don't. Keys and values are now uppercased one character at a time, keeping any character that would expand. Also: - Make "Did not match any rules." a constant rather than a function. - Say in parse_condition's docstring that a missing type raises at evaluation, unlike an unrecognised one. - Test as_int directly. Co-Authored-By: Claude Opus 5.5 --- .../_v4/conditions/context_attributes.py | 31 ++++++++--- .../_v4/evaluation_reasons.py | 3 +- .../_v4/parse_server_side_evaluation.py | 6 ++- .../_v4/server_side_evaluation.py | 2 +- tests/v4/test_client_side_evaluation.py | 52 ++++++++++++++++++- tests/v4/test_json_utils.py | 11 ++++ 6 files changed, 93 insertions(+), 12 deletions(-) diff --git a/src/octopus_openfeature_provider/_v4/conditions/context_attributes.py b/src/octopus_openfeature_provider/_v4/conditions/context_attributes.py index 097d34f..9c6103b 100644 --- a/src/octopus_openfeature_provider/_v4/conditions/context_attributes.py +++ b/src/octopus_openfeature_provider/_v4/conditions/context_attributes.py @@ -36,15 +36,34 @@ def is_one_of( if open_feature_context is None: return False - # Uppercased to stand in for .NET's OrdinalIgnoreCase, as the browser - # provider does. They agree on every ASCII input. - upper_key = key.upper() - upper_values = {value.upper() for value in values if value is not None} + upper_key = _ordinal_upper(key) + upper_values = {_ordinal_upper(value) for value in values if value is not None} return any( isinstance(attribute_key, str) - and attribute_key.upper() == upper_key + and _ordinal_upper(attribute_key) == upper_key and isinstance(attribute, str) - and attribute.upper() in upper_values + and _ordinal_upper(attribute) in upper_values for attribute_key, attribute in open_feature_context.attributes.items() ) + + +def _ordinal_upper(text: str) -> str: + """``text`` uppercased one character at a time, so two strings compare as + .NET's ``OrdinalIgnoreCase`` and Java's ``equalsIgnoreCase`` compare them. + + ``str.upper`` applies Unicode's full case mappings, some of which expand a + character, so "Straße" would equal "STRASSE" where .NET and Java say it + doesn't. A character that expands is kept as it is instead. That agrees with + .NET on ASCII and on expansions such as "ß" and "fi", but not on the few Greek + letters with an iota subscript, which .NET maps to their titlecase form. + """ + upper = text.upper() + + # Nothing expanded, so every character mapped one to one. + if len(upper) == len(text): + return upper + + return "".join( + upper_char if len(upper_char := char.upper()) == 1 else char for char in text + ) diff --git a/src/octopus_openfeature_provider/_v4/evaluation_reasons.py b/src/octopus_openfeature_provider/_v4/evaluation_reasons.py index 08708e7..18dacb4 100644 --- a/src/octopus_openfeature_provider/_v4/evaluation_reasons.py +++ b/src/octopus_openfeature_provider/_v4/evaluation_reasons.py @@ -9,5 +9,4 @@ def matched_rule(rule_name: str) -> str: return f"Matched rule '{rule_name}'." -def did_not_match_any_rules() -> str: - return "Did not match any rules." +DID_NOT_MATCH_ANY_RULES = "Did not match any rules." diff --git a/src/octopus_openfeature_provider/_v4/parse_server_side_evaluation.py b/src/octopus_openfeature_provider/_v4/parse_server_side_evaluation.py index 4964e3c..fdb8f69 100644 --- a/src/octopus_openfeature_provider/_v4/parse_server_side_evaluation.py +++ b/src/octopus_openfeature_provider/_v4/parse_server_side_evaluation.py @@ -102,8 +102,10 @@ def parse_condition(raw: object) -> ClientSideCondition | None: object. An unrecognised or missing ``type`` parses to ``UnknownCondition`` rather - than failing, so a condition type introduced by a newer server degrades - safely on an older provider. + than failing the whole response. An unrecognised type never matches, so a + condition type introduced by a newer server degrades safely on an older + provider. A missing one raises ``ParseError`` when the flag is evaluated, as + no server sends a condition without a type. """ condition = as_dict(raw) if condition is None: diff --git a/src/octopus_openfeature_provider/_v4/server_side_evaluation.py b/src/octopus_openfeature_provider/_v4/server_side_evaluation.py index f772597..e0f6cf8 100644 --- a/src/octopus_openfeature_provider/_v4/server_side_evaluation.py +++ b/src/octopus_openfeature_provider/_v4/server_side_evaluation.py @@ -74,5 +74,5 @@ def evaluate( ) return FlagResolutionDetails( - value=False, reason=evaluation_reasons.did_not_match_any_rules() + value=False, reason=evaluation_reasons.DID_NOT_MATCH_ANY_RULES ) diff --git a/tests/v4/test_client_side_evaluation.py b/tests/v4/test_client_side_evaluation.py index ba5254a..a71e4f4 100644 --- a/tests/v4/test_client_side_evaluation.py +++ b/tests/v4/test_client_side_evaluation.py @@ -1,7 +1,8 @@ """Client-side evaluation cases the specification fixtures don't cover. The fixtures exercise missing and null fields, but not fields of the wrong type, -or context attributes that aren't strings. +or context attributes that aren't strings, or case-insensitive matching beyond +ASCII. """ from datetime import UTC, datetime @@ -171,3 +172,52 @@ def test_a_targeting_key_that_is_not_a_string_counts_as_missing( ).evaluate(context) assert result.value is (percentage == 100) + + +# Case-insensitive matching beyond ASCII, compared as .NET's OrdinalIgnoreCase +# compares it + + +@pytest.mark.parametrize( + ("attribute", "value", "expected"), + [ + pytest.param("straße", "STRAßE", True, id="sharp-s-in-both"), + pytest.param("Straße", "STRASSE", False, id="sharp-s-does-not-expand"), + pytest.param("file", "FILE", False, id="ligature-does-not-expand"), + pytest.param("café", "CAFÉ", True, id="accented-letter"), + pytest.param("пользователь", "ПОЛЬЗОВАТЕЛЬ", True, id="cyrillic"), + ], +) +def test_a_non_ascii_value_compares_one_character_at_a_time( + attribute: str, value: str, expected: bool +) -> None: + context = EvaluationContext(attributes={"city": attribute}) + + result = deferred_flag( + rule_with( + {"type": "context-attribute-is-one-of", "key": "city", "values": [value]} + ) + ).evaluate(context) + + assert result.value is expected + + +@pytest.mark.parametrize( + ("attribute_key", "expected"), + [ + pytest.param("STRAßE", True, id="sharp-s-in-both"), + pytest.param("STRASSE", False, id="sharp-s-does-not-expand"), + ], +) +def test_a_non_ascii_key_compares_one_character_at_a_time( + attribute_key: str, expected: bool +) -> None: + context = EvaluationContext(attributes={attribute_key: "beta"}) + + result = deferred_flag( + rule_with( + {"type": "context-attribute-is-one-of", "key": "straße", "values": ["beta"]} + ) + ).evaluate(context) + + assert result.value is expected diff --git a/tests/v4/test_json_utils.py b/tests/v4/test_json_utils.py index 080daea..2e1019c 100644 --- a/tests/v4/test_json_utils.py +++ b/tests/v4/test_json_utils.py @@ -3,6 +3,7 @@ from octopus_openfeature_provider._v4._json_utils import ( as_bool, as_dict, + as_int, as_list, as_str, ) @@ -28,6 +29,16 @@ def test_as_bool_reads_any_other_type_as_absent(value: object) -> None: assert as_bool(value) is None +@pytest.mark.parametrize("value", [0, 50, -1, 101]) +def test_as_int_returns_an_integer(value: int) -> None: + assert as_int(value) == value + + +@pytest.mark.parametrize("value", [None, True, False, 50.0, "50", [], {}]) +def test_as_int_reads_any_other_type_as_absent(value: object) -> None: + assert as_int(value) is None + + @pytest.mark.parametrize("value", [[], [1, "two", None]]) def test_as_list_returns_a_list(value: list[object]) -> None: assert as_list(value) is value From 6c601bf765d22d38f8cdba93e70e9fc25ba9b893 Mon Sep 17 00:00:00 2001 From: Lourens de Jager Date: Fri, 20 Nov 2026 01:10:58 +0000 Subject: [PATCH 3/4] test: pin that evaluation never reads a malformed part it doesn't reach Nothing checks a response up front, so a malformed rule behind a matching one, or a malformed condition behind a failing one, never fails the flag. That was agreed in the review of the .NET provider's client-side evaluation, and the .NET, Java and browser providers each pin it with the same tests. The specification fixtures don't cover it. Co-Authored-By: Claude Opus 5.5 --- tests/v4/test_client_side_evaluation.py | 32 +++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/tests/v4/test_client_side_evaluation.py b/tests/v4/test_client_side_evaluation.py index a71e4f4..d549348 100644 --- a/tests/v4/test_client_side_evaluation.py +++ b/tests/v4/test_client_side_evaluation.py @@ -1,8 +1,8 @@ """Client-side evaluation cases the specification fixtures don't cover. The fixtures exercise missing and null fields, but not fields of the wrong type, -or context attributes that aren't strings, or case-insensitive matching beyond -ASCII. +context attributes that aren't strings, case-insensitive matching beyond ASCII, +or a malformed part of a flag that evaluation never reaches. """ from datetime import UTC, datetime @@ -114,6 +114,34 @@ def test_a_field_of_the_wrong_type_raises_a_parse_error( assert raised.value.error_message == expected_problem +# Malformed parts evaluation never reaches. Nothing checks the response up front, +# as in the .NET, Java and browser providers, so a malformed rule or condition +# only fails the flag if evaluation reaches it. + + +def test_a_malformed_rule_behind_a_matching_rule_is_never_read() -> None: + result = deferred_flag( + rule_with(is_one_of(["beta"])), + { + "name": "Trial licences", + "conditions": [{"key": "license", "values": ["trial"]}], + }, + ).evaluate(CONTEXT) + + assert result.value is True + assert result.reason == "Matched rule 'Beta ring'." + + +def test_a_malformed_condition_behind_a_failing_one_is_never_read() -> None: + # Conditions stop at the first that does not match, so the rest are never read. + result = deferred_flag( + rule_with(is_one_of(["alpha"]), {"type": "percentage-by-context"}) + ).evaluate(CONTEXT) + + assert result.value is False + assert result.reason == "Did not match any rules." + + # Context attributes that aren't strings From 5905038da0a447473c12744cac67811478b9ddc5 Mon Sep 17 00:00:00 2001 From: Lourens de Jager Date: Sun, 22 Nov 2026 18:51:12 +0000 Subject: [PATCH 4/4] test: keep only the non-ASCII cases where the providers disagree MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The accented and Cyrillic cases behave the same in every provider, so they pinned nothing. What's left are the "ß" and ligature cases, where .NET and Java differ from the browser provider, with a pointer to BMBB-1553, which will settle which way the specification goes. Co-Authored-By: Claude Opus 5.5 --- tests/v4/test_client_side_evaluation.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/v4/test_client_side_evaluation.py b/tests/v4/test_client_side_evaluation.py index d549348..7728b69 100644 --- a/tests/v4/test_client_side_evaluation.py +++ b/tests/v4/test_client_side_evaluation.py @@ -202,8 +202,10 @@ def test_a_targeting_key_that_is_not_a_string_counts_as_missing( assert result.value is (percentage == 100) -# Case-insensitive matching beyond ASCII, compared as .NET's OrdinalIgnoreCase -# compares it +# Case-insensitive matching where the providers disagree. .NET and Java leave a +# character that uppercases to several ("ß" to "SS") as it is, but the browser +# provider expands it. These follow .NET until the specification settles it in +# BMBB-1553, which would change them if it went the other way. @pytest.mark.parametrize( @@ -212,8 +214,6 @@ def test_a_targeting_key_that_is_not_a_string_counts_as_missing( pytest.param("straße", "STRAßE", True, id="sharp-s-in-both"), pytest.param("Straße", "STRASSE", False, id="sharp-s-does-not-expand"), pytest.param("file", "FILE", False, id="ligature-does-not-expand"), - pytest.param("café", "CAFÉ", True, id="accented-letter"), - pytest.param("пользователь", "ПОЛЬЗОВАТЕЛЬ", True, id="cyrillic"), ], ) def test_a_non_ascii_value_compares_one_character_at_a_time(