diff --git a/tools/openfeature-flagd-core/src/openfeature/contrib/tools/flagd/core/targeting/custom_ops.py b/tools/openfeature-flagd-core/src/openfeature/contrib/tools/flagd/core/targeting/custom_ops.py index 5047bb979..e102beaed 100644 --- a/tools/openfeature-flagd-core/src/openfeature/contrib/tools/flagd/core/targeting/custom_ops.py +++ b/tools/openfeature-flagd-core/src/openfeature/contrib/tools/flagd/core/targeting/custom_ops.py @@ -17,7 +17,8 @@ @dataclass class Fraction: - variant: str | float | int | bool | None + # whatever the variant expression evaluated to, the resolver decides what to do with it + variant: typing.Any weight: int = 1 @@ -54,7 +55,7 @@ def normalize_numbers(data: typing.Any) -> typing.Any: return data -def fractional(data: dict, *args: typing.Any) -> str | float | int | bool | None: +def fractional(data: dict, *args: typing.Any) -> typing.Any: if not args: logger.error("No arguments provided to fractional operator.") return None diff --git a/tools/openfeature-flagd-core/tests/test_targeting.py b/tools/openfeature-flagd-core/tests/test_targeting.py index 4e016b660..494cdad6f 100644 --- a/tools/openfeature-flagd-core/tests/test_targeting.py +++ b/tools/openfeature-flagd-core/tests/test_targeting.py @@ -205,6 +205,34 @@ def test_fractional_non_string_types(self) -> None: result = fractional({}, key, ["a", 50], ["b", 50]) assert result in ("a", "b") + def test_fractional_computed_variant_expression(self) -> None: + """A bucket variant can be any JSON Logic expression, its result is returned.""" + rule = { + "fractional": [ + {"var": "targetingKey"}, + [{"cat": ["r", "ed"]}, 1], + [{"cat": ["bl", "ue"]}, 0], + ] + } + ctx = EvaluationContext(targeting_key="user-1") + assert targeting("test-flag", rule, ctx) == "red" + + def test_fractional_computed_variant_selected_by_weight(self) -> None: + rule = { + "fractional": [ + {"var": "targetingKey"}, + [{"cat": ["r", "ed"]}, 0], + [{"cat": ["bl", "ue"]}, 1], + ] + } + ctx = EvaluationContext(targeting_key="user-1") + assert targeting("test-flag", rule, ctx) == "blue" + + def test_fractional_non_scalar_variant_passed_through(self) -> None: + """The variant isn't type checked, e.g. the result of a resolve expression.""" + resolved = {"variant": "red", "reason": "SPLIT"} + assert fractional({}, "key", [resolved, 1]) == resolved + def test_fractional_top_level_array_not_explicit_key(self) -> None: """Top-level array is reserved for variant buckets (shorthand syntax) per ADR.""" # When no targetingKey in context, shorthand fails and returns None