Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(flags): make exact boolean matching explicit (#90694)

Manoel Aranda Neto3315c116a361
diff --git a/docs/internal/feature-flags/rust-service-overview.md b/docs/internal/feature-flags/rust-service-overview.md
index 6fb4dd960b72..ec5aa19fec96 100644
--- a/docs/internal/feature-flags/rust-service-overview.md
+++ b/docs/internal/feature-flags/rust-service-overview.md
@@ -237,6 +237,10 @@ All values come from environment variables via the `envconfig` crate. Defined in
| `ENABLE_METRICS` | `false` | Expose `/metrics` endpoint |
| `SERVICE_MODE` | `all` | Fleet mode: `flags`, `definitions`, or `all` |
+### Property matching rollout
+
+Exact property matching is selected per team through `TeamFeatureFlagsConfig.property_matching_version`. Version `1` preserves legacy boolean coercion, while version `2` uses exact scalar and array equality. Team metadata and local-evaluation responses expose the selected version.
+
### PostgreSQL
| Variable | Default | Purpose |
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index 6829876c13d4..52645e81cf7c 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -39,7 +39,11 @@ from posthog.hogql.property import PERSON_METADATA_FIELDS, property_to_expr
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.services.flags_service import FlagVersionConflictError, batch_evaluate_flag_for_team
+from posthog.api.services.flags_service import (
+ FlagVersionConflictError,
+ PropertyMatchingVersionConflictError,
+ batch_evaluate_flag_for_team,
+)
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
from posthog.api.utils import action
from posthog.cdp.filters import build_behavioral_event_expr
@@ -102,6 +106,10 @@ from products.cohorts.backend.models.util import (
)
from products.cohorts.backend.models.validation import CohortTypeValidationSerializer
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.models.team_feature_flags_config import (
+ PropertyMatchingVersion,
+ TeamFeatureFlagsConfig,
+)
from products.product_analytics.backend.facade.models import Insight
@@ -2145,6 +2153,7 @@ def _batch_evaluate_flag_page_with_retries(
project_id: int,
flag_key: str,
expected_version: int,
+ expected_property_matching_version: int,
cursor: int,
limit: int,
) -> dict[str, Any]:
@@ -2159,11 +2168,12 @@ def _batch_evaluate_flag_page_with_retries(
project_id=project_id,
flag_key=flag_key,
expected_version=expected_version,
+ expected_property_matching_version=expected_property_matching_version,
cursor=cursor,
limit=limit,
)
- except FlagVersionConflictError:
- # Permanent: the flag changed mid-run; retrying the same page cannot help.
+ except (FlagVersionConflictError, PropertyMatchingVersionConflictError):
+ # Permanent: the pinned evaluation inputs changed; retrying the same page cannot help.
raise
except requests.RequestException as err:
if (
@@ -2216,6 +2226,12 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,
# service refuses to evaluate under any other, so a run can never mix two
# definitions of the flag. Nullable versions coerce to 0 on both sides.
expected_version = feature_flag.version or 0
+ expected_property_matching_version = (
+ TeamFeatureFlagsConfig.objects.filter(team_id=team_id)
+ .values_list("property_matching_version", flat=True)
+ .first()
+ or PropertyMatchingVersion.LEGACY
+ )
started_at = timezone.now()
start_monotonic = time.monotonic()
@@ -2229,6 +2245,7 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,
project_id=project_id,
flag_key=feature_flag.key,
expected_version=expected_version,
+ expected_property_matching_version=expected_property_matching_version,
cursor=cursor,
limit=batchsize,
)
@@ -2281,7 +2298,9 @@ def get_cohort_actors_for_feature_flag(cohort_id: int, flag: str, team_id: int,
)
capture_exception(err, additional_properties={"cohort_id": cohort_id, "team_id": team_id})
error_code = (
- CohortErrorCode.FLAG_CHANGED if isinstance(err, FlagVersionConflictError) else CohortErrorCode.UNKNOWN
+ CohortErrorCode.FLAG_CHANGED
+ if isinstance(err, (FlagVersionConflictError, PropertyMatchingVersionConflictError))
+ else CohortErrorCode.UNKNOWN
)
COHORT_FLAG_GENERATION_COMPLETED_COUNTER.labels(outcome=error_code.value).inc()
COHORT_FLAG_GENERATION_DURATION_SECONDS.labels(outcome=error_code.value).observe(
diff --git a/posthog/api/services/flags_service.py b/posthog/api/services/flags_service.py
index 42089832751d..acfcdb6b9907 100644
--- a/posthog/api/services/flags_service.py
+++ b/posthog/api/services/flags_service.py
@@ -34,6 +34,10 @@ class FlagVersionConflictError(Exception):
"""The feature flag changed while a static cohort was being generated from it."""
+class PropertyMatchingVersionConflictError(Exception):
+ """Property matching semantics changed during static cohort generation."""
+
+
def get_flags_from_service(
token: str,
distinct_id: str,
@@ -155,6 +159,7 @@ def batch_evaluate_flag_for_team(
expected_version: int,
cursor: int,
limit: int,
+ expected_property_matching_version: int = 1,
) -> dict[str, Any]:
"""
Request one page of batch flag evaluation from the Rust flags service.
@@ -172,13 +177,15 @@ def batch_evaluate_flag_for_team(
limit: Page size; the service rejects (400) any value above its configured
maximum (BATCH_FLAG_EVAL_MAX_LIMIT, default 10000) rather than clamping it,
so keep this at or below that maximum
+ expected_property_matching_version: Matching semantics pinned for every page in the run
Returns:
- The page as a dict: {"matched_person_uuids": [...], "next_cursor": int | None, "errors_count": int}
+ The page as a dict with matched_person_uuids, next_cursor, errors_count, and property_matching_version
Raises:
ImproperlyConfigured: `INTERNAL_REQUEST_TOKEN` is not set
FlagVersionConflictError: The flag's version no longer matches `expected_version`
+ PropertyMatchingVersionConflictError: The service cannot use the pinned matching version
requests.RequestException: If the HTTP request fails (timeout, connection error, etc.)
requests.HTTPError: If the service returns a non-2xx status code
"""
@@ -198,6 +205,7 @@ def batch_evaluate_flag_for_team(
"project_id": project_id,
"flag_key": flag_key,
"expected_version": expected_version,
+ "expected_property_matching_version": expected_property_matching_version,
"cursor": cursor,
"limit": limit,
},
@@ -205,9 +213,21 @@ def batch_evaluate_flag_for_team(
timeout=BATCH_FLAG_EVALUATION_TIMEOUT_SECONDS,
)
if response.status_code == 409:
+ error = response.json().get("error")
+ if error == "property_matching_version_conflict":
+ raise PropertyMatchingVersionConflictError(
+ f"Property matching semantics changed while generating a cohort from feature flag '{flag_key}'. "
+ "Re-run cohort generation with the current matching version."
+ )
raise FlagVersionConflictError(
f"Feature flag '{flag_key}' changed while generating the cohort (expected version "
f"{expected_version}). Re-run cohort generation to use the latest flag definition."
)
response.raise_for_status()
- return response.json()
+ response_data = response.json()
+ if response_data.get("property_matching_version", 1) != expected_property_matching_version:
+ raise PropertyMatchingVersionConflictError(
+ f"Feature flags service did not use property matching version {expected_property_matching_version} "
+ f"while generating a cohort from feature flag '{flag_key}'."
+ )
+ return response_data
diff --git a/posthog/api/test/test_flags_service.py b/posthog/api/test/test_flags_service.py
index 68bfcdce7d50..0391d0410be5 100644
--- a/posthog/api/test/test_flags_service.py
+++ b/posthog/api/test/test_flags_service.py
@@ -8,6 +8,7 @@ from parameterized import parameterized
from posthog.api.services.flags_service import (
FlagVersionConflictError,
+ PropertyMatchingVersionConflictError,
batch_evaluate_flag_for_team,
get_flags_from_service,
)
@@ -34,6 +35,7 @@ class TestBatchEvaluateFlagForTeam(SimpleTestCase):
def test_409_maps_to_flag_version_conflict_before_raise_for_status(self, mock_post):
response = MagicMock()
response.status_code = 409
+ response.json.return_value = {"error": "version_conflict"}
mock_post.return_value = response
with self.assertRaises(FlagVersionConflictError):
@@ -48,7 +50,65 @@ class TestBatchEvaluateFlagForTeam(SimpleTestCase):
# The 409 branch must short-circuit: a generic HTTPError from raise_for_status
# would lose the version-conflict semantics the paging loop relies on.
response.raise_for_status.assert_not_called()
- response.json.assert_not_called()
+
+ @override_settings(INTERNAL_REQUEST_TOKEN="secret")
+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")
+ def test_property_matching_version_conflict_is_permanent(self, mock_post):
+ response = MagicMock()
+ response.status_code = 409
+ response.json.return_value = {"error": "property_matching_version_conflict"}
+ mock_post.return_value = response
+
+ with self.assertRaises(PropertyMatchingVersionConflictError):
+ batch_evaluate_flag_for_team(
+ team_id=1,
+ project_id=1,
+ flag_key="my-flag",
+ expected_version=7,
+ expected_property_matching_version=2,
+ cursor=0,
+ limit=100,
+ )
+
+ @override_settings(INTERNAL_REQUEST_TOKEN="secret")
+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")
+ def test_accepts_legacy_response_without_property_matching_version(self, mock_post):
+ response_data: dict[str, object] = {"matched_person_uuids": [], "next_cursor": None, "errors_count": 0}
+ response = MagicMock()
+ response.status_code = 200
+ response.json.return_value = response_data
+ mock_post.return_value = response
+
+ result = batch_evaluate_flag_for_team(
+ team_id=1,
+ project_id=1,
+ flag_key="my-flag",
+ expected_version=7,
+ expected_property_matching_version=1,
+ cursor=0,
+ limit=100,
+ )
+
+ self.assertEqual(result, response_data)
+
+ @override_settings(INTERNAL_REQUEST_TOKEN="secret")
+ @patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")
+ def test_rejects_response_without_pinned_property_matching_version(self, mock_post):
+ response = MagicMock()
+ response.status_code = 200
+ response.json.return_value = {"matched_person_uuids": [], "next_cursor": None, "errors_count": 0}
+ mock_post.return_value = response
+
+ with self.assertRaises(PropertyMatchingVersionConflictError):
+ batch_evaluate_flag_for_team(
+ team_id=1,
+ project_id=1,
+ flag_key="my-flag",
+ expected_version=7,
+ expected_property_matching_version=2,
+ cursor=0,
+ limit=100,
+ )
@override_settings(INTERNAL_REQUEST_TOKEN="secret")
@patch("posthog.api.services.flags_service._FLAGS_SERVICE_SESSION.post")
diff --git a/posthog/storage/team_metadata_cache.py b/posthog/storage/team_metadata_cache.py
index 1a6d700daafd..d0e17fdbdccb 100644
--- a/posthog/storage/team_metadata_cache.py
+++ b/posthog/storage/team_metadata_cache.py
@@ -65,7 +65,10 @@ from posthog.storage.hypercache_manager import (
get_cache_stats as get_cache_stats_generic,
)
-from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig
+from products.feature_flags.backend.models.team_feature_flags_config import (
+ PropertyMatchingVersion,
+ TeamFeatureFlagsConfig,
+)
logger = structlog.get_logger(__name__)
@@ -156,7 +159,11 @@ def _serialize_team_field(field: str, value: Any) -> Any:
return value
-def _serialize_team_to_metadata(team: Team, minimal_flag_called_events: bool | None = None) -> dict[str, Any]:
+def _serialize_team_to_metadata(
+ team: Team,
+ minimal_flag_called_events: bool | None = None,
+ property_matching_version: int | None = None,
+) -> dict[str, Any]:
"""
Serialize a Team object to metadata dictionary.
@@ -164,6 +171,8 @@ def _serialize_team_to_metadata(team: Team, minimal_flag_called_events: bool | N
team: Team object with organization and project already loaded
minimal_flag_called_events: Pre-fetched value from TeamFeatureFlagsConfig, to let
batch callers avoid an N+1 query. If None, this looks it up itself.
+ property_matching_version: Pre-fetched property matching semantics version. If None,
+ this looks it up with the other feature flags config value.
Returns:
Dictionary containing full team metadata
@@ -176,19 +185,22 @@ def _serialize_team_to_metadata(team: Team, minimal_flag_called_events: bool | N
metadata["organization_name"] = team.organization.name if team.organization else None
metadata["project_name"] = team.project.name if team.project else None
- if minimal_flag_called_events is None:
+ if minimal_flag_called_events is None or property_matching_version is None:
# Deliberately not team.teamfeatureflagsconfig: the reverse O2O accessor gets
# cache-populated as a side effect of register_team_extension_signal's
# get_or_create(team=instance, ...) at team-creation time, so an already-loaded
# Team object can carry a stale cached value if the config row changes after
# the Team was loaded. An explicit query is always fresh.
- minimal_flag_called_events = (
+ config_values = (
TeamFeatureFlagsConfig.objects.filter(team_id=team.id)
- .values_list("minimal_flag_called_events", flat=True)
+ .values_list("minimal_flag_called_events", "property_matching_version")
.first()
- or False
)
- metadata["minimal_flag_called_events"] = minimal_flag_called_events
+ if config_values is not None:
+ minimal_flag_called_events = config_values[0]
+ property_matching_version = config_values[1]
+ metadata["minimal_flag_called_events"] = minimal_flag_called_events or False
+ metadata["property_matching_version"] = property_matching_version or PropertyMatchingVersion.LEGACY
return metadata
@@ -207,14 +219,17 @@ def _batch_load_team_metadata(teams: list[Team]) -> dict[int, dict[str, Any]]:
Returns:
Dict mapping team_id -> metadata dict
"""
- minimal_flag_called_events_by_team = dict(
- TeamFeatureFlagsConfig.objects.filter(team_id__in=[team.id for team in teams]).values_list(
- "team_id", "minimal_flag_called_events"
- )
- )
+ config_by_team_id = {
+ team_id: (minimal_flag_called_events, property_matching_version)
+ for team_id, minimal_flag_called_events, property_matching_version in TeamFeatureFlagsConfig.objects.filter(
+ team_id__in=[team.id for team in teams]
+ ).values_list("team_id", "minimal_flag_called_events", "property_matching_version")
+ }
return {
team.id: _serialize_team_to_metadata(
- team, minimal_flag_called_events=minimal_flag_called_events_by_team.get(team.id, False)
+ team,
+ minimal_flag_called_events=config_by_team_id.get(team.id, (False, PropertyMatchingVersion.LEGACY))[0],
+ property_matching_version=config_by_team_id.get(team.id, (False, PropertyMatchingVersion.LEGACY))[1],
)
for team in teams
}
@@ -332,7 +347,12 @@ def verify_team_metadata(
# Compare only fields we care about (defined in TEAM_METADATA_FIELDS + derived fields).
# This allows removing fields from the cache without triggering unnecessary fixes.
- fields_to_check = set(TEAM_METADATA_FIELDS) | {"organization_name", "project_name", "minimal_flag_called_events"}
+ fields_to_check = set(TEAM_METADATA_FIELDS) | {
+ "organization_name",
+ "project_name",
+ "minimal_flag_called_events",
+ "property_matching_version",
+ }
diffs = []
for key in fields_to_check:
db_val = db_data.get(key)
diff --git a/posthog/storage/test/test_team_metadata_cache.py b/posthog/storage/test/test_team_metadata_cache.py
index d192d1c0e8d8..186d70d823c2 100644
--- a/posthog/storage/test/test_team_metadata_cache.py
+++ b/posthog/storage/test/test_team_metadata_cache.py
@@ -418,9 +418,9 @@ class TestVerifyTeamMetadata(BaseTest):
@parameterized.expand(
[
("name", "Wrong Name"),
- # minimal_flag_called_events isn't in TEAM_METADATA_FIELDS — it's added to
- # fields_to_check separately, so it needs its own mismatch case.
+ # TeamFeatureFlagsConfig fields are tracked separately from TEAM_METADATA_FIELDS.
("minimal_flag_called_events", True),
+ ("property_matching_version", 2),
]
)
@patch("posthog.storage.team_metadata_cache.get_team_metadata")
@@ -450,13 +450,8 @@ class TestVerifyTeamMetadata(BaseTest):
self.assertEqual(result["issue"], "CACHE_MISS")
-class TestMinimalFlagCalledEventsInMetadata(BaseTest):
- """
- minimal_flag_called_events lives on TeamFeatureFlagsConfig, not on Team, so it's
- derived rather than pulled from TEAM_METADATA_FIELDS. Guards against the derivation
- defaulting to the wrong value or the batch path (used by cache warming) drifting
- from the single-team path (used by cache miss lookups).
- """
+class TestFeatureFlagsConfigInMetadata(BaseTest):
+ """TeamFeatureFlagsConfig values are derived separately from TEAM_METADATA_FIELDS."""
def test_defaults_to_false_for_ungated_team(self):
from posthog.storage.team_metadata_cache import _serialize_team_to_metadata
@@ -464,21 +459,29 @@ class TestMinimalFlagCalledEventsInMetadata(BaseTest):
metadata = _serialize_team_to_metadata(self.team)
self.assertIs(metadata["minimal_flag_called_events"], False)
+ self.assertEqual(metadata["property_matching_version"], 1)
def test_reflects_gated_config_row(self):
from posthog.storage.team_metadata_cache import _serialize_team_to_metadata
- TeamFeatureFlagsConfig.objects.update_or_create(team=self.team, defaults={"minimal_flag_called_events": True})
+ TeamFeatureFlagsConfig.objects.update_or_create(
+ team=self.team,
+ defaults={"minimal_flag_called_events": True, "property_matching_version": 2},
+ )
metadata = _serialize_team_to_metadata(self.team)
self.assertIs(metadata["minimal_flag_called_events"], True)
+ self.assertEqual(metadata["property_matching_version"], 2)
def test_batch_load_matches_single_team_load(self):
from posthog.storage.team_metadata_cache import _batch_load_team_metadata, _serialize_team_to_metadata
gated_team = self.organization.teams.create(name="Gated team")
- TeamFeatureFlagsConfig.objects.update_or_create(team=gated_team, defaults={"minimal_flag_called_events": True})
+ TeamFeatureFlagsConfig.objects.update_or_create(
+ team=gated_team,
+ defaults={"minimal_flag_called_events": True, "property_matching_version": 2},
+ )
ungated_team = self.organization.teams.create(name="Ungated team")
batch_result = _batch_load_team_metadata([gated_team, ungated_team])
@@ -492,7 +495,9 @@ class TestMinimalFlagCalledEventsInMetadata(BaseTest):
_serialize_team_to_metadata(ungated_team)["minimal_flag_called_events"],
)
self.assertIs(batch_result[gated_team.id]["minimal_flag_called_events"], True)
+ self.assertEqual(batch_result[gated_team.id]["property_matching_version"], 2)
self.assertIs(batch_result[ungated_team.id]["minimal_flag_called_events"], False)
+ self.assertEqual(batch_result[ungated_team.id]["property_matching_version"], 1)
@override_settings(FLAGS_REDIS_URL="redis://test:6379/0")
diff --git a/products/feature_flags/backend/api/staff_team_config.py b/products/feature_flags/backend/api/staff_team_config.py
index 5c81490ea32c..66384dcc0531 100644
--- a/products/feature_flags/backend/api/staff_team_config.py
+++ b/products/feature_flags/backend/api/staff_team_config.py
@@ -24,6 +24,7 @@ from products.feature_flags.backend.flag_limits import (
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.team_feature_flags_config import (
MAX_FEATURE_FLAGS_OVERRIDE_CEILING,
+ PropertyMatchingVersion,
TeamFeatureFlagsConfig,
)
@@ -34,13 +35,14 @@ logger = structlog.get_logger(__name__)
# value today by coincidence, not by requirement.
MAX_TEAM_IDS_PER_QUERY = 50
-MUTABLE_SETTINGS = ("minimal_flag_called_events", "max_feature_flags_override")
+MUTABLE_SETTINGS = ("minimal_flag_called_events", "property_matching_version", "max_feature_flags_override")
def _config_row(
*,
team_id: int,
minimal_flag_called_events: bool,
+ property_matching_version: int,
max_feature_flags_override: int | None,
feature_flag_count: int,
) -> dict[str, Any]:
@@ -48,6 +50,7 @@ def _config_row(
return {
"team_id": team_id,
"minimal_flag_called_events": minimal_flag_called_events,
+ "property_matching_version": property_matching_version,
"max_feature_flags_override": max_feature_flags_override,
"effective_max_feature_flags": resolve_max_feature_flags(max_feature_flags_override),
"feature_flag_count": feature_flag_count,
@@ -70,6 +73,10 @@ class StaffTeamConfigSerializer(serializers.Serializer):
"(omitting fields only needed for experiments) instead of the full legacy shape."
)
)
+ property_matching_version = serializers.ChoiceField(
+ choices=PropertyMatchingVersion.choices,
+ help_text="Property matching semantics used by /flags, local evaluation, and cohort generation.",
+ )
max_feature_flags_override = serializers.IntegerField(
allow_null=True,
help_text=(
@@ -106,6 +113,15 @@ class StaffTeamConfigMutationSerializer(serializers.Serializer):
"$feature_flag_called event shape."
),
)
+ property_matching_version = serializers.ChoiceField(
+ choices=PropertyMatchingVersion.choices,
+ required=False,
+ help_text=(
+ "New property matching version for the team. Version 1 preserves legacy behavior. "
+ "Version 2 uses explicit scalar and array equality. Only set version 2 after confirming "
+ "that the team's local-evaluation SDK versions support it. Omit to leave it unchanged."
+ ),
+ )
max_feature_flags_override = serializers.IntegerField(
required=False,
allow_null=True,
@@ -126,13 +142,12 @@ class StaffTeamConfigMutationSerializer(serializers.Serializer):
class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):
"""
- Staff-only, unscoped read/write for TeamFeatureFlagsConfig: the minimal_flag_called_events
- rollout gate and the per-team feature-flag count override.
+ Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and the
+ per-team feature-flag count override.
- Single-team writes only, by design. minimal_flag_called_events is flipped one team at a time
- after staff verify that team's SDK versions support the slim $feature_flag_called event shape,
- and max_feature_flags_override is a per-customer capacity grant. Neither is a bulk operation,
- unlike the cache tools' rebuild and clear.
+ Single-team writes only, by design. Rollout settings are changed after staff verify SDK
+ compatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a
+ bulk operation, unlike the cache tools' rebuild and clear.
set() takes partial updates: omit a setting to leave it unchanged, and send
max_feature_flags_override as null to clear the override.
@@ -170,8 +185,8 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):
for team_id, parent_team_id in Team.objects.filter(id__in=team_ids).values_list("id", "parent_team_id")
}
root_team_ids = set(root_team_id_by_team_id.values())
- # minimal_flag_called_events stays per-team (the Rust and nodejs readers key on the
- # literal team), so it is read from each team's own row; the override is read from the root.
+ # Behavior rollouts stay per-team because evaluation readers key on the literal team, so
+ # they come from each team's row. The capacity override comes from the project root.
config_by_team_id = TeamFeatureFlagsConfig.objects.in_bulk(team_ids)
override_by_root_team_id = dict(
TeamFeatureFlagsConfig.objects.filter(team_id__in=root_team_ids).values_list(
@@ -200,6 +215,7 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):
_config_row(
team_id=team_id,
minimal_flag_called_events=config.minimal_flag_called_events,
+ property_matching_version=config.property_matching_version,
max_feature_flags_override=override_by_root_team_id.get(root_team_id),
feature_flag_count=flag_count_by_root_team_id.get(root_team_id, 0),
)
@@ -221,8 +237,8 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):
# The limit is enforced against the project's whole flag set, and get_max_feature_flags_for_team
# reads the override off the project root, so a row written here would never be read.
- # minimal_flag_called_events stays per-team (the Rust and nodejs readers key on the literal
- # team), which is why only the override is refused rather than the whole request.
+ # Behavior rollouts stay per-team because evaluation readers key on the literal team. This
+ # is why only the capacity override is refused rather than the whole request.
if "max_feature_flags_override" in validated and team.parent_team_id is not None:
raise serializers.ValidationError(
f"Team {team_id} is an environment of project {team.parent_team_id}. Set the flag limit on "
@@ -231,6 +247,7 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):
config = get_or_create_team_extension(team, TeamFeatureFlagsConfig)
old_minimal_flag_called_events = config.minimal_flag_called_events
+ old_property_matching_version = config.property_matching_version
old_max_feature_flags_override = config.max_feature_flags_override
# Saving only the fields actually sent keeps two staff editing different settings on the
@@ -240,7 +257,7 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):
setattr(config, setting, validated[setting])
config.save(update_fields=update_fields)
- if "minimal_flag_called_events" in validated:
+ if {"minimal_flag_called_events", "property_matching_version"} & validated.keys():
# posthog.tasks.team_metadata sits under posthog.tasks, whose __init__ is a celery
# autoimport aggregator that pulls in every task module — keep that off the API
# router's import path by deferring it to call time. The local tasks module is
@@ -262,6 +279,9 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):
if "minimal_flag_called_events" in validated:
changed_values["old_value"] = old_minimal_flag_called_events
changed_values["new_value"] = config.minimal_flag_called_events
+ if "property_matching_version" in validated:
+ changed_values["old_property_matching_version"] = old_property_matching_version
+ changed_values["new_property_matching_version"] = config.property_matching_version
if "max_feature_flags_override" in validated:
changed_values["old_max_feature_flags_override"] = old_max_feature_flags_override
changed_values["new_max_feature_flags_override"] = config.max_feature_flags_override
@@ -276,12 +296,13 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):
)
# The row has to show the root's override, matching list() and the validator. A root team's
- # own config is already that, and an environment team reaches here only on a
- # minimal_flag_called_events-only edit, since the override write is refused above.
+ # own config is already that, and an environment team reaches here only for rollout edits,
+ # since the override write is refused above.
return response.Response(
_config_row(
team_id=team.id,
minimal_flag_called_events=config.minimal_flag_called_events,
+ property_matching_version=config.property_matching_version,
max_feature_flags_override=(
config.max_feature_flags_override
if team.parent_team_id is None
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index 65a15f1b236b..29787648e514 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -1068,17 +1068,10 @@
# ---
# name: TestFeatureFlag.test_creating_static_cohort.19
'''
- SELECT 1 AS "a"
- FROM "posthog_cohort"
- INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")
- WHERE (("posthog_cohort"."team_id" =
- (SELECT U0."parent_team_id" AS "parent_team_id"
- FROM "posthog_team" U0
- WHERE U0."id" = 99999
- LIMIT 1)
- OR ("posthog_team"."parent_team_id" IS NULL
- AND "posthog_cohort"."team_id" = 99999))
- AND "posthog_cohort"."id" = 99999)
+ SELECT "feature_flags_teamfeatureflagsconfig"."property_matching_version" AS "property_matching_version"
+ FROM "feature_flags_teamfeatureflagsconfig"
+ WHERE "feature_flags_teamfeatureflagsconfig"."team_id" = 99999
+ ORDER BY "feature_flags_teamfeatureflagsconfig"."team_id" ASC
LIMIT 1
'''
# ---
@@ -1226,6 +1219,22 @@
'''
# ---
# name: TestFeatureFlag.test_creating_static_cohort.20
+ '''
+ SELECT 1 AS "a"
+ FROM "posthog_cohort"
+ INNER JOIN "posthog_team" ON ("posthog_cohort"."team_id" = "posthog_team"."id")
+ WHERE (("posthog_cohort"."team_id" =
+ (SELECT U0."parent_team_id" AS "parent_team_id"
+ FROM "posthog_team" U0
+ WHERE U0."id" = 99999
+ LIMIT 1)
+ OR ("posthog_team"."parent_team_id" IS NULL
+ AND "posthog_cohort"."team_id" = 99999))
+ AND "posthog_cohort"."id" = 99999)
+ LIMIT 1
+ '''
+# ---
+# name: TestFeatureFlag.test_creating_static_cohort.21
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1327,7 +1336,7 @@
LIMIT 21
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.21
+# name: TestFeatureFlag.test_creating_static_cohort.22
'''
SELECT "posthog_filesystem"."team_id",
"posthog_filesystem"."id",
@@ -1352,7 +1361,7 @@
AND "posthog_filesystem"."shortcut" IS NOT NULL))
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.22
+# name: TestFeatureFlag.test_creating_static_cohort.23
'''
SELECT "posthog_filesystemshortcut"."id",
"posthog_filesystemshortcut"."team_id",
@@ -1375,7 +1384,7 @@
AND "posthog_filesystemshortcut"."href" IS NOT NULL))
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.23
+# name: TestFeatureFlag.test_creating_static_cohort.24
'''
SELECT "posthog_cohort"."id",
"posthog_cohort"."name",
@@ -1412,7 +1421,7 @@
LIMIT 21
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.24
+# name: TestFeatureFlag.test_creating_static_cohort.25
'''
SELECT "posthog_team"."id",
"posthog_team"."uuid",
@@ -1514,7 +1523,7 @@
LIMIT 21
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.25
+# name: TestFeatureFlag.test_creating_static_cohort.26
'''
SELECT "posthog_user"."id",
"posthog_user"."password",
@@ -1561,7 +1570,7 @@
LIMIT 21
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.26
+# name: TestFeatureFlag.test_creating_static_cohort.27
'''
SELECT "posthog_cohortcalculationhistory"."id",
"posthog_cohortcalculationhistory"."team_id",
@@ -1582,7 +1591,7 @@
LIMIT 1
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.27
+# name: TestFeatureFlag.test_creating_static_cohort.28
'''
SELECT "posthog_experiment"."id",
"posthog_experiment"."name",
@@ -1624,7 +1633,7 @@
WHERE "posthog_experiment"."exposure_cohort_id" = 99999
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.28
+# name: TestFeatureFlag.test_creating_static_cohort.29
'''
/* user_id:0 celery:posthog.tasks.calculate_cohort.insert_cohort_from_feature_flag */
SELECT person_id
@@ -1635,7 +1644,21 @@
GROUP BY person_id
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.29
+# name: TestFeatureFlag.test_creating_static_cohort.3
+ '''
+ SELECT "posthog_project"."updated_at",
+ "posthog_project"."id",
+ "posthog_project"."organization_id",
+ "posthog_project"."name",
+ "posthog_project"."created_at",
+ "posthog_project"."product_description",
+ "posthog_project"."is_pending_deletion"
+ FROM "posthog_project"
+ WHERE "posthog_project"."id" = 99999
+ LIMIT 21
+ '''
+# ---
+# name: TestFeatureFlag.test_creating_static_cohort.30
'''
/* user_id:0 request:_snapshot_ */
SELECT persons.id AS id
@@ -1675,20 +1698,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestFeatureFlag.test_creating_static_cohort.3
- '''
- SELECT "posthog_project"."updated_at",
- "posthog_project"."id",
- "posthog_project"."organization_id",
- "posthog_project"."name",
- "posthog_project"."created_at",
- "posthog_project"."product_description",
- "posthog_project"."is_pending_deletion"
- FROM "posthog_project"
- WHERE "posthog_project"."id" = 99999
- LIMIT 21
- '''
-# ---
# name: TestFeatureFlag.test_creating_static_cohort.4
'''
SELECT "posthog_organizationmembership"."id",
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 65e73b8a329e..683ca9071cea 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -32,7 +32,7 @@ from posthog.hogql.database.database import Database
from posthog import redis
from posthog.api.cohort import BATCH_FLAG_EVALUATION_PAGE_ATTEMPTS, get_cohort_actors_for_feature_flag
-from posthog.api.services.flags_service import FlagVersionConflictError
+from posthog.api.services.flags_service import FlagVersionConflictError, PropertyMatchingVersionConflictError
from posthog.constants import AvailableFeature
from posthog.models import TaggedItem, User
from posthog.models.group.util import create_group, raw_create_group_ch
@@ -9067,6 +9067,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
project_id=self.team.project_id,
flag_key="some-feature",
expected_version=1,
+ expected_property_matching_version=1,
cursor=0,
limit=1_000,
)
@@ -9098,6 +9099,7 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
@patch("posthog.api.cohort.batch_evaluate_flag_for_team")
def test_cursor_loop_advances_and_terminates(self, mock_batch_evaluate):
self._create_flag()
+ TeamFeatureFlagsConfig.objects.filter(team=self.team).update(property_matching_version=2)
persons = [
_create_person(team=self.team, distinct_ids=[f"person{i}"], properties={"key": "value"}, immediate=True)
for i in range(3)
@@ -9118,6 +9120,10 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(cursors, [0, 100, 200])
limits = {call.kwargs["limit"] for call in mock_batch_evaluate.call_args_list}
self.assertEqual(limits, {2})
+ matching_versions = {
+ call.kwargs["expected_property_matching_version"] for call in mock_batch_evaluate.call_args_list
+ }
+ self.assertEqual(matching_versions, {2})
cohort.refresh_from_db()
self.assertEqual(cohort.count, 3)
@@ -9193,15 +9199,26 @@ class TestCohortGenerationForFeatureFlag(APIBaseTest, ClickhouseTestMixin):
assert history.error is not None
self.assertNotIn("connection refused", history.error)
+ @parameterized.expand(
+ [
+ ("flag_version", FlagVersionConflictError("flag changed during cohort generation")),
+ (
+ "property_matching_version",
+ PropertyMatchingVersionConflictError("matching changed during cohort generation"),
+ ),
+ ]
+ )
@patch("posthog.api.cohort.time.sleep")
@patch("posthog.api.cohort.batch_evaluate_flag_for_team")
- def test_version_conflict_is_not_retried_and_surfaces_user_facing_error(self, mock_batch_evaluate, mock_sleep):
+ def test_pinned_input_conflict_is_not_retried_and_surfaces_user_facing_error(
+ self, _name, conflict, mock_batch_evaluate, mock_sleep
+ ):
self._create_flag()
cohort = self._create_static_cohort()
- mock_batch_evaluate.side_effect = FlagVersionConflictError("flag changed during cohort generation")
+ mock_batch_evaluate.side_effect = conflict
- with self.assertRaises(FlagVersionConflictError):
+ with self.assertRaises(type(conflict)):
get_cohort_actors_for_feature_flag(cohort.pk, "some-feature", self.team.pk)
# Permanent error: no retries
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index 9c72ea1c84d9..eaf507c18385 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -60,7 +60,10 @@ from products.feature_flags.backend.flags_cache import (
)
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag
-from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfig
+from products.feature_flags.backend.models.team_feature_flags_config import (
+ PropertyMatchingVersion,
+ TeamFeatureFlagsConfig,
+)
from products.feature_flags.backend.types import FlagFilters, FlagProperty, PropertyFilterType
from products.surveys.backend.models import Survey
@@ -549,12 +552,14 @@ def _local_eval_response(
group_type_mapping: dict[str, str],
cohorts: dict[str, Any],
minimal_flag_called_events: bool,
+ property_matching_version: int,
) -> dict[str, Any]:
return {
"flags": flags,
"group_type_mapping": group_type_mapping,
"cohorts": cohorts,
"minimal_flag_called_events": minimal_flag_called_events,
+ "property_matching_version": property_matching_version,
}
@@ -563,7 +568,13 @@ def _get_flags_response_for_local_evaluation(team: Team) -> dict[str, Any]:
results = _get_flags_response_for_local_evaluation_batch([team])
return results.get(
team.id,
- _local_eval_response(flags=[], group_type_mapping={}, cohorts={}, minimal_flag_called_events=False),
+ _local_eval_response(
+ flags=[],
+ group_type_mapping={},
+ cohorts={},
+ minimal_flag_called_events=False,
+ property_matching_version=PropertyMatchingVersion.LEGACY,
+ ),
)
@@ -584,15 +595,16 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in
team_by_id = {t.id: t for t in teams}
project_ids = list({t.project_id for t in teams})
- # Slim $feature_flag_called gate, exposed top-level so local-eval SDKs (which never
- # call /flags) get the same signal FlagsResponse.minimal_flag_called_events carries.
- # Absent row → False → SDKs send full events, same fail-safe as the /flags path.
- minimal_flag_called_events_by_team: defaultdict[int, bool] = defaultdict(
- bool,
- TeamFeatureFlagsConfig.objects.db_manager(DATABASE_FOR_LOCAL_EVALUATION)
+ # Local-evaluation SDKs never call /flags, so team rollout settings must travel in
+ # this blob. Missing config rows retain both legacy behaviors.
+ team_config_by_team_id = {
+ team_id: (minimal_flag_called_events, property_matching_version)
+ for team_id, minimal_flag_called_events, property_matching_version in TeamFeatureFlagsConfig.objects.db_manager(
+ DATABASE_FOR_LOCAL_EVALUATION
+ )
.filter(team_id__in=team_ids)
- .values_list("team_id", "minimal_flag_called_events"),
- )
+ .values_list("team_id", "minimal_flag_called_events", "property_matching_version")
+ }
# Bulk load survey flag IDs across all teams
survey_flag_ids: set[int] = set()
@@ -722,11 +734,15 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in
FLAG_PROCESSING_ERROR_COUNTER.inc()
continue
+ minimal_flag_called_events, property_matching_version = team_config_by_team_id.get(
+ tid, (False, PropertyMatchingVersion.LEGACY)
+ )
response_data = _local_eval_response(
flags=flags_data,
group_type_mapping=gtm_by_project.get(team.project_id, {}),
cohorts=cohorts,
- minimal_flag_called_events=minimal_flag_called_events_by_team[tid],
+ minimal_flag_called_events=minimal_flag_called_events,
+ property_matching_version=property_matching_version,
)
results[tid] = _apply_flag_dependency_transformation(response_data, flag_id_to_key)
@@ -734,11 +750,15 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in
# Ensure every requested team has a result, even if it had no flags
for tid in team_ids:
if tid not in results:
+ minimal_flag_called_events, property_matching_version = team_config_by_team_id.get(
+ tid, (False, PropertyMatchingVersion.LEGACY)
+ )
results[tid] = _local_eval_response(
flags=[],
group_type_mapping=gtm_by_project.get(team_by_id[tid].project_id, {}),
cohorts={},
- minimal_flag_called_events=minimal_flag_called_events_by_team[tid],
+ minimal_flag_called_events=minimal_flag_called_events,
+ property_matching_version=property_matching_version,
)
return results
@@ -784,6 +804,7 @@ _TOP_LEVEL_FIELDS_TO_COMPARE: list[tuple[str, str, Any]] = [
("cohorts", "COHORTS_MISMATCH", None),
("group_type_mapping", "GROUP_TYPE_MAPPING_MISMATCH", None),
("minimal_flag_called_events", "MINIMAL_FLAG_CALLED_EVENTS_MISMATCH", False),
+ ("property_matching_version", "PROPERTY_MATCHING_VERSION_MISMATCH", PropertyMatchingVersion.LEGACY),
]
diff --git a/products/feature_flags/backend/migrations/0017_teamfeatureflagsconfig_property_matching_version.py b/products/feature_flags/backend/migrations/0017_teamfeatureflagsconfig_property_matching_version.py
new file mode 100644
index 000000000000..61942599687d
--- /dev/null
+++ b/products/feature_flags/backend/migrations/0017_teamfeatureflagsconfig_property_matching_version.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.17 on 2026-09-04 10:30
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("feature_flags", "0016_teamfeatureflagpolicyconfig"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="teamfeatureflagsconfig",
+ name="property_matching_version",
+ field=models.SmallIntegerField(
+ choices=[(1, "Legacy"), (2, "Explicit")],
+ db_default=1,
+ default=1,
+ ),
+ ),
+ ]
diff --git a/products/feature_flags/backend/migrations/max_migration.txt b/products/feature_flags/backend/migrations/max_migration.txt
index ee240fa25047..4e739ff04cf2 100644
--- a/products/feature_flags/backend/migrations/max_migration.txt
+++ b/products/feature_flags/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0016_teamfeatureflagpolicyconfig
+0017_teamfeatureflagsconfig_property_matching_version
diff --git a/products/feature_flags/backend/models/team_feature_flags_config.py b/products/feature_flags/backend/models/team_feature_flags_config.py
index 664a14fd6af8..a0fb4a665f0f 100644
--- a/products/feature_flags/backend/models/team_feature_flags_config.py
+++ b/products/feature_flags/backend/models/team_feature_flags_config.py
@@ -19,6 +19,11 @@ logger = logging.getLogger(__name__)
MAX_FEATURE_FLAGS_OVERRIDE_CEILING = 20_000
+class PropertyMatchingVersion(models.IntegerChoices):
+ LEGACY = 1, "Legacy"
+ EXPLICIT = 2, "Explicit"
+
+
class TeamFeatureFlagsConfig(models.Model):
"""Internal-only team-level feature flags settings, written by staff and never by customers.
@@ -26,9 +31,8 @@ class TeamFeatureFlagsConfig(models.Model):
It holds server-controlled behavior rollouts and staff-granted limit overrides, not
customer-editable preferences. The staff-only feature-flags-staff API
(products/feature_flags/backend/api/staff_team_config.py, gated by IsStaffUser) is the only
- interactive write surface: it flips minimal_flag_called_events one team at a time after staff
- manually verify that team's SDK versions support the slim event shape, and it grants per-team
- flag-count overrides.
+ interactive write surface: it changes SDK-facing behavior one team at a time after staff
+ verify compatible SDK versions, and it grants per-team flag-count overrides.
Sanctioned writers: the team-creation signal below, get_or_create_team_extension, the
staff-only feature-flags-staff API (gated by IsStaffUser), and management commands.
"""
@@ -44,6 +48,14 @@ class TeamFeatureFlagsConfig(models.Model):
# management command.
minimal_flag_called_events = models.BooleanField(default=False)
+ # Version 1 preserves released SDK behavior. Version 2 uses explicit scalar and array
+ # equality semantics. The database default protects older writers during rolling deploys.
+ property_matching_version = models.SmallIntegerField(
+ choices=PropertyMatchingVersion,
+ default=PropertyMatchingVersion.LEGACY,
+ db_default=PropertyMatchingVersion.LEGACY,
+ )
+
# Raises or lowers this team's flag-count cap. Null means no override, falling back to the
# global settings.MAX_FEATURE_FLAGS_PER_TEAM. Resolved by
# products/feature_flags/backend/flag_limits.py, and read only when a flag is created.
diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.py
index 7fe1ebc37d41..457db49bbcd2 100644
--- a/products/feature_flags/backend/test/test_local_evaluation.py
+++ b/products/feature_flags/backend/test/test_local_evaluation.py
@@ -183,6 +183,7 @@ class TestLocalEvaluationCache(BaseTest):
assert len(response.get("flags", [])) == 2
assert response.get("group_type_mapping", {}) == {"0": "organization"}
assert len(response.get("cohorts", {})) == 2
+ assert response.get("property_matching_version") == 1
def test_get_flags_cache_hot(self):
update_flag_caches(self.team)
@@ -971,18 +972,20 @@ class TestLocalEvaluationBatch(BaseTest):
assert "group_type_mapping" in results[team_without_flags.id]
assert "cohorts" in results[team_without_flags.id]
- def test_batch_includes_minimal_flag_called_events_gate(self):
- # Local-eval SDKs never call /flags, so the blob is their only source of the slim
- # $feature_flag_called gate. Catches the key being dropped from the payload, a gated
- # team reading False, or an ungated/legacy team (no config row) reading anything but
- # False — including on the no-flags fallback path.
+ def test_batch_includes_team_rollout_settings(self):
+ # Local-eval SDKs never call /flags, so the blob is their only source of team rollout
+ # settings. This covers configured, default, and no-flags response paths.
gated_team = self._create_team_with_project("Gated")
gated_team_no_flags = self._create_team_with_project("Gated no flags")
ungated_team = self._create_team_with_project("Ungated")
- TeamFeatureFlagsConfig.objects.update_or_create(team=gated_team, defaults={"minimal_flag_called_events": True})
TeamFeatureFlagsConfig.objects.update_or_create(
- team=gated_team_no_flags, defaults={"minimal_flag_called_events": True}
+ team=gated_team,
+ defaults={"minimal_flag_called_events": True, "property_matching_version": 2},
+ )
+ TeamFeatureFlagsConfig.objects.update_or_create(
+ team=gated_team_no_flags,
+ defaults={"minimal_flag_called_events": True, "property_matching_version": 2},
)
TeamFeatureFlagsConfig.objects.filter(team=ungated_team).delete()
@@ -995,12 +998,12 @@ class TestLocalEvaluationBatch(BaseTest):
results = _get_flags_response_for_local_evaluation_batch([gated_team, gated_team_no_flags, ungated_team])
assert results[gated_team.id]["minimal_flag_called_events"] is True
- # Gated team with no flags hits the no-flags fallback path, not the main response path.
- # Without this case, a fallback that hardcodes False instead of threading the gate would
- # pass unnoticed, since the ungated team's expected False is indistinguishable from that.
+ assert results[gated_team.id]["property_matching_version"] == 2
assert results[gated_team_no_flags.id]["flags"] == []
assert results[gated_team_no_flags.id]["minimal_flag_called_events"] is True
+ assert results[gated_team_no_flags.id]["property_matching_version"] == 2
assert results[ungated_team.id]["minimal_flag_called_events"] is False
+ assert results[ungated_team.id]["property_matching_version"] == 1
def test_batch_team_with_no_flags_includes_group_type_mapping(self):
team = self._create_team_with_project("GTM Team")
diff --git a/products/feature_flags/backend/test/test_staff_team_config_api.py b/products/feature_flags/backend/test/test_staff_team_config_api.py
index 950e455dad91..bef69c689783 100644
--- a/products/feature_flags/backend/test/test_staff_team_config_api.py
+++ b/products/feature_flags/backend/test/test_staff_team_config_api.py
@@ -16,6 +16,7 @@ from products.feature_flags.backend.api.staff_team_config import (
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.team_feature_flags_config import (
MAX_FEATURE_FLAGS_OVERRIDE_CEILING,
+ PropertyMatchingVersion,
TeamFeatureFlagsConfig,
)
@@ -50,8 +51,11 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):
other_team = Team.objects.create(organization=self.organization, name="Other team")
config = get_or_create_team_extension(other_team, TeamFeatureFlagsConfig)
config.minimal_flag_called_events = True
+ config.property_matching_version = PropertyMatchingVersion.EXPLICIT
config.max_feature_flags_override = 5000
- config.save(update_fields=["minimal_flag_called_events", "max_feature_flags_override"])
+ config.save(
+ update_fields=["minimal_flag_called_events", "property_matching_version", "max_feature_flags_override"]
+ )
FeatureFlag.objects.create(team=other_team, created_by=self.user, key="other-1", filters={"groups": []})
FeatureFlag.objects.create(team=other_team, created_by=self.user, key="other-2", filters={"groups": []})
@@ -62,6 +66,7 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):
results = {
row["team_id"]: (
row["minimal_flag_called_events"],
+ row["property_matching_version"],
row["max_feature_flags_override"],
row["effective_max_feature_flags"],
row["feature_flag_count"],
@@ -75,8 +80,8 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):
self.assertEqual(
results,
{
- self.team.id: (False, None, 2000, 0),
- other_team.id: (True, 5000, 5000, 2),
+ self.team.id: (False, 1, None, 2000, 0),
+ other_team.id: (True, 2, 5000, 5000, 2),
},
)
@@ -94,6 +99,7 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):
{
"team_id": self.team.id,
"minimal_flag_called_events": False,
+ "property_matching_version": 1,
"max_feature_flags_override": None,
"effective_max_feature_flags": 2000,
"feature_flag_count": 0,
@@ -128,6 +134,7 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):
{
"team_id": self.team.id,
"minimal_flag_called_events": new_value,
+ "property_matching_version": 1,
"max_feature_flags_override": None,
"effective_max_feature_flags": 2000,
"feature_flag_count": 0,
@@ -142,6 +149,21 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):
mock_metadata_task.delay.assert_called_once_with(self.team.id)
mock_flags_task.delay.assert_called_once_with(self.team.id)
+ def test_set_updates_property_matching_version_and_enqueues_cache_refresh_tasks(self):
+ with (
+ patch("posthog.tasks.team_metadata.update_team_metadata_cache_task") as mock_metadata_task,
+ patch("products.feature_flags.backend.tasks.update_team_flags_cache") as mock_flags_task,
+ ):
+ response = self.client.post(
+ SET_URL, {"team_id": self.team.id, "property_matching_version": 2}, format="json"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["property_matching_version"], 2)
+ self.assertEqual(TeamFeatureFlagsConfig.objects.get(team=self.team).property_matching_version, 2)
+ mock_metadata_task.delay.assert_called_once_with(self.team.id)
+ mock_flags_task.delay.assert_called_once_with(self.team.id)
+
def test_set_returns_404_for_unknown_team(self):
missing_id = self.team.id + 9999
response = self.client.post(SET_URL, {"team_id": missing_id, "minimal_flag_called_events": True}, format="json")
@@ -340,6 +362,11 @@ class TestStaffTeamConfigMutationSerializerBounds(SimpleTestCase):
@parameterized.expand(
[
("zero_rejected", {"team_id": 1, "max_feature_flags_override": 0}, "max_feature_flags_override"),
+ (
+ "unknown_matching_version_rejected",
+ {"team_id": 1, "property_matching_version": 3},
+ "property_matching_version",
+ ),
(
"above_ceiling_rejected",
{"team_id": 1, "max_feature_flags_override": MAX_FEATURE_FLAGS_OVERRIDE_CEILING + 1},
diff --git a/products/feature_flags/backend/test/test_team_feature_flags_config.py b/products/feature_flags/backend/test/test_team_feature_flags_config.py
index c3aa6ccd7559..cd8bfad99eda 100644
--- a/products/feature_flags/backend/test/test_team_feature_flags_config.py
+++ b/products/feature_flags/backend/test/test_team_feature_flags_config.py
@@ -17,6 +17,7 @@ class TestTeamFeatureFlagsConfig(BaseTest):
config = TeamFeatureFlagsConfig.objects.get(team=team)
self.assertFalse(config.minimal_flag_called_events)
+ self.assertEqual(config.property_matching_version, 1)
def test_lazily_created_config_defaults_to_disabled(self):
# A team without a row models a legacy team predating this extension.
@@ -24,6 +25,7 @@ class TestTeamFeatureFlagsConfig(BaseTest):
config = get_or_create_team_extension(self.team, TeamFeatureFlagsConfig)
self.assertFalse(config.minimal_flag_called_events)
+ self.assertEqual(config.property_matching_version, 1)
@parameterized.expand(
[
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 5a62b79ab7ef..4960462989e4 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -172,11 +172,28 @@ export interface StaffWarmRunCancelResponseApi {
cancel_requested: boolean
}
+/**
+ * * `1` - Legacy
+ * * `2` - Explicit
+ */
+export type PropertyMatchingVersionEnumApi =
+ (typeof PropertyMatchingVersionEnumApi)[keyof typeof PropertyMatchingVersionEnumApi]
+
+export const PropertyMatchingVersionEnumApi = {
+ Number1: 1,
+ Number2: 2,
+} as const
+
export interface StaffTeamConfigApi {
/** Team id. */
team_id: number
/** Whether this team's SDKs receive the slim $feature_flag_called event shape (omitting fields only needed for experiments) instead of the full legacy shape. */
minimal_flag_called_events: boolean
+ /** Property matching semantics used by /flags, local evaluation, and cohort generation.
+ *
+ * * `1` - Legacy
+ * * `2` - Explicit */
+ property_matching_version: PropertyMatchingVersionEnumApi
/**
* Per-team override for the maximum number of feature flags this team may create, or null when the team uses the global default.
* @nullable
@@ -198,6 +215,11 @@ export interface StaffTeamConfigMutationApi {
team_id: number
/** New value for the team's minimal_flag_called_events setting. Omit to leave it unchanged. Only set true after confirming that team's SDK versions support the slim $feature_flag_called event shape. */
minimal_flag_called_events?: boolean
+ /** New property matching version for the team. Version 1 preserves legacy behavior. Version 2 uses explicit scalar and array equality. Only set version 2 after confirming that the team's local-evaluation SDK versions support it. Omit to leave it unchanged.
+ *
+ * * `1` - Legacy
+ * * `2` - Explicit */
+ property_matching_version?: PropertyMatchingVersionEnumApi
/**
* New per-team flag-count limit (1-20,000). Send null to clear the override so the team falls back to the global default. Omit to leave it unchanged.
* @minimum 1
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index e761bfa9614b..da48d809f581 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -259,13 +259,12 @@ export const getFeatureFlagsStaffTeamConfigListUrl = (params: FeatureFlagsStaffT
}
/**
- * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: the minimal_flag_called_events
- * rollout gate and the per-team feature-flag count override.
+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and the
+ * per-team feature-flag count override.
*
- * Single-team writes only, by design. minimal_flag_called_events is flipped one team at a time
- * after staff verify that team's SDK versions support the slim $feature_flag_called event shape,
- * and max_feature_flags_override is a per-customer capacity grant. Neither is a bulk operation,
- * unlike the cache tools' rebuild and clear.
+ * Single-team writes only, by design. Rollout settings are changed after staff verify SDK
+ * compatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a
+ * bulk operation, unlike the cache tools' rebuild and clear.
*
* set() takes partial updates: omit a setting to leave it unchanged, and send
* max_feature_flags_override as null to clear the override.
@@ -288,13 +287,12 @@ export const getFeatureFlagsStaffTeamConfigSetCreateUrl = () => {
}
/**
- * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: the minimal_flag_called_events
- * rollout gate and the per-team feature-flag count override.
+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and the
+ * per-team feature-flag count override.
*
- * Single-team writes only, by design. minimal_flag_called_events is flipped one team at a time
- * after staff verify that team's SDK versions support the slim $feature_flag_called event shape,
- * and max_feature_flags_override is a per-customer capacity grant. Neither is a bulk operation,
- * unlike the cache tools' rebuild and clear.
+ * Single-team writes only, by design. Rollout settings are changed after staff verify SDK
+ * compatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a
+ * bulk operation, unlike the cache tools' rebuild and clear.
*
* set() takes partial updates: omit a setting to leave it unchanged, and send
* max_feature_flags_override as null to clear the override.
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index b0bb706647f2..f9e81dd265ee 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -68,13 +68,12 @@ export const FeatureFlagsStaffCacheRebuildCreateBody = /* @__PURE__ */ zod.objec
})
/**
- * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: the minimal_flag_called_events
- * rollout gate and the per-team feature-flag count override.
+ * Staff-only, unscoped read/write for TeamFeatureFlagsConfig: behavior rollout gates and the
+ * per-team feature-flag count override.
*
- * Single-team writes only, by design. minimal_flag_called_events is flipped one team at a time
- * after staff verify that team's SDK versions support the slim $feature_flag_called event shape,
- * and max_feature_flags_override is a per-customer capacity grant. Neither is a bulk operation,
- * unlike the cache tools' rebuild and clear.
+ * Single-team writes only, by design. Rollout settings are changed after staff verify SDK
+ * compatibility, and max_feature_flags_override is a per-customer capacity grant. Neither is a
+ * bulk operation, unlike the cache tools' rebuild and clear.
*
* set() takes partial updates: omit a setting to leave it unchanged, and send
* max_feature_flags_override as null to clear the override.
@@ -92,6 +91,13 @@ export const FeatureFlagsStaffTeamConfigSetCreateBody = /* @__PURE__ */ zod.obje
.describe(
"New value for the team's minimal_flag_called_events setting. Omit to leave it unchanged. Only set true after confirming that team's SDK versions support the slim $feature_flag_called event shape."
),
+ property_matching_version: zod
+ .union([zod.literal(1), zod.literal(2)])
+ .describe('\* `1` - Legacy\n\* `2` - Explicit')
+ .optional()
+ .describe(
+ "New property matching version for the team. Version 1 preserves legacy behavior. Version 2 uses explicit scalar and array equality. Only set version 2 after confirming that the team's local-evaluation SDK versions support it. Omit to leave it unchanged.\n\n\* `1` - Legacy\n\* `2` - Explicit"
+ ),
max_feature_flags_override: zod
.number()
.min(1)
diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rs
index 5fe0c508bdee..f2ae90305c24 100644
--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs
+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs
@@ -8,8 +8,8 @@
//!
//! Deliberate differences from the live `/flags` pipeline:
//! - Auth is the `INTERNAL_REQUEST_TOKEN` bearer token only — no SDK token, no team lookup
-//! by token. The team is still loaded by id (once per page) to read its timezone, so
-//! naive datetime filters evaluate in the team's local time exactly like live `/flags`.
+//! by token. The team is still loaded by id once per page to read its timezone and
+//! property-matching version, matching live `/flags`.
//! - The handler bypasses the `/flags` request pipeline entirely, so no billing or
//! flag-analytics counters are emitted, and dedicated `flags_batch_eval_*` ops metrics
//! track batch traffic. The per-person matcher still emits its own evaluation metrics
@@ -23,7 +23,7 @@
//! The paged scan walks `posthog_person.id` ascending across a live table, so the run sees
//! a moving snapshot rather than a point-in-time one: persons inserted above the current
//! cursor mid-run are included, persons inserted below it (or deleted) are not. Flag
-//! definitions are pinned by `expected_version`, but person membership is eventually
+//! definitions and property-matching semantics are pinned, but person membership is eventually
//! consistent with the table at the time each page is scanned. This matches the existing
//! cohort-generation contract (a later refresh reconciles drift).
@@ -59,6 +59,7 @@ use crate::{
FLAG_BATCH_EVAL_PERSONS_COUNTER, FLAG_BATCH_EVAL_REQUESTS_COUNTER, FLAG_BATCH_EVAL_TIME,
},
router,
+ team::team_models::{PropertyMatchingVersion, Team},
};
#[derive(Debug, Deserialize)]
@@ -75,6 +76,9 @@ pub struct BatchFlagEvaluationRequest {
/// treated as 0.
#[serde(default)]
pub expected_version: Option<i32>,
+ /// Optimistic-lock pin for the team's property matching semantics.
+ #[serde(default)]
+ pub expected_property_matching_version: Option<i16>,
/// Exclusive lower bound on `posthog_person.id`; 0 (default) starts from the beginning.
#[serde(default)]
pub cursor: i64,
@@ -89,6 +93,8 @@ pub struct BatchFlagEvaluationResponse {
pub next_cursor: Option<i64>,
/// Number of persons in this page whose evaluation failed (they are skipped, not matched).
pub errors_count: u64,
+ /// Matching semantics used for this page.
+ pub property_matching_version: i16,
}
const DEFAULT_LIMIT: i64 = 1_000;
@@ -102,6 +108,7 @@ pub enum BatchFlagEvaluationError {
FlagInactive,
GroupAggregatedFlag,
VersionConflict { expected: i32, actual: i32 },
+ PropertyMatchingVersionConflict { expected: i16, actual: i16 },
Upstream(FlagError),
}
@@ -115,6 +122,7 @@ impl BatchFlagEvaluationError {
Self::FlagInactive => "flag_inactive",
Self::GroupAggregatedFlag => "group_aggregated_flag",
Self::VersionConflict { .. } => "version_conflict",
+ Self::PropertyMatchingVersionConflict { .. } => "property_matching_version_conflict",
Self::Upstream(_) => "upstream_error",
}
}
@@ -122,52 +130,67 @@ impl BatchFlagEvaluationError {
impl IntoResponse for BatchFlagEvaluationError {
fn into_response(self) -> Response {
- let (status, error, detail, actual_version) = match self {
+ let (status, error, detail, actual_version, actual_property_matching_version) = match self {
Self::Unauthorized => (
StatusCode::UNAUTHORIZED,
"unauthorized",
"Missing or invalid internal request token".to_string(),
None,
+ None,
),
Self::InvalidRequest(detail) => {
- (StatusCode::BAD_REQUEST, "invalid_request", detail, None)
+ (StatusCode::BAD_REQUEST, "invalid_request", detail, None, None)
}
Self::PayloadTooLarge => (
StatusCode::PAYLOAD_TOO_LARGE,
"payload_too_large",
format!("Request body exceeds the {MAX_BATCH_BODY_BYTES}-byte limit"),
None,
+ None,
),
Self::FlagNotFound => (
StatusCode::NOT_FOUND,
"flag_not_found",
"No flag with this key exists for this team".to_string(),
None,
+ None,
),
Self::FlagInactive => (
StatusCode::BAD_REQUEST,
"flag_inactive",
"Flag is not active".to_string(),
None,
+ None,
),
Self::GroupAggregatedFlag => (
StatusCode::BAD_REQUEST,
"group_aggregated_flag",
"Group-aggregated flags are not supported for batch evaluation".to_string(),
None,
+ None,
),
Self::VersionConflict { expected, actual } => (
StatusCode::CONFLICT,
"version_conflict",
format!("Flag version is {actual}, expected {expected}; the flag changed during cohort generation"),
Some(actual),
+ None,
+ ),
+ Self::PropertyMatchingVersionConflict { expected, actual } => (
+ StatusCode::CONFLICT,
+ "property_matching_version_conflict",
+ format!(
+ "Property matching version is {actual}, expected {expected}; matching semantics changed during cohort generation"
+ ),
+ None,
+ Some(actual),
),
Self::Upstream(e) => {
// Delegate status selection to FlagError's own mapping, but keep the
// JSON envelope consistent with the other variants.
let status = StatusCode::from_u16(e.status_code())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
- (status, "upstream_error", e.to_string(), None)
+ (status, "upstream_error", e.to_string(), None, None)
}
};
@@ -175,6 +198,9 @@ impl IntoResponse for BatchFlagEvaluationError {
if let Some(actual) = actual_version {
body["actual_version"] = serde_json::json!(actual);
}
+ if let Some(actual) = actual_property_matching_version {
+ body["actual_property_matching_version"] = serde_json::json!(actual);
+ }
(status, Json(body)).into_response()
}
}
@@ -369,6 +395,30 @@ async fn handle_batch_flag_evaluation(
}
let target_key = target.key.clone();
+ let expected_property_matching_version = request
+ .expected_property_matching_version
+ .unwrap_or(PropertyMatchingVersion::LEGACY.0);
+ let mut team = Team::from_pg_by_id(
+ state.database_pools.non_persons_reader.clone(),
+ request.team_id,
+ )
+ .await
+ .map_err(BatchFlagEvaluationError::Upstream)?;
+ if team.property_matching_version.0 != expected_property_matching_version {
+ team = Team::from_pg_by_id(
+ state.database_pools.non_persons_writer.clone(),
+ request.team_id,
+ )
+ .await
+ .map_err(BatchFlagEvaluationError::Upstream)?;
+ if team.property_matching_version.0 != expected_property_matching_version {
+ return Err(BatchFlagEvaluationError::PropertyMatchingVersionConflict {
+ expected: expected_property_matching_version,
+ actual: team.property_matching_version.0,
+ });
+ }
+ }
+
// Mirror the live pipeline's exclusion of inactive flags so dependency conditions on
// them pre-seed as false instead of evaluating.
let filtered_out_flag_ids: HashSet<i32> = flags_vec
@@ -421,17 +471,7 @@ async fn handle_batch_flag_evaluation(
.config
.realtime_cohort_evaluation_team_ids
.includes_team(request.team_id);
-
- // Read the team's timezone from Postgres so naive datetime filter values (IS_DATE_* and
- // relative dates) are interpreted in the team's local time, matching live `/flags`
- // evaluation and HogQL/ClickHouse cohort membership. The live path reads the same
- // `team.timezone`; this is one PK lookup per page, negligible against the per-page
- // person scan. Falls back to UTC for an unrecognized timezone string.
- let team = state
- .flag_service()
- .get_team_by_id(request.team_id)
- .await
- .map_err(BatchFlagEvaluationError::Upstream)?;
+ let use_explicit_exact_matching = team.property_matching_version.uses_explicit_matching();
let team_timezone = team.parsed_timezone();
let mut matched_person_uuids: Vec<Uuid> = Vec::new();
@@ -458,6 +498,7 @@ async fn handle_batch_flag_evaluation(
)
.with_cohort_membership_provider(state.cohort_membership_provider.clone())
.with_realtime_cohort_evaluation(enable_realtime_cohort_evaluation)
+ .with_explicit_exact_matching(use_explicit_exact_matching)
.with_membership_stamp_policy(state.config.realtime_cohort_membership_stamp_policy)
.with_rayon_dispatcher(state.rayon_dispatcher.clone())
.with_parallel_eval_threshold(state.config.parallel_eval_threshold)
@@ -516,6 +557,7 @@ async fn handle_batch_flag_evaluation(
matched_person_uuids,
next_cursor,
errors_count,
+ property_matching_version: team.property_matching_version.0,
})
}
diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rs
index e8ad2a5424ae..c6b8e70a78a8 100644
--- a/rust/feature-flags/src/api/types.rs
+++ b/rust/feature-flags/src/api/types.rs
@@ -4,7 +4,7 @@ use crate::flags::flag_match_reason::FeatureFlagMatchReason;
use crate::flags::flag_matching::FeatureFlagMatch;
use crate::flags::flag_matching_utils::match_flag_value_to_flag_filter;
use crate::flags::flag_models::{FeatureFlag, FeatureFlagId, FlagFilters, Holdout};
-use crate::properties::property_matching::match_property;
+use crate::properties::property_matching::{match_property, PropertyMatchingContext};
use crate::properties::property_models::OperatorType;
use chrono_tz::Tz;
use serde::{de, Deserialize, Deserializer, Serialize};
@@ -488,7 +488,7 @@ pub trait FromFeatureAndMatch {
property_values: Option<&HashMap<String, Value>>,
group_property_values: Option<&HashMap<GroupTypeIndex, HashMap<String, Value>>>,
flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> Self;
fn create_error(flag: &FeatureFlag, error: &FlagError, condition_index: Option<i32>) -> Self;
fn get_reason_description(match_info: &FeatureFlagMatch) -> Option<String>;
@@ -497,7 +497,15 @@ pub trait FromFeatureAndMatch {
impl FromFeatureAndMatch for FlagDetails {
fn create(flag: &FeatureFlag, flag_match: &FeatureFlagMatch) -> Self {
// Timezone is only consulted for detailed analysis, which is off here.
- Self::create_with_analysis(flag, flag_match, false, None, None, None, Tz::UTC)
+ Self::create_with_analysis(
+ flag,
+ flag_match,
+ false,
+ None,
+ None,
+ None,
+ PropertyMatchingContext::new(Tz::UTC, false),
+ )
}
fn create_with_analysis(
@@ -507,7 +515,7 @@ impl FromFeatureAndMatch for FlagDetails {
property_values: Option<&HashMap<String, Value>>,
group_property_values: Option<&HashMap<GroupTypeIndex, HashMap<String, Value>>>,
flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> Self {
FlagDetails {
key: flag.key.clone(),
@@ -533,7 +541,7 @@ impl FromFeatureAndMatch for FlagDetails {
property_values,
group_property_values,
flag_evaluation_results,
- team_timezone,
+ matching_context,
))
} else {
None
@@ -601,7 +609,7 @@ impl FlagDetails {
property_values: Option<&HashMap<String, Value>>,
group_property_values: Option<&HashMap<GroupTypeIndex, HashMap<String, Value>>>,
flag_evaluation_results: Option<&HashMap<FeatureFlagId, FlagValue>>,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> Vec<ConditionAnalysis> {
let mut analyses = Vec::new();
@@ -724,8 +732,8 @@ impl FlagDetails {
let (property_matched, actual_value) = if let Some(props) = resolved_props {
let actual = props.get(&property.key).cloned();
- let matched =
- match_property(property, props, false, team_timezone).unwrap_or(false);
+ let matched = match_property(property, props, false, matching_context)
+ .unwrap_or(false);
(matched, actual)
} else {
// No properties available, fall back to condition-level match
@@ -1456,7 +1464,7 @@ mod tests {
Some(&property_values),
None,
None,
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
// Verify we have analysis for both conditions
@@ -1559,7 +1567,7 @@ mod tests {
Some(&person_props),
Some(&group_props),
None,
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
assert_eq!(analysis.len(), 1);
@@ -1640,7 +1648,7 @@ mod tests {
None,
Some(&group_props),
None,
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
assert_eq!(analysis.len(), 1);
@@ -1703,7 +1711,7 @@ mod tests {
Some(&HashMap::new()),
None,
Some(&flag_results),
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
assert_eq!(analysis.len(), 1);
@@ -1736,7 +1744,7 @@ mod tests {
Some(&HashMap::new()),
None,
Some(&flag_results),
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
assert_eq!(analysis.len(), 1);
@@ -1770,7 +1778,7 @@ mod tests {
Some(&HashMap::new()),
None,
None, // empty — dependency flag 42 absent
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
assert_eq!(analysis.len(), 1);
@@ -1839,7 +1847,7 @@ mod tests {
Some(&property_values),
None,
None,
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
// Enrollment is surfaced as the first entry (omitted entirely before the fix).
@@ -1914,7 +1922,7 @@ mod tests {
Some(&property_values),
None,
None,
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
// Holdout is surfaced as the first entry (omitted entirely before the fix).
@@ -1957,7 +1965,7 @@ mod tests {
Some(&property_values),
None,
None,
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
assert_eq!(analysis.len(), 1);
@@ -2003,7 +2011,7 @@ mod tests {
Some(&property_values),
None,
None,
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
assert_eq!(analysis.len(), 3);
@@ -2060,7 +2068,7 @@ mod tests {
Some(&property_values),
None,
None,
- chrono_tz::Tz::UTC,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
);
// Enrollment entry, then both release conditions in order, with only group 1 as the winner.
diff --git a/rust/feature-flags/src/cohorts/cohort_operations.rs b/rust/feature-flags/src/cohorts/cohort_operations.rs
index 5e6fe5eccb36..a0f55735d75c 100644
--- a/rust/feature-flags/src/cohorts/cohort_operations.rs
+++ b/rust/feature-flags/src/cohorts/cohort_operations.rs
@@ -16,11 +16,10 @@ use crate::metrics::consts::{
COHORT_MALFORMED_FILTER_COUNTER, COHORT_UNSUPPORTED_FILTER_COUNTER,
FLAG_COHORT_STAMP_POLICY_DIVERGENCE_COUNTER,
};
-use crate::properties::property_matching::match_property;
+use crate::properties::property_matching::{match_property, PropertyMatchingContext};
use crate::properties::property_models::OperatorType;
use crate::utils::graph_utils::{DependencyGraph, DependencyProvider, DependencyType};
use crate::{api::errors::FlagError, properties::property_models::PropertyFilter};
-use chrono_tz::Tz;
use common_database::PostgresReader;
use common_types::TeamId;
@@ -318,7 +317,7 @@ impl InnerCohortProperty {
&self,
target_properties: &HashMap<String, Value>,
cohort_matches: &HashMap<CohortId, bool>,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> Result<bool, FlagError> {
match self.prop_type {
CohortPropertyType::OR => {
@@ -328,7 +327,7 @@ impl InnerCohortProperty {
target_properties,
cohort_matches,
0,
- team_timezone,
+ matching_context,
)? {
return Ok(true);
}
@@ -342,7 +341,7 @@ impl InnerCohortProperty {
target_properties,
cohort_matches,
0,
- team_timezone,
+ matching_context,
)? {
return Ok(false);
}
@@ -359,7 +358,7 @@ fn evaluate_cohort_item(
target_properties: &HashMap<String, Value>,
cohort_matches: &HashMap<CohortId, bool>,
depth: usize,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> Result<bool, FlagError> {
if depth > MAX_COHORT_FILTER_DEPTH {
return Err(FlagError::CohortFiltersParsingError);
@@ -370,10 +369,10 @@ fn evaluate_cohort_item(
target_properties,
cohort_matches,
depth,
- team_timezone,
+ matching_context,
),
CohortValuesItem::Filter(filter) => {
- evaluate_cohort_filter(filter, target_properties, cohort_matches, team_timezone)
+ evaluate_cohort_filter(filter, target_properties, cohort_matches, matching_context)
}
// A known filter type that's otherwise malformed; fail loud rather than
// silently resolving to non-match (see `traverse_item`).
@@ -388,7 +387,7 @@ fn evaluate_cohort_filter(
filter: &PropertyFilter,
target_properties: &HashMap<String, Value>,
cohort_matches: &HashMap<CohortId, bool>,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> Result<bool, FlagError> {
if filter.is_cohort() {
// Handle cohort membership check with negation
@@ -400,7 +399,7 @@ fn evaluate_cohort_filter(
Ok(evaluate_property_with_negation(
filter,
target_properties,
- team_timezone,
+ matching_context,
))
}
}
@@ -416,7 +415,7 @@ fn evaluate_cohort_values(
target_properties: &HashMap<String, Value>,
cohort_matches: &HashMap<CohortId, bool>,
depth: usize,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> Result<bool, FlagError> {
match values.prop_type.as_str() {
"OR" => {
@@ -426,7 +425,7 @@ fn evaluate_cohort_values(
target_properties,
cohort_matches,
depth + 1,
- team_timezone,
+ matching_context,
)? {
return Ok(true);
}
@@ -440,7 +439,7 @@ fn evaluate_cohort_values(
target_properties,
cohort_matches,
depth + 1,
- team_timezone,
+ matching_context,
)? {
return Ok(false);
}
@@ -458,10 +457,10 @@ fn evaluate_cohort_values(
fn evaluate_property_with_negation(
filter: &PropertyFilter,
target_properties: &HashMap<String, Value>,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> bool {
let property_result =
- match_property(filter, target_properties, false, team_timezone).unwrap_or(false);
+ match_property(filter, target_properties, false, matching_context).unwrap_or(false);
// Apply negation if specified
if filter.negation.unwrap_or(false) {
@@ -477,7 +476,7 @@ fn evaluate_single_cohort(
cohort: &Cohort,
target_properties: &HashMap<String, Value>,
evaluation_results: &HashMap<CohortId, bool>,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> Result<bool, FlagError> {
// Get the filters for this cohort
let filters = match &cohort.filters {
@@ -494,7 +493,7 @@ fn evaluate_single_cohort(
// Use our evaluation method that respects OR/AND structure
cohort_property
.properties
- .evaluate(target_properties, evaluation_results, team_timezone)
+ .evaluate(target_properties, evaluation_results, matching_context)
.inspect_err(|_| record_malformed_cohort_filter(cohort.id, cohort.team_id, "evaluation"))
}
@@ -503,7 +502,7 @@ pub fn evaluate_dynamic_cohorts(
target_properties: &HashMap<String, Value>,
cohorts: &[Cohort],
static_cohort_matches: &HashMap<CohortId, bool>,
- team_timezone: Tz,
+ matching_context: PropertyMatchingContext,
) -> Result<bool, FlagError> {
// First check if this is a static cohort
let initial_cohort = cohorts
@@ -534,7 +533,7 @@ pub fn evaluate_dynamic_cohorts(
return Ok(());
}
- *result = evaluate_single_cohort(cohort, target_properties, results, team_timezone)?;
+ *result = evaluate_single_cohort(cohort, target_properties, results, matching_context)?;
Ok(())
})?;
@@ -603,8 +602,25 @@ mod tests {
use super::*;
use crate::cohorts::cohort_models::CohortType;
use crate::utils::test_utils::TestContext;
+ use chrono_tz::Tz;
use serde_json::json;
+ fn evaluate_dynamic_cohorts(
+ initial_cohort_id: CohortId,
+ target_properties: &HashMap<String, Value>,
+ cohorts: &[Cohort],
+ static_cohort_matches: &HashMap<CohortId, bool>,
+ team_timezone: Tz,
+ ) -> Result<bool, FlagError> {
+ super::evaluate_dynamic_cohorts(
+ initial_cohort_id,
+ target_properties,
+ cohorts,
+ static_cohort_matches,
+ PropertyMatchingContext::new(team_timezone, false),
+ )
+ }
+
#[tokio::test]
async fn test_list_from_pg() {
let context = TestContext::new(None).await;
@@ -1177,6 +1193,39 @@ mod tests {
}
}
+ #[test]
+ fn test_dynamic_cohort_exact_matching_preserves_legacy_behavior_without_rollout() {
+ let cohort = create_dynamic_cohort_with_filters(
+ 1,
+ json!({
+ "properties": {
+ "type": "OR",
+ "values": [
+ {"key": "enabled", "type": "person", "value": false, "operator": "exact", "negation": true}
+ ]
+ }
+ }),
+ );
+ let target_properties = HashMap::from([("enabled".to_string(), json!("banana"))]);
+
+ assert!(!super::evaluate_dynamic_cohorts(
+ 1,
+ &target_properties,
+ std::slice::from_ref(&cohort),
+ &HashMap::new(),
+ PropertyMatchingContext::new(Tz::UTC, false),
+ )
+ .unwrap());
+ assert!(super::evaluate_dynamic_cohorts(
+ 1,
+ &target_properties,
+ &[cohort],
+ &HashMap::new(),
+ PropertyMatchingContext::new(Tz::UTC, true),
+ )
+ .unwrap());
+ }
+
#[test]
fn test_record_stamp_policy_divergence_only_records_divergent_cohorts() {
let behavioral = json!({
diff --git a/rust/feature-flags/src/flags/flag_matching.rs b/rust/feature-flags/src/flags/flag_matching.rs
index f398acbd5950..1d6535d2f5ae 100644
--- a/rust/feature-flags/src/flags/flag_matching.rs
+++ b/rust/feature-flags/src/flags/flag_matching.rs
@@ -35,7 +35,7 @@ use crate::metrics::consts::{
FLAG_REALTIME_COHORT_QUERY_ERROR_COUNTER, FLAG_REALTIME_COHORT_QUERY_TIME,
PROPERTY_CACHE_HITS_COUNTER, PROPERTY_CACHE_MISSES_COUNTER,
};
-use crate::properties::property_matching::match_property;
+use crate::properties::property_matching::{match_property, PropertyMatchingContext};
use crate::properties::property_models::{PropertyFilter, PropertyType};
use crate::rayon_dispatcher::RayonDispatcher;
use crate::utils::graph_utils::PrecomputedDependencyGraph;
@@ -343,6 +343,7 @@ pub struct FeatureFlagMatcher {
/// Whether to enable realtime cohort evaluation.
/// When false, realtime cohorts are treated as non-members.
enable_realtime_cohort_evaluation: bool,
+ use_explicit_exact_matching: bool,
membership_stamp_policy: MembershipStampPolicy,
/// Cohort definitions preloaded from the flags hypercache.
/// When present, scoped to only the cohorts referenced by flags (including transitive deps),
@@ -421,6 +422,7 @@ impl FeatureFlagMatcher {
skip_writes: false,
filtered_out_flag_ids: HashSet::new(),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
preloaded_cohorts: None,
detailed_analysis: false,
@@ -465,6 +467,11 @@ impl FeatureFlagMatcher {
self
}
+ pub fn with_explicit_exact_matching(mut self, enable: bool) -> Self {
+ self.use_explicit_exact_matching = enable;
+ self
+ }
+
pub fn with_membership_stamp_policy(mut self, policy: MembershipStampPolicy) -> Self {
self.membership_stamp_policy = policy;
self
@@ -783,7 +790,7 @@ impl FeatureFlagMatcher {
target_properties,
&cohorts,
&current_matches,
- self.timezone,
+ PropertyMatchingContext::new(self.timezone, self.use_explicit_exact_matching),
)?;
cohort_matches.insert(cohort_id, match_result);
}
@@ -1081,7 +1088,10 @@ impl FeatureFlagMatcher {
merged_person_props.as_ref(),
Some(&merged_group_props),
Some(&self.flag_evaluation_state.flag_evaluation_results),
- self.timezone,
+ PropertyMatchingContext::new(
+ self.timezone,
+ self.use_explicit_exact_matching,
+ ),
)
} else {
FlagDetails::create(flag, flag_match)
@@ -1701,7 +1711,16 @@ impl FeatureFlagMatcher {
// is unknowable under Pending.
let partial_props = filter.prop_type != PropertyType::Group
&& self.flag_evaluation_state.person_properties_pending();
- if !match_property(filter, props, partial_props, self.timezone).unwrap_or(false)
+ if !match_property(
+ filter,
+ props,
+ partial_props,
+ PropertyMatchingContext::new(
+ self.timezone,
+ self.use_explicit_exact_matching,
+ ),
+ )
+ .unwrap_or(false)
{
return Ok((false, FeatureFlagMatchReason::NoConditionMatch));
}
diff --git a/rust/feature-flags/src/flags/property_filter.rs b/rust/feature-flags/src/flags/property_filter.rs
index dae7ee0749a7..254e937c9f82 100644
--- a/rust/feature-flags/src/flags/property_filter.rs
+++ b/rust/feature-flags/src/flags/property_filter.rs
@@ -265,7 +265,7 @@ mod tests {
#[test]
fn test_invalid_pattern_returns_false_for_both_regex_and_not_regex() {
- use crate::properties::property_matching::match_property;
+ use crate::properties::property_matching::{match_property, PropertyMatchingContext};
let props = HashMap::from([("email".to_string(), serde_json::json!("[email protected]"))]);
@@ -285,7 +285,12 @@ mod tests {
Some(CompiledRegex::InvalidPattern)
));
assert_eq!(
- match_property(&regex_filter, &props, false, chrono_tz::Tz::UTC),
+ match_property(
+ &regex_filter,
+ &props,
+ false,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
+ ),
Ok(false)
);
@@ -308,7 +313,12 @@ mod tests {
// on-the-fly behavior where a failed compilation returns Ok(false)
// regardless of operator.
assert_eq!(
- match_property(&not_regex_filter, &props, false, chrono_tz::Tz::UTC),
+ match_property(
+ &not_regex_filter,
+ &props,
+ false,
+ PropertyMatchingContext::new(chrono_tz::Tz::UTC, false),
+ ),
Ok(false)
);
}
@@ -372,7 +382,7 @@ mod tests {
property_value: &str,
expected: Result<bool, crate::properties::property_matching::FlagMatchingError>,
) {
- use crate::properties::property_matching::match_property;
+ use crate::properties::property_matching::{match_property, PropertyMatchingContext};
let props = HashMap::from([("key".to_string(), serde_json::json!(property_value))]);
@@ -386,11 +396,12 @@ mod tests {
compiled_regex: None,
extra: Default::default(),
};
- let result_raw = match_property(&filter_raw, &props, false, chrono_tz::Tz::UTC);
+ let context = PropertyMatchingContext::new(chrono_tz::Tz::UTC, false);
+ let result_raw = match_property(&filter_raw, &props, false, context);
let mut filter_compiled = filter_raw.clone();
filter_compiled.prepare_regex();
- let result_compiled = match_property(&filter_compiled, &props, false, chrono_tz::Tz::UTC);
+ let result_compiled = match_property(&filter_compiled, &props, false, context);
assert_eq!(result_raw, result_compiled);
assert_eq!(result_compiled, expected);
diff --git a/rust/feature-flags/src/handler/evaluation.rs b/rust/feature-flags/src/handler/evaluation.rs
index 2927df7fa55a..c8218a2d320b 100644
--- a/rust/feature-flags/src/handler/evaluation.rs
+++ b/rust/feature-flags/src/handler/evaluation.rs
@@ -34,6 +34,7 @@ pub async fn evaluate_feature_flags(
.with_rayon_dispatcher(context.rayon_dispatcher)
.with_skip_writes(context.skip_writes)
.with_realtime_cohort_evaluation(context.enable_realtime_cohort_evaluation)
+ .with_explicit_exact_matching(context.use_explicit_exact_matching)
.with_membership_stamp_policy(context.membership_stamp_policy)
.with_detailed_analysis(context.detailed_analysis)
.with_only_use_override_person_properties(context.only_use_override_person_properties)
diff --git a/rust/feature-flags/src/handler/flags.rs b/rust/feature-flags/src/handler/flags.rs
index d7dd82fa6fb0..34b594cd9bf1 100644
--- a/rust/feature-flags/src/handler/flags.rs
+++ b/rust/feature-flags/src/handler/flags.rs
@@ -333,6 +333,7 @@ pub async fn evaluate_for_request(
state: &State<router::State>,
team_id: i32,
team_timezone: Tz,
+ use_explicit_exact_matching: bool,
distinct_id: String,
device_id: Option<String>,
filtered_flags: FeatureFlagList,
@@ -392,6 +393,7 @@ pub async fn evaluate_for_request(
.config
.realtime_cohort_evaluation_team_ids
.includes_team(team_id),
+ use_explicit_exact_matching,
membership_stamp_policy: state.config.realtime_cohort_membership_stamp_policy,
detailed_analysis: detailed_analysis.unwrap_or(false),
only_use_override_person_properties: only_use_override_person_properties.unwrap_or(false),
diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rs
index 1bec7b18a842..992980f132a8 100644
--- a/rust/feature-flags/src/handler/mod.rs
+++ b/rust/feature-flags/src/handler/mod.rs
@@ -272,6 +272,7 @@ async fn process_request_inner(
// Interpret naive datetime filter values in the team timezone so flag
// evaluation matches HogQL/ClickHouse cohort membership.
team.parsed_timezone(),
+ team.property_matching_version.uses_explicit_matching(),
distinct_id.clone(),
device_id.clone(),
filtered_flags.clone(),
diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rs
index db9bb73c40a1..4bc8a0d068bf 100644
--- a/rust/feature-flags/src/handler/tests.rs
+++ b/rust/feature-flags/src/handler/tests.rs
@@ -329,6 +329,7 @@ async fn test_evaluate_feature_flags() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -415,6 +416,7 @@ async fn test_evaluate_feature_flags_with_errors() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -808,6 +810,7 @@ async fn test_evaluate_feature_flags_multiple_flags() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -892,6 +895,7 @@ async fn test_evaluate_feature_flags_details() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -1049,6 +1053,7 @@ async fn test_evaluate_feature_flags_with_overrides() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -1132,6 +1137,7 @@ async fn test_long_distinct_id() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -1740,6 +1746,7 @@ async fn test_parallel_path_matches_sequential_results() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -1772,6 +1779,7 @@ async fn test_parallel_path_matches_sequential_results() {
skip_writes: false,
cohort_membership_provider: Arc::new(NoOpCohortMembershipProvider),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -1865,6 +1873,7 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {
skip_writes: false,
cohort_membership_provider: provider_disabled.clone(),
enable_realtime_cohort_evaluation: false,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
@@ -1903,6 +1912,7 @@ async fn test_realtime_cohort_evaluation_setting_behavior() {
skip_writes: false,
cohort_membership_provider: provider_enabled.clone(),
enable_realtime_cohort_evaluation: true,
+ use_explicit_exact_matching: false,
membership_stamp_policy: MembershipStampPolicy::default(),
detailed_analysis: false,
only_use_override_person_properties: false,
diff --git a/rust/feature-flags/src/handler/types.rs b/rust/feature-flags/src/handler/types.rs
index 6be4d11c03ae..6d827ee45b0c 100644
--- a/rust/feature-flags/src/handler/types.rs
+++ b/rust/feature-flags/src/handler/types.rs
@@ -97,6 +97,7 @@ pub struct FeatureFlagEvaluationContext {
pub cohort_membership_provider: Arc<dyn CohortMembershipProvider>,
/// Whether to enable realtime cohort evaluation.
pub enable_realtime_cohort_evaluation: bool,
+ pub use_explicit_exact_matching: bool,
pub membership_stamp_policy: MembershipStampPolicy,
/// Whether to include detailed condition analysis in flag evaluation results.
pub detailed_analysis: bool,
diff --git a/rust/feature-flags/src/properties/property_matching.rs b/rust/feature-flags/src/properties/property_matching.rs
index 6deb35a98360..1b5c7084d908 100644
--- a/rust/feature-flags/src/properties/property_matching.rs
+++ b/rust/feature-flags/src/properties/property_matching.rs
@@ -61,6 +61,21 @@ pub fn to_string_representation(value: &Value) -> String {
value.to_string()
}
+#[derive(Clone, Copy)]
+pub struct PropertyMatchingContext {
+ team_timezone: Tz,
+ use_explicit_exact_matching: bool,
+}
+
+impl PropertyMatchingContext {
+ pub fn new(team_timezone: Tz, use_explicit_exact_matching: bool) -> Self {
+ Self {
+ team_timezone,
+ use_explicit_exact_matching,
+ }
+ }
+}
+
pub fn to_f64_representation(value: &Value) -> Option<f64> {
if value.is_number() {
return value.as_f64();
@@ -162,8 +177,10 @@ pub fn match_property(
property: &PropertyFilter,
matching_property_values: &HashMap<String, Value>,
partial_props: bool,
- team_timezone: Tz,
+ context: PropertyMatchingContext,
) -> Result<bool, FlagMatchingError> {
+ let team_timezone = context.team_timezone;
+ let use_explicit_exact_matching = context.use_explicit_exact_matching;
let lookup_key = lookup_key_for(property);
let key: &str = lookup_key.as_ref();
@@ -209,26 +226,26 @@ pub fn match_property(
match operator {
OperatorType::Exact | OperatorType::IsNot => {
let compute_exact_match = |value: &Value, override_value: &Value| -> bool {
- if is_truthy_or_falsy_property_value(value) {
- // Do boolean handling, such that passing in "true" or "True" or "false" or "False" as matching value is equivalent
- let (truthy_value, truthy_override_value) = (
- is_truthy_property_value(value),
- is_truthy_property_value(override_value),
- );
- return truthy_override_value.to_string().to_lowercase()
- == truthy_value.to_string().to_lowercase();
+ if !use_explicit_exact_matching && is_truthy_or_falsy_property_value(value) {
+ return is_truthy_property_value(value)
+ == is_truthy_property_value(override_value);
}
- if value.is_array() {
- let target = to_string_representation(override_value).to_lowercase();
- return value
- .as_array()
- .expect("expected array value")
- .iter()
- .any(|v| to_string_representation(v).to_lowercase() == target);
+ match value {
+ Value::Array(values) if values.is_empty() => {
+ is_truthy_property_value(override_value)
+ }
+ Value::Array(values) => {
+ let target = to_string_representation(override_value).to_lowercase();
+ values
+ .iter()
+ .any(|value| to_string_representation(value).to_lowercase() == target)
+ }
+ single_value => {
+ to_string_representation(single_value).to_lowercase()
+ == to_string_representation(override_value).to_lowercase()
+ }
}
- to_string_representation(value).to_lowercase()
- == to_string_representation(override_value).to_lowercase()
};
if let Some(match_value) = match_value {
@@ -644,51 +661,23 @@ pub fn match_property(
}
fn is_truthy_or_falsy_property_value(value: &Value) -> bool {
- if value.is_boolean() {
- return true;
- }
-
- if value.is_string() {
- let parsed_value = value
- .as_str()
- .expect("expected string value")
- .to_lowercase();
- return parsed_value == "true" || parsed_value == "false";
- }
-
- if value.is_array() {
- return value
- .as_array()
- .expect("expected array value")
- .iter()
- .all(is_truthy_or_falsy_property_value);
+ match value {
+ Value::Bool(_) => true,
+ Value::String(value) => {
+ value.eq_ignore_ascii_case("true") || value.eq_ignore_ascii_case("false")
+ }
+ Value::Array(values) => values.iter().all(is_truthy_or_falsy_property_value),
+ _ => false,
}
-
- false
}
fn is_truthy_property_value(value: &Value) -> bool {
- if value.is_boolean() {
- return value.as_bool().expect("expected boolean value");
- }
-
- if value.is_string() {
- let parsed_value = value
- .as_str()
- .expect("expected string value")
- .to_lowercase();
- return parsed_value == "true";
+ match value {
+ Value::Bool(value) => *value,
+ Value::String(value) => value.eq_ignore_ascii_case("true"),
+ Value::Array(values) => values.iter().all(is_truthy_property_value),
+ _ => false,
}
-
- if value.is_array() {
- return value
- .as_array()
- .expect("expected array value")
- .iter()
- .all(is_truthy_property_value);
- }
-
- false
}
/// Naive wall-clock datetime formats (no embedded offset). A match here means the
@@ -788,7 +777,12 @@ mod test_match_properties {
matching_property_values: &HashMap<String, Value>,
partial_props: bool,
) -> Result<bool, FlagMatchingError> {
- super::match_property(property, matching_property_values, partial_props, Tz::UTC)
+ super::match_property(
+ property,
+ matching_property_values,
+ partial_props,
+ PropertyMatchingContext::new(Tz::UTC, true),
+ )
}
#[test]
@@ -954,24 +948,138 @@ mod test_match_properties {
assert_eq!(actual, expected, "user_value = {user_value}");
}
- #[test]
- fn test_match_properties_exact_empty_array_never_matches() {
+ fn match_exact_value(filter_value: Value, user_value: Value, operator: OperatorType) -> bool {
+ match_exact_value_with_semantics(filter_value, user_value, operator, true)
+ }
+
+ fn match_exact_value_with_semantics(
+ filter_value: Value,
+ user_value: Value,
+ operator: OperatorType,
+ use_explicit_exact_matching: bool,
+ ) -> bool {
let property = PropertyFilter {
- key: "country".to_string(),
- value: Some(json!([])),
- operator: Some(OperatorType::Exact),
+ key: "key".to_string(),
+ value: Some(filter_value),
+ operator: Some(operator),
prop_type: PropertyType::Person,
group_type_index: None,
negation: None,
compiled_regex: None,
extra: Default::default(),
};
- assert!(!match_property(
+
+ super::match_property(
&property,
- &HashMap::from([("country".to_string(), json!("us"))]),
- true
+ &HashMap::from([("key".to_string(), user_value)]),
+ true,
+ PropertyMatchingContext::new(Tz::UTC, use_explicit_exact_matching),
)
- .expect("expected match to exist"));
+ .expect("expected match to exist")
+ }
+
+ #[test_case(json!(false), json!(false), true; "bool false matches bool false")]
+ #[test_case(json!(false), json!("FALSE"), true; "bool false matches uppercase false string")]
+ #[test_case(json!("FaLsE"), json!(false), true; "mixed case false string matches bool false")]
+ #[test_case(json!(true), json!(true), true; "bool true matches bool true")]
+ #[test_case(json!(true), json!("TRUE"), true; "bool true matches uppercase true string")]
+ #[test_case(json!("TrUe"), json!(true), true; "mixed case true string matches bool true")]
+ #[test_case(json!(false), json!(true), false; "bool false does not match bool true")]
+ #[test_case(json!(false), json!("true"), false; "bool false does not match true string")]
+ #[test_case(json!(false), json!(0), false; "zero does not coerce to false")]
+ #[test_case(json!(false), Value::Null, false; "null does not coerce to false")]
+ #[test_case(json!(false), json!(""), false; "empty string does not coerce to false")]
+ #[test_case(json!(false), json!("banana"), false; "arbitrary string does not coerce to false")]
+ #[test_case(json!(true), json!(1), false; "one does not coerce to true")]
+ #[test_case(json!(true), json!("banana"), false; "arbitrary string does not coerce to true")]
+ #[test_case(json!(true), json!([true]), false; "bool true does not match bool array")]
+ #[test_case(json!(true), json!([]), false; "bool true does not match empty array")]
+ fn test_match_properties_exact_scalar_values_do_not_use_truthiness(
+ filter_value: Value,
+ user_value: Value,
+ expected: bool,
+ ) {
+ assert_eq!(
+ match_exact_value(
+ filter_value.clone(),
+ user_value.clone(),
+ OperatorType::Exact,
+ ),
+ expected
+ );
+ assert_eq!(
+ match_exact_value(filter_value, user_value, OperatorType::IsNot),
+ !expected
+ );
+ }
+
+ #[test_case(json!(false), json!("banana"); "arbitrary string remains false-like")]
+ #[test_case(json!(false), json!(0); "zero remains false-like")]
+ #[test_case(json!(false), Value::Null; "null remains false-like")]
+ #[test_case(json!(false), json!(""); "empty string remains false-like")]
+ #[test_case(json!(["false"]), json!("banana"); "boolean array keeps aggregate truthiness")]
+ fn test_match_properties_exact_legacy_behavior_without_rollout(
+ filter_value: Value,
+ user_value: Value,
+ ) {
+ assert!(match_exact_value_with_semantics(
+ filter_value.clone(),
+ user_value.clone(),
+ OperatorType::Exact,
+ false,
+ ));
+ assert!(!match_exact_value_with_semantics(
+ filter_value,
+ user_value,
+ OperatorType::IsNot,
+ false,
+ ));
+ }
+
+ #[test_case(json!(["true", "false"]), json!(true), true; "boolean strings contain bool true")]
+ #[test_case(json!(["true", "false"]), json!("TRUE"), true; "boolean strings contain uppercase true string")]
+ #[test_case(json!(["true", "false"]), json!(false), true; "boolean strings contain bool false")]
+ #[test_case(json!(["true", "false"]), json!("false"), true; "boolean strings contain false string")]
+ #[test_case(json!(["true", "false"]), json!("pro"), false; "boolean strings do not contain arbitrary string")]
+ #[test_case(json!(["false"]), json!("banana"), false; "false string does not match arbitrary string")]
+ #[test_case(json!(["FREE", "PRO"]), json!("pro"), true; "string membership is case insensitive")]
+ fn test_match_properties_exact_boolean_arrays_use_any_membership(
+ filter_value: Value,
+ user_value: Value,
+ expected: bool,
+ ) {
+ assert_eq!(
+ match_exact_value(
+ filter_value.clone(),
+ user_value.clone(),
+ OperatorType::Exact,
+ ),
+ expected
+ );
+ assert_eq!(
+ match_exact_value(filter_value, user_value, OperatorType::IsNot),
+ !expected
+ );
+ }
+
+ #[test_case(json!(true), true; "empty filter keeps bool true match")]
+ #[test_case(json!("true"), true; "empty filter keeps true string match")]
+ #[test_case(json!(false), false; "empty filter keeps bool false mismatch")]
+ #[test_case(json!("banana"), false; "empty filter keeps arbitrary string mismatch")]
+ #[test_case(json!([]), true; "empty filter keeps empty array match")]
+ #[test_case(json!([true]), true; "empty filter keeps truthy array match")]
+ fn test_match_properties_exact_empty_array_preserves_existing_behavior(
+ user_value: Value,
+ expected: bool,
+ ) {
+ assert_eq!(
+ match_exact_value(json!([]), user_value.clone(), OperatorType::Exact),
+ expected
+ );
+ assert_eq!(
+ match_exact_value(json!([]), user_value, OperatorType::IsNot),
+ !expected
+ );
}
#[test]
@@ -4336,7 +4444,7 @@ mod test_match_properties {
filter,
&HashMap::from([("joined_at".to_string(), person_value)]),
true,
- tz,
+ PropertyMatchingContext::new(tz, true),
)
.expect("expected match to exist")
}
diff --git a/rust/feature-flags/src/team/team_models.rs b/rust/feature-flags/src/team/team_models.rs
index bb415f043576..885ec52e2a8e 100644
--- a/rust/feature-flags/src/team/team_models.rs
+++ b/rust/feature-flags/src/team/team_models.rs
@@ -3,6 +3,26 @@ use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use sqlx::types::{Json, Uuid};
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, sqlx::Type)]
+#[serde(transparent)]
+#[sqlx(transparent)]
+pub struct PropertyMatchingVersion(pub i16);
+
+impl PropertyMatchingVersion {
+ pub const LEGACY: Self = Self(1);
+ pub const EXPLICIT: Self = Self(2);
+
+ pub fn uses_explicit_matching(self) -> bool {
+ self == Self::EXPLICIT
+ }
+}
+
+impl Default for PropertyMatchingVersion {
+ fn default() -> Self {
+ Self::LEGACY
+ }
+}
+
#[derive(Clone, Debug, Default, Deserialize, Serialize, sqlx::FromRow)]
pub struct Team {
pub id: TeamId,
@@ -55,6 +75,9 @@ pub struct Team {
// deserializing to `false` (full events), fail-safe.
#[serde(default)]
pub minimal_flag_called_events: bool,
+ // Cache entries written before this field existed retain legacy matching.
+ #[serde(default)]
+ pub property_matching_version: PropertyMatchingVersion,
}
fn default_timezone() -> String {
@@ -109,5 +132,9 @@ mod tests {
serde_json::from_value(legacy_json).expect("legacy blob must still deserialize");
assert!(!team.minimal_flag_called_events);
+ assert_eq!(
+ team.property_matching_version,
+ PropertyMatchingVersion::LEGACY
+ );
}
}
diff --git a/rust/feature-flags/src/team/team_operations.rs b/rust/feature-flags/src/team/team_operations.rs
index dd1853f5e4d8..1e46b435ae97 100644
--- a/rust/feature-flags/src/team/team_operations.rs
+++ b/rust/feature-flags/src/team/team_operations.rs
@@ -47,7 +47,11 @@ const TEAM_COLUMNS: &str = "
COALESCE(
(SELECT minimal_flag_called_events FROM feature_flags_teamfeatureflagsconfig WHERE team_id = posthog_team.id),
false
- ) AS minimal_flag_called_events
+ ) AS minimal_flag_called_events,
+ COALESCE(
+ (SELECT property_matching_version FROM feature_flags_teamfeatureflagsconfig WHERE team_id = posthog_team.id),
+ 1
+ )::smallint AS property_matching_version
";
impl Team {
@@ -111,6 +115,7 @@ impl Team {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::team::team_models::PropertyMatchingVersion;
use crate::utils::test_utils::{
insert_new_team_in_redis, setup_redis_client, setup_team_hypercache_reader, TestContext,
};
@@ -304,7 +309,7 @@ mod tests {
}
#[tokio::test]
- async fn test_fetch_team_defaults_minimal_flag_called_events_false_without_config_row() {
+ async fn test_fetch_team_defaults_feature_flags_config_without_config_row() {
let context = TestContext::new(None).await;
let team = context
.insert_new_team(None)
@@ -316,10 +321,14 @@ mod tests {
.expect("Failed to fetch team from pg");
assert!(!team_from_pg.minimal_flag_called_events);
+ assert_eq!(
+ team_from_pg.property_matching_version,
+ PropertyMatchingVersion::LEGACY
+ );
}
#[tokio::test]
- async fn test_fetch_team_reflects_gated_minimal_flag_called_events() {
+ async fn test_fetch_team_reflects_feature_flags_config() {
let context = TestContext::new(None).await;
let team = context
.insert_new_team(None)
@@ -335,7 +344,9 @@ mod tests {
.expect("Failed to get connection");
sqlx::query(
- "INSERT INTO feature_flags_teamfeatureflagsconfig (team_id, minimal_flag_called_events) VALUES ($1, true)",
+ "INSERT INTO feature_flags_teamfeatureflagsconfig \
+ (team_id, minimal_flag_called_events, property_matching_version) \
+ VALUES ($1, true, 2)",
)
.bind(team.id)
.execute(&mut *conn)
@@ -347,5 +358,9 @@ mod tests {
.expect("Failed to fetch team from pg");
assert!(team_from_pg.minimal_flag_called_events);
+ assert_eq!(
+ team_from_pg.property_matching_version,
+ PropertyMatchingVersion::EXPLICIT
+ );
}
}
diff --git a/rust/feature-flags/tests/test_batch_flag_evaluation.rs b/rust/feature-flags/tests/test_batch_flag_evaluation.rs
index 67cb17e5cba4..e4149cb16766 100644
--- a/rust/feature-flags/tests/test_batch_flag_evaluation.rs
+++ b/rust/feature-flags/tests/test_batch_flag_evaluation.rs
@@ -286,6 +286,119 @@ async fn test_version_mismatch_returns_conflict_with_actual_version() -> Result<
Ok(())
}
+#[tokio::test]
+async fn test_property_matching_version_mismatch_returns_conflict() -> Result<()> {
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await?;
+ let server = ServerHandle::for_config(batch_eval_config()).await;
+
+ context
+ .insert_flag(
+ team.id,
+ Some(flag_row(
+ team.id,
+ "matching-version-flag",
+ json!({"groups": [{"rollout_percentage": 100}]}),
+ )),
+ )
+ .await?;
+
+ let mut body = batch_body(team.id, "matching-version-flag", 0);
+ body["expected_property_matching_version"] = json!(2);
+ let res = send_batch_request(&server, Some(INTERNAL_TOKEN), &body).await;
+ assert_eq!(res.status(), StatusCode::CONFLICT);
+ let json_response = res.json::<Value>().await?;
+ assert_eq!(json_response["error"], "property_matching_version_conflict");
+ assert_eq!(json_response["actual_property_matching_version"], json!(1));
+
+ Ok(())
+}
+
+#[tokio::test]
+async fn test_team_property_matching_version_selects_live_and_batch_semantics() -> Result<()> {
+ let context = TestContext::new(None).await;
+ let team = context.insert_new_team(None).await?;
+ let server = ServerHandle::for_config(batch_eval_config()).await;
+
+ context
+ .insert_flag(
+ team.id,
+ Some(flag_row(
+ team.id,
+ "boolean-property-flag",
+ json!({
+ "groups": [{
+ "properties": [{
+ "key": "key",
+ "value": false,
+ "type": "person",
+ "operator": "exact"
+ }],
+ "rollout_percentage": 100
+ }]
+ }),
+ )),
+ )
+ .await?;
+ let distinct_id = "non-boolean-value";
+ context
+ .insert_person(
+ team.id,
+ distinct_id.to_string(),
+ Some(json!({"key": "banana"})),
+ )
+ .await?;
+ let person_uuid = context
+ .get_person_uuid_by_distinct_id(team.id, distinct_id)
+ .await?;
+
+ let legacy_response = send_batch_request(
+ &server,
+ Some(INTERNAL_TOKEN),
+ &batch_body(team.id, "boolean-property-flag", 0),
+ )
+ .await
+ .json::<Value>()
+ .await?;
+ assert_eq!(legacy_response["property_matching_version"], json!(1));
+ assert_eq!(matched_uuids(&legacy_response), vec![person_uuid]);
+
+ let mut conn = context.get_non_persons_connection().await?;
+ sqlx::query(
+ "INSERT INTO feature_flags_teamfeatureflagsconfig \
+ (team_id, minimal_flag_called_events, property_matching_version) \
+ VALUES ($1, false, 2)",
+ )
+ .bind(team.id)
+ .execute(&mut *conn)
+ .await?;
+
+ let live_response = server
+ .send_flags_request(
+ json!({"token": team.api_token, "distinct_id": distinct_id}).to_string(),
+ Some("2"),
+ None,
+ )
+ .await;
+ assert_eq!(live_response.status(), StatusCode::OK);
+ let live_response = live_response.json::<Value>().await?;
+ assert_eq!(
+ live_response["flags"]["boolean-property-flag"]["enabled"],
+ json!(false)
+ );
+
+ let mut explicit_body = batch_body(team.id, "boolean-property-flag", 0);
+ explicit_body["expected_property_matching_version"] = json!(2);
+ let explicit_response = send_batch_request(&server, Some(INTERNAL_TOKEN), &explicit_body)
+ .await
+ .json::<Value>()
+ .await?;
+ assert_eq!(explicit_response["property_matching_version"], json!(2));
+ assert!(matched_uuids(&explicit_response).is_empty());
+
+ Ok(())
+}
+
#[tokio::test]
async fn test_null_expected_version_coerces_to_zero() -> Result<()> {
let context = TestContext::new(None).await;
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 7991c572b0e8..86a8b8e249fd 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -71157,6 +71157,18 @@ export namespace Schemas {
role?: string | null;
}
+ /**
+ * * `1` - Legacy
+ * * `2` - Explicit
+ */
+ export type PropertyMatchingVersionEnum = typeof PropertyMatchingVersionEnum[keyof typeof PropertyMatchingVersionEnum];
+
+
+ export const PropertyMatchingVersionEnum = {
+ Number1: 1,
+ Number2: 2,
+ } as const;
+
export type PropertyType = typeof PropertyType[keyof typeof PropertyType];
@@ -83080,6 +83092,11 @@ export namespace Schemas {
team_id: number;
/** Whether this team's SDKs receive the slim $feature_flag_called event shape (omitting fields only needed for experiments) instead of the full legacy shape. */
minimal_flag_called_events: boolean;
+ /** Property matching semantics used by /flags, local evaluation, and cohort generation.
+ *
+ * * `1` - Legacy
+ * * `2` - Explicit */
+ property_matching_version: PropertyMatchingVersionEnum;
/**
* Per-team override for the maximum number of feature flags this team may create, or null when the team uses the global default.
* @nullable
@@ -83101,6 +83118,11 @@ export namespace Schemas {
team_id: number;
/** New value for the team's minimal_flag_called_events setting. Omit to leave it unchanged. Only set true after confirming that team's SDK versions support the slim $feature_flag_called event shape. */
minimal_flag_called_events?: boolean;
+ /** New property matching version for the team. Version 1 preserves legacy behavior. Version 2 uses explicit scalar and array equality. Only set version 2 after confirming that the team's local-evaluation SDK versions support it. Omit to leave it unchanged.
+ *
+ * * `1` - Legacy
+ * * `2` - Explicit */
+ property_matching_version?: PropertyMatchingVersionEnum;
/**
* New per-team flag-count limit (1-20,000). Send null to clear the override so the team falls back to the global default. Omit to leave it unchanged.
* @minimum 1