From ceeaf1ee62a1f1355f0ea128abe47bdb74e79a00 Mon Sep 17 00:00:00 2001 From: Anders Asheim Hennum Date: Fri, 27 Nov 2026 11:50:39 +0100 Subject: [PATCH 1/3] feat(flags): request the v=2 definitions feed Local evaluation already evaluates a config version 2 definition when one is loaded. The definitions request now asks for them with v=2, on the first load and on every poll. The version 1 path and remote /flags requests are unchanged, and for a project without such flags the response is the same. The compliance adapter declares feature_flags_local_evaluation_v2 and lets /get_feature_flag use the default getter on the client with definitions (allow_remote_fallback). --- .../local-flag-definitions-v2-request.md | 5 ++ posthog/client.py | 4 +- .../test/test_feature_flags_v2_dispatch.py | 30 ++++++---- sdk_compliance_adapter/README.md | 8 +++ sdk_compliance_adapter/adapter.py | 20 ++++++- sdk_compliance_adapter/test_adapter.py | 58 +++++++++++++++++++ 6 files changed, 112 insertions(+), 13 deletions(-) create mode 100644 .sampo/changesets/local-flag-definitions-v2-request.md diff --git a/.sampo/changesets/local-flag-definitions-v2-request.md b/.sampo/changesets/local-flag-definitions-v2-request.md new file mode 100644 index 000000000..e8b5185de --- /dev/null +++ b/.sampo/changesets/local-flag-definitions-v2-request.md @@ -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. diff --git a/posthog/client.py b/posthog/client.py index 036b7b989..a8d1c92f0 100644 --- a/posthog/client.py +++ b/posthog/client.py @@ -4430,9 +4430,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, diff --git a/posthog/test/test_feature_flags_v2_dispatch.py b/posthog/test/test_feature_flags_v2_dispatch.py index 961f25491..42450369d 100644 --- a/posthog/test/test_feature_flags_v2_dispatch.py +++ b/posthog/test/test_feature_flags_v2_dispatch.py @@ -320,21 +320,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 ------------------------------------------------------------------------ diff --git a/sdk_compliance_adapter/README.md b/sdk_compliance_adapter/README.md index 703f5873a..2263bbf08 100644 --- a/sdk_compliance_adapter/README.md +++ b/sdk_compliance_adapter/README.md @@ -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 diff --git a/sdk_compliance_adapter/adapter.py b/sdk_compliance_adapter/adapter.py index 18d36976c..91aa9074f 100644 --- a/sdk_compliance_adapter/adapter.py +++ b/sdk_compliance_adapter/adapter.py @@ -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. @@ -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( @@ -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 diff --git a/sdk_compliance_adapter/test_adapter.py b/sdk_compliance_adapter/test_adapter.py index 6c12e86ee..ba091070a 100644 --- a/sdk_compliance_adapter/test_adapter.py +++ b/sdk_compliance_adapter/test_adapter.py @@ -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_")] == [ @@ -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) From b818a19d7459726273adef4337c6fc6a85d4e5f0 Mon Sep 17 00:00:00 2001 From: Anders Asheim Hennum Date: Fri, 27 Nov 2026 12:41:38 +0100 Subject: [PATCH 2/3] fix(flags): drop the definitions ETag when the cache installs other definitions A client that fetched the v=2 feed kept its ETag after it loaded other definitions from a shared flag definition cache, such as the legacy feed an older release wrote. Its next request then got 304 for the unchanged v=2 feed and kept the legacy definitions, without config version 2 flags, until the feed changed. Loading definitions from the cache that differ from the installed ones now clears the ETag, so the next request gets the whole feed and stores it for the other readers. The same definitions keep it. --- .../local-flag-definitions-v2-request.md | 2 +- posthog/client.py | 8 +- .../test/test_feature_flags_v2_dispatch.py | 102 ++++++++++++++++++ 3 files changed, 110 insertions(+), 2 deletions(-) diff --git a/.sampo/changesets/local-flag-definitions-v2-request.md b/.sampo/changesets/local-flag-definitions-v2-request.md index e8b5185de..829959f07 100644 --- a/.sampo/changesets/local-flag-definitions-v2-request.md +++ b/.sampo/changesets/local-flag-definitions-v2-request.md @@ -2,4 +2,4 @@ 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. +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`. diff --git a/posthog/client.py b/posthog/client.py index a8d1c92f0..0539606e8 100644 --- a/posthog/client.py +++ b/posthog/client.py @@ -4222,10 +4222,16 @@ def _update_flag_state( data: FlagDefinitionCacheData, *, _fingerprint: Optional[str] = None, + _from_cache: bool = False, ) -> Optional[str]: """Publish definitions and return the old cache identity for unlocked cleanup.""" fingerprint = _fingerprint or self._hash_flag_definitions(data) 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.feature_flags = data["flags"] self.group_type_mapping = data["group_type_mapping"] @@ -4390,7 +4396,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): diff --git a/posthog/test/test_feature_flags_v2_dispatch.py b/posthog/test/test_feature_flags_v2_dispatch.py index 42450369d..5e5884964 100644 --- a/posthog/test/test_feature_flags_v2_dispatch.py +++ b/posthog/test/test_feature_flags_v2_dispatch.py @@ -1301,6 +1301,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. From 2f37b3ef3ee8ce18203617031c6dfaacf93243c4 Mon Sep 17 00:00:00 2001 From: Anders Asheim Hennum Date: Fri, 27 Nov 2026 12:41:43 +0100 Subject: [PATCH 3/3] docs(adapter): say the payload route does not take allow_remote_fallback --- sdk_compliance_adapter/adapter.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk_compliance_adapter/adapter.py b/sdk_compliance_adapter/adapter.py index 91aa9074f..da32f1d9f 100644 --- a/sdk_compliance_adapter/adapter.py +++ b/sdk_compliance_adapter/adapter.py @@ -710,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: