Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .sampo/changesets/local-flag-definitions-v2-request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: minor
---

Local evaluation now asks for flag definitions with `v=2`, on the first load and on every poll, so it receives flags in the newer configuration format and evaluates them locally. A flag it cannot evaluate locally falls back to a remote request in the default mode and has no value with `only_evaluate_locally`, as for any other flag it cannot resolve. For a project without such flags the definitions response does not change. With a `flag_definition_cache_provider`, a client that loads definitions from the cache that differ from the ones it fetched, such as the legacy definitions an older release wrote, drops its ETag, so its next request gets the whole feed instead of `304`.
12 changes: 10 additions & 2 deletions posthog/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4230,6 +4230,7 @@ def _update_flag_state(
*,
_fingerprint: Optional[str] = None,
_parsed_v2_definitions: Optional[Dict[str, _ParsedDefinition]] = None,
_from_cache: bool = False,
) -> Optional[str]:
"""Publish definitions and return the old cache identity for unlocked cleanup.

Expand All @@ -4240,6 +4241,11 @@ def _update_flag_state(
if _parsed_v2_definitions is None:
_parsed_v2_definitions = _parse_definitions(flags)
with self._flag_definition_publication_lock:
if _from_cache and fingerprint != self._flag_definition_fingerprint:
# The ETag validates the definitions this client fetched. A 304 for it
# would keep other definitions read from the cache, such as the legacy
# feed an older release wrote, until the feed changes.
self._flags_etag = None
old_fingerprint = self._flag_definition_fingerprint
self._set_feature_flags(flags, _parsed_v2_definitions)
self.group_type_mapping = data["group_type_mapping"]
Expand Down Expand Up @@ -4404,7 +4410,7 @@ def _load_feature_flags(self):
"[FEATURE FLAGS] Using cached flag definitions from external cache"
)
old_fingerprint = self._update_flag_state(
_with_cached_v2_flags(cached_data)
_with_cached_v2_flags(cached_data), _from_cache=True
)
self._warn_unresolvable_flags()
if isinstance(self.flag_cache, RedisFlagCache):
Expand Down Expand Up @@ -4444,9 +4450,11 @@ def _fetch_feature_flags_from_api(self):
cache_data_to_store: Optional[FlagDefinitionCacheData] = None
old_fingerprint: Optional[str] = None
try:
# v=2 selects the feed with config version 2 definitions. For a project
# without them, and on a server that ignores v, the body is the same.
response = get(
personal_api_key,
f"/flags/definitions?token={self.api_key}&send_cohorts",
f"/flags/definitions?token={self.api_key}&send_cohorts&v=2",
self.host,
timeout=10,
etag=request_etag,
Expand Down
132 changes: 122 additions & 10 deletions posthog/test/test_feature_flags_v2_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,21 +321,31 @@ def test_any_other_config_version_goes_to_the_config_version_2_evaluator(
assert result is not None and result.get_value() == "remote"


def test_the_definitions_request_is_unchanged(client):
# This release evaluates a config version 2 definition when one is loaded, but it
# does not ask for them yet: the request still selects the legacy definitions.
def test_every_definitions_request_asks_for_the_version_2_feed(client):
# The first load and every poll select the feed that carries config version 2
# definitions, including a poll that sends the ETag of that feed and gets 304.
feed = copy.deepcopy(FEED["feed"])
with mock.patch(
"posthog.client.get",
return_value=GetResponse(
data={"flags": [], "group_type_mapping": {}, "cohorts": {}}
),
side_effect=[
GetResponse(data=feed, etag='"feed-v2"'),
GetResponse(data=None, etag='"feed-v2"', not_modified=True),
GetResponse(data=feed, etag='"feed-v2-next"'),
],
) as get:
client.load_feature_flags()
client.load_feature_flags()
# The 304 kept the config version 2 definitions the first load installed.
assert "layout-preview" in (client.feature_flags_by_key or {})
client.load_feature_flags()

[request] = get.call_args_list
assert (
request.args[1] == f"/flags/definitions?token={FAKE_TEST_API_KEY}&send_cohorts"
)
expected = f"/flags/definitions?token={FAKE_TEST_API_KEY}&send_cohorts&v=2"
assert [request.args[1] for request in get.call_args_list] == [expected] * 3
assert [request.kwargs["etag"] for request in get.call_args_list] == [
None,
'"feed-v2"',
'"feed-v2"',
]


# --- Results ------------------------------------------------------------------------
Expand Down Expand Up @@ -1292,6 +1302,108 @@ def test_the_cache_keeps_the_identity_of_the_definitions(keys):
reader.shutdown()


class _SharedProvider(_Provider):
"""A cache that other processes also write. This client fetches only while
``fetch`` is set, and otherwise reads what was stored last."""

def __init__(self) -> None:
super().__init__()
self.fetch = True

def should_fetch_flag_definitions(self) -> bool:
return self.fetch

def on_flag_definitions_received(self, data: Dict[str, Any]) -> None:
super().on_flag_definitions_received(data)
self.stored = self.received[-1]


def _v2_feed_service(flags: List[Dict[str, Any]]):
"""The definitions service with an unchanged v=2 feed: 304 for its ETag."""

def get(*args: Any, etag: Optional[str] = None, **kwargs: Any) -> GetResponse:
if etag == '"feed-v2"':
return GetResponse(data=None, etag=etag, not_modified=True)
return GetResponse(
data={
"flags": copy.deepcopy(flags),
"group_type_mapping": {},
"cohorts": {},
},
etag='"feed-v2"',
)

return get


def test_definitions_from_the_cache_do_not_keep_the_etag_of_other_definitions():
# A release that does not ask for v=2 writes the legacy feed, without config
# version 2 flags, to the shared cache. The ETag of the v=2 feed does not describe
# those definitions, so a 304 for it must not keep them.
legacy = _v1_definition("legacy-shelf")
provider = _SharedProvider()
client = Client(
FAKE_TEST_API_KEY,
send=False,
secret_key="secret-key",
flag_definition_cache_provider=provider,
)
try:
with mock.patch(
"posthog.client.get", side_effect=_v2_feed_service([legacy, BOOLEAN])
) as get:
client._load_feature_flags()
provider.stored = {
"flags": [legacy],
"group_type_mapping": {},
"cohorts": {},
}
provider.fetch = False
client._load_feature_flags()
assert "reading-mode" not in (client.feature_flags_by_key or {})
provider.fetch = True
client._load_feature_flags()

assert [request.kwargs["etag"] for request in get.call_args_list] == [
None,
None,
]
assert "reading-mode" in (client.feature_flags_by_key or {})
# The cache gets the whole feed back for the other readers.
assert provider.stored is not None and provider.stored["flags_v2"] == [BOOLEAN]
finally:
client.shutdown()


def test_the_same_definitions_from_the_cache_keep_the_etag():
legacy = _v1_definition("legacy-shelf")
provider = _SharedProvider()
client = Client(
FAKE_TEST_API_KEY,
send=False,
secret_key="secret-key",
flag_definition_cache_provider=provider,
)
try:
with mock.patch(
"posthog.client.get", side_effect=_v2_feed_service([legacy, BOOLEAN])
) as get:
client._load_feature_flags()
provider.fetch = False
client._load_feature_flags()
provider.fetch = True
client._load_feature_flags()

assert [request.kwargs["etag"] for request in get.call_args_list] == [
None,
'"feed-v2"',
]
assert len(provider.received) == 1
assert "reading-mode" in (client.feature_flags_by_key or {})
finally:
client.shutdown()


def test_the_identity_of_version_1_definitions_is_unchanged():
# Releases without the config version 2 evaluator share a flag cache with this
# one, so they must give version 1 definitions the same identity.
Expand Down
8 changes: 8 additions & 0 deletions sdk_compliance_adapter/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,14 @@ explicit property matching; it does not change the SDK's default matching mode.
they cannot accidentally resolve from local rules. Legacy remote responses
and flag-called events are preserved. Reset disposes both Clients.

The adapter also advertises `feature_flags_local_evaluation_v2`: the SDK asks for
definitions with `v=2` and evaluates config version 2 flags locally.

- `/get_feature_flag` with `allow_remote_fallback: true` calls the SDK's default
getter on the Client with definitions: local first, then a `/flags` request for
a flag it cannot decide. It sends the flag-called events of the read and
conflicts with `only_evaluate_locally` and `force_remote`.

The adapter is sequential (it does not advertise parallel-test support).

## Documentation
Expand Down
23 changes: 20 additions & 3 deletions sdk_compliance_adapter/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,9 @@ def health():
"fail_open",
"encoding_" + compression_name(),
"feature_flags_local_evaluation_v1",
# Definitions requests send v=2, and config version 2 flags evaluate locally.
# /get_feature_flag honors allow_remote_fallback.
"feature_flags_local_evaluation_v2",
# Remote /flags requests send ?v=4 and read the v4 flag record.
"flags_response_v4",
# The legacy payload accessor is exposed on /get_feature_flag_payload.
Expand Down Expand Up @@ -634,7 +637,20 @@ def get_feature_flag():
group_properties = data.get("group_properties")
disable_geoip = data.get("disable_geoip")
only_evaluate_locally = data.get("only_evaluate_locally", False)
force_remote = data.get("force_remote", not only_evaluate_locally)
# The SDK's default getter on the client with definitions: local first, then
# a /flags request for a flag that local evaluation cannot decide.
allow_remote_fallback = data.get("allow_remote_fallback", False)
if allow_remote_fallback and (
only_evaluate_locally or data.get("force_remote")
):
return jsonify(
{
"error": "allow_remote_fallback conflicts with only_evaluate_locally and force_remote"
}
), 400
force_remote = data.get(
"force_remote", not (only_evaluate_locally or allow_remote_fallback)
)

if only_evaluate_locally and force_remote:
return jsonify(
Expand Down Expand Up @@ -673,7 +689,7 @@ def get_feature_flag():
groups=groups,
group_properties=group_properties,
disable_geoip=disable_geoip,
only_evaluate_locally=not force_remote,
only_evaluate_locally=not (force_remote or allow_remote_fallback),
)

# Ensure the SDK's side-effect $feature_flag_called event is sent before
Expand All @@ -694,7 +710,8 @@ def get_feature_flag():
def get_feature_flag_payload():
"""Read a flag's payload with the legacy payload accessor.

Takes the same evaluation modes as /get_feature_flag; remote by default.
Takes only_evaluate_locally and force_remote as /get_feature_flag does, but not
allow_remote_fallback; remote by default.
"""
try:
if not state.client:
Expand Down
58 changes: 58 additions & 0 deletions sdk_compliance_adapter/test_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ def test_health_and_init_use_one_codec(adapter, monkeypatch, env_value, codec):
} <= set(capabilities)
assert "flags_response_v4" in capabilities
assert "feature_flag_payloads" in capabilities
assert "feature_flags_local_evaluation_v2" in capabilities
assert "capture_v0" not in capabilities
assert "capture_ai_v0" not in capabilities
assert [c for c in capabilities if c.startswith("encoding_")] == [
Expand Down Expand Up @@ -296,6 +297,63 @@ def test_rejects_conflicting_evaluation_modes(adapter, route):
assert response.status_code == 400


@pytest.mark.parametrize(
"conflict", [{"only_evaluate_locally": True}, {"force_remote": True}]
)
def test_remote_fallback_conflicts_with_the_other_modes(adapter, conflict):
client = initialize(adapter)
response = client.post(
"/get_feature_flag",
json={
"key": "flag",
"distinct_id": "user",
"allow_remote_fallback": True,
**conflict,
},
)
assert response.status_code == 400


@pytest.mark.parametrize("properties,local", [({"plan": "banana"}, True), ({}, False)])
def test_remote_fallback_uses_the_default_getter_on_the_local_client(
adapter, monkeypatch, properties, local
):
# A conclusive local result needs no request; an inconclusive one asks /flags
# from the client that holds the definitions, and the read sends its event.
client = initialize(adapter)
monkeypatch.setattr(
posthog.client, "get", Mock(return_value=GetResponse(data=definitions()))
)
client.post("/reload_feature_flag_definitions", json={})
remote = Mock(
return_value=posthog.client.normalize_flags_response(
{"featureFlags": {"flag": "remote-value"}}
)
)
monkeypatch.setattr(adapter.state.client, "_get_flags_decision", remote)
unused = Mock(side_effect=AssertionError("The remote-only client is not used"))
monkeypatch.setattr(adapter.state.remote_client, "_get_flags_decision", unused)
captured = Mock()
monkeypatch.setattr(adapter.state.client, "capture", captured)
response = client.post(
"/get_feature_flag",
json={
"key": "flag",
"distinct_id": "user",
"person_properties": properties,
"allow_remote_fallback": True,
},
)
assert response.json == {
"success": True,
"value": True if local else "remote-value",
}
assert remote.call_count == (0 if local else 1)
[call] = captured.call_args_list
assert call.args[0] == "$feature_flag_called"
assert call.kwargs["properties"]["locally_evaluated"] is local


@pytest.mark.parametrize("timeout", [0, -1, 30001, True, "100", None])
def test_reload_validates_deadline(adapter, timeout):
client = initialize(adapter)
Expand Down