Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
0488f91
feat(flagd-core): add terminal resolve operator
marcozabel Nov 20, 2026
413fe1d
test(flagd): run the testbed resolve scenarios
marcozabel Nov 20, 2026
d0e76f0
test(flagd): skip the non-finite resolve metadata scenario
marcozabel Nov 20, 2026
17f6ba9
test(flagd-core): cover boolean targeting results
marcozabel Nov 23, 2026
236f533
feat(flagd-core): ignore reserved resolve reasons
marcozabel Nov 23, 2026
9d0d3ce
test(flagd): bump the test harness for reserved resolve reasons
marcozabel Nov 23, 2026
ede2045
test(flagd): bump the test harness for more resolve scenarios
marcozabel Nov 23, 2026
968f362
feat(flagd-core): reserve all reasons but TARGETING_MATCH and SPLIT
marcozabel Nov 24, 2026
e61d7e3
test(flagd): bump the test harness for the final reserved reasons
marcozabel Nov 24, 2026
fa5f0f9
test(flagd): bump the test harness for the resolve scenario move
marcozabel Nov 24, 2026
84e5598
test(flagd): drop the resolve provider type
marcozabel Nov 24, 2026
4dcd208
fixup: return None for non-primitive fractional bucket variants
toddbaert Nov 25, 2026
e6a2732
test(flagd): pin the test harness to testbed main
marcozabel Nov 26, 2026
6ac83ad
fixup: null resolve variant, free-form reasons, and RPC defaults on n…
toddbaert Nov 27, 2026
6825ac2
fixup: clarify that reasons only affect telemetry and side effects
toddbaert Nov 27, 2026
a458a62
test(flagd): bump the test harness to v3.12.0 and run resolve in-process
marcozabel Dec 1, 2026
ccd30ba
test(flagd-core): load per-feature flag files from the test harness
marcozabel Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -471,13 +471,8 @@ def _resolve( # noqa: PLR0915 C901
raise ParseError(message) from e
raise GeneralError(message) from e

# When no default variant is configured, the server returns an empty/zero proto
# value with reason=DEFAULT. For DISABLED flags the server omits the variant too.
# In both cases, return the caller's code default value.
if (
response.reason in (Reason.DEFAULT, Reason.DISABLED)
and not response.variant
):
# no variant means no value (code default); reasons only affect telemetry and side effects such as caching
if not response.variant:
value = default_value

# Got a valid flag and valid type. Return it.
Expand Down
15 changes: 15 additions & 0 deletions providers/openfeature-provider-flagd/tests/e2e/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
import pytest

from tests.e2e.step.config_steps import * # noqa: F403
from tests.e2e.step.context_steps import * # noqa: F403
from tests.e2e.step.event_steps import * # noqa: F403
from tests.e2e.step.flag_step import * # noqa: F403
from tests.e2e.step.provider_steps import * # noqa: F403

# Python's JsonLogic raises ZeroDivisionError for x/0, where the other cores compute
# Infinity or NaN, so the flag never reaches resolve's non-finite metadata check
SKIPPED_SCENARIOS = {
"Resolve with a non-finite computed number in metadata falls back to the default variant",
}


def pytest_collection_modifyitems(config, items):
for item in items:
scenario = getattr(getattr(item, "obj", None), "__scenario__", None)
if scenario is not None and scenario.name in SKIPPED_SCENARIOS:
item.add_marker(pytest.mark.skip(reason="JsonLogic raises on x/0"))
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
"~deprecated",
"~fractional-v1",
"~fractional-v2",
# event-payload steps for these are not bound yet
"~metadata-change",
"~change-event-excludes-unchanged",
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
"~deprecated",
"~fractional-v1",
"~fractional-v2",
# event-payload steps for these are not bound yet
"~metadata-change",
"~change-event-excludes-unchanged",
]


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
"~deprecated",
"~fractional-v1",
"~fractional-v2",
# flagd v0.19.0 in the v3.12.0 testbed image does not support resolve yet
"~resolve",
# event-payload steps for this are not bound yet
"~change-event-excludes-unchanged",
]


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from openfeature.client import OpenFeatureClient
from openfeature.evaluation_context import EvaluationContext
from openfeature.event import EventDetails
from openfeature.flag_evaluation import FlagEvaluationDetails, Reason
from openfeature.flag_evaluation import FlagEvaluationDetails

from ._utils import JsonPrimitive, type_cast

Expand Down Expand Up @@ -93,7 +93,8 @@ def resolve_details_reason(
details: FlagEvaluationDetails[JsonPrimitive],
reason: str,
):
assert_equal(details.reason, Reason(reason))
# resolve rules may return any reason, not only the spec ones
assert_equal(details.reason, reason)


@then(
Expand All @@ -117,8 +118,7 @@ def resolve_details_empty_error_code(

@then(parsers.cfparse("the resolved metadata should contain"))
def metadata_contains(details: FlagEvaluationDetails[JsonPrimitive], datatable):
assert_equal(len(details.flag_metadata), len(datatable) - 1) # skip table header
for i in range(1, len(datatable)):
for i in range(1, len(datatable)): # skip table header
key, metadata_type, expected = datatable[i]
assert_equal(details.flag_metadata[key], type_cast[metadata_type](expected))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from unittest.mock import MagicMock, Mock, patch

import grpc
import pytest
from grpc import Channel

from openfeature.contrib.provider.flagd.config import CacheType, Config
Expand Down Expand Up @@ -63,6 +64,41 @@ def test_unary_call_omits_metadata_when_no_selector():
assert "metadata" not in kwargs


@pytest.mark.parametrize("reason", ["DEFAULT", "DISABLED", "OFF_BY_POLICY"])
def test_resolve_without_variant_uses_default_value(reason):
# no variant means no value (code default); reasons only affect telemetry and side effects such as caching
resolver = _make_resolver(None)
mock_stub = MagicMock()
mock_stub.ResolveString = Mock(
return_value=evaluation_pb2.ResolveStringResponse(reason=reason)
)
resolver.stub = mock_stub

result = resolver._resolve("flag", FlagType.STRING, "fallback", None)

assert result.value == "fallback"
assert result.variant is None
assert result.reason == reason


def test_resolve_with_variant_and_disabled_reason_uses_value():
# a reason does not change the outcome, so a variant's value is used
resolver = _make_resolver(None)
mock_stub = MagicMock()
mock_stub.ResolveString = Mock(
return_value=evaluation_pb2.ResolveStringResponse(
value="on-value", variant="on", reason="DISABLED"
)
)
resolver.stub = mock_stub

result = resolver._resolve("flag", FlagType.STRING, "fallback", None)

assert result.value == "on-value"
assert result.variant == "on"
assert result.reason == "DISABLED"


def test_event_stream_includes_selector_metadata_when_configured():
resolver = _make_resolver("test-selector")
mock_stub = MagicMock()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import importlib.resources
from pathlib import Path


def get_features_path() -> str:
Expand All @@ -10,11 +11,18 @@ def get_features_path() -> str:
return str(ref)


def load_testkit_flags() -> str:
"""Load the bundled testkit-flags.json as a string."""
ref = (
def load_testkit_flags(feature_file: str | None = None) -> str:
"""Load the flags for a feature file as a string.

A feature `<name>.feature` uses `<name>-flags.json` when the harness ships one,
and the shared testkit-flags.json otherwise.
"""
flag_data = (
importlib.resources.files("openfeature.contrib.tools.flagd.testkit")
/ "flag_data"
/ "testkit-flags.json"
)
return ref.read_text(encoding="utf-8")
if feature_file:
ref = flag_data / f"{Path(feature_file).stem}-flags.json"
if ref.is_file():
return ref.read_text(encoding="utf-8")
return (flag_data / "testkit-flags.json").read_text(encoding="utf-8")
2 changes: 1 addition & 1 deletion tools/openfeature-flagd-core/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# OpenFeature flagd Core

Reference implementation of the flagd evaluator -- flag parsing, targeting rules (JSON logic), and custom operators (fractional, sem_ver, starts_with, ends_with). Mirrors the Java `flagd-core` module.
Reference implementation of the flagd evaluator -- flag parsing, targeting rules (JSON logic), and custom operators (fractional, sem_ver, starts_with, ends_with, resolve). Mirrors the Java `flagd-core` module.

It is part of the [OpenFeature Python SDK contrib](https://github.com/open-feature/python-sdk-contrib) project.

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import dataclasses
import json
import logging
import threading
import typing
from collections.abc import Mapping, Sequence
Expand All @@ -15,9 +17,15 @@
from .model.flag import Flag
from .model.flag_store import FlagStore
from .targeting import targeting
from .targeting.custom_ops import ResolveResult

T = typing.TypeVar("T")

logger = logging.getLogger("openfeature.contrib")

# flag set metadata keys a resolve rule can't override; the schema only catches literal keys
RESERVED_METADATA_KEYS = frozenset({"flagSetId", "version"})

# Type map for each resolve method
_TYPE_MAP: dict[str, tuple[type | tuple[type, ...], str]] = {
"boolean": ((bool,), "bool"),
Expand All @@ -39,13 +47,45 @@ def _merge_metadata(
return metadata


def _merge_rule_metadata(
metadata: Mapping[str, float | int | str | bool],
rule_metadata: Mapping[str, float | int | str | bool],
) -> Mapping[str, float | int | str | bool]:
merged = dict(metadata)
for key, value in rule_metadata.items():
if key in RESERVED_METADATA_KEYS:
logger.debug(f"Ignoring reserved resolve metadata key {key}")
continue
merged[key] = value
return merged


def _targeting_match(
resolved: typing.Any, metadata: Mapping[str, float | int | str | bool]
) -> tuple[str | None, str | None, Mapping[str, float | int | str | bool]]:
"""Variant, rule reason and metadata of a targeting result."""
if resolved is None:
return None, None, metadata
if isinstance(resolved, ResolveResult):
return (
resolved.variant,
resolved.reason,
_merge_rule_metadata(metadata, resolved.metadata),
)
# convert to string to support shorthand
if isinstance(resolved, bool):
return str(resolved).lower(), None, metadata
return str(resolved), None, metadata


def _default_resolve(
flag: Flag,
default_value: T,
metadata: Mapping[str, float | int | str | bool],
reason: Reason,
) -> FlagResolutionDetails:
variant, value = flag.default
# no variant means no value (code default); reasons only affect telemetry and side effects such as caching
if variant is None:
return FlagResolutionDetails(
default_value,
Expand Down Expand Up @@ -151,27 +191,23 @@ def _resolve(
return result

try:
variant = targeting(flag.key, flag.targeting, evaluation_context)
if variant is None:
result = _default_resolve(
flag, default_value, metadata, Reason.DEFAULT
)
self._check_type(result, flag_type)
return result

if isinstance(variant, bool):
variant = str(variant).lower()
elif not isinstance(variant, str):
variant = str(variant)

if variant not in flag.variants:
raise GeneralError(
f"Resolved variant {variant} not in variants config."
)

resolved = targeting(flag.key, flag.targeting, evaluation_context)
except ReferenceError as e:
raise ParseError(f"Invalid targeting {flag.targeting}") from e

variant, reason, metadata = _targeting_match(resolved, metadata)
if variant is None:
result = _default_resolve(flag, default_value, metadata, Reason.DEFAULT)
if reason is not None:
result = dataclasses.replace(result, reason=reason)
self._check_type(result, flag_type)
return result

if variant not in flag.variants:
raise GeneralError(
f"Resolved variant {variant} not in variants config."
)

variant, value = flag.get_variant(variant)
if value is None:
raise GeneralError(
Expand All @@ -181,7 +217,7 @@ def _resolve(
result = FlagResolutionDetails(
value,
variant=variant,
reason=Reason.TARGETING_MATCH,
reason=Reason.TARGETING_MATCH if reason is None else reason,
flag_metadata=metadata,
)
self._check_type(result, flag_type)
Expand All @@ -195,11 +231,9 @@ def _check_type(
"""Validate the resolved value type matches the expected flag type."""
if flag_type is None:
return
# Skip type check when value is the caller's default (no variant resolved)
# This happens for DEFAULT reason with no variant, or DISABLED flags
if result.reason == Reason.DISABLED:
return
if result.reason == Reason.DEFAULT and result.variant is None:
# Skip type check when value is the caller's default (no variant resolved).
# Not by reason: a resolve rule may return any reason, DISABLED included.
if result.variant is None:
return

type_info = _TYPE_MAP.get(flag_type)
Expand Down
Loading
Loading