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.

feat(flags): shadow-compare remote_config against the Rust port (#65546)

Patriciocabfc4bdfdb7
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 10a1e50236ac..2285ab1cc269 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -600,6 +600,11 @@ AI_GATEWAY_PUBLIC_URL = os.getenv("AI_GATEWAY_PUBLIC_URL", "http://localhost:808
# This is used to proxy flag evaluation requests to the Rust feature flags service
FEATURE_FLAGS_SERVICE_URL = os.getenv("FEATURE_FLAGS_SERVICE_URL", "http://localhost:3001")
+# Temporary (Rust remote_config port, phase 2): when true, each Django remote_config response is
+# shadow-compared against Rust. Off by default; flip per environment to start/stop without a deploy.
+# Delete with remote_config_shadow.py at the phase-3 cutover.
+REMOTE_CONFIG_SHADOW_ENABLED = get_from_env("REMOTE_CONFIG_SHADOW_ENABLED", False, type_cast=str_to_bool)
+
# Bearer token for marking Django -> Rust /flags calls as internal (non-billable).
# When set, internal Django callers (toolbar prep, my_flags, evaluation_reasons) pass this
# as `Authorization: Bearer …` so the Rust service skips per-team billing and quota limits.
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 2db00f222ec8..a4bcd985351c 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -73,6 +73,7 @@ from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.util import get_all_cohort_dependencies
from products.dashboards.backend.api.dashboard import Dashboard
from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.api.remote_config_shadow import shadow_compare_remote_config
from products.feature_flags.backend.encrypted_flag_payloads import (
REDACTED_PAYLOAD_VALUE,
encrypt_flag_payloads,
@@ -4037,6 +4038,16 @@ class FeatureFlagViewSet(
throttle_classes=[RemoteConfigThrottle],
)
def remote_config(self, request: request.Request, **kwargs):
+ response = self._remote_config_response(request, **kwargs)
+ # Temporary (Rust remote_config port, phase 2): shadow-compare against Rust; delete after cutover.
+ # Guarded here too so a bug in the throwaway shadow can never break the live endpoint.
+ try:
+ shadow_compare_remote_config(request, response, project_id=self.project_id, key=kwargs["pk"])
+ except Exception:
+ logger.exception("remote_config shadow comparison failed")
+ return response
+
+ def _remote_config_response(self, request: request.Request, **kwargs) -> Response:
is_flag_id_provided = kwargs["pk"].isdigit()
try:
diff --git a/products/feature_flags/backend/api/remote_config_shadow.py b/products/feature_flags/backend/api/remote_config_shadow.py
new file mode 100644
index 000000000000..2c0125d1ea3f
--- /dev/null
+++ b/products/feature_flags/backend/api/remote_config_shadow.py
@@ -0,0 +1,112 @@
+"""Temporary Django↔Rust shadow comparison for the remote_config port (phase 2).
+
+For each Django remote_config response, replays the same request against the Rust flags
+service and records whether status + body match, to prove parity before the cutover.
+Inline (every request, no background thread) and fully guarded — any failure is counted
+and swallowed, never affecting the real response. Delete with the cutover (phase 3); Rust
+bills nothing for remote_config until then, so this can't double-count usage.
+"""
+
+from typing import Any
+
+from django.conf import settings
+
+import structlog
+from prometheus_client import Counter
+from requests.adapters import HTTPAdapter
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.auth import PersonalAPIKeyAuthentication, TeamSecretTokenAuthentication
+from posthog.security.outbound_proxy import internal_requests_session
+
+logger = structlog.get_logger(__name__)
+
+# Internal call: trust_env=False so it skips the outbound proxy, like the live flags proxy.
+_SHADOW_SESSION = internal_requests_session()
+# Shared module-level session across workers: size the pool and disable retries so a slow Rust
+# never silently multiplies the work behind one shadow call.
+_SHADOW_SESSION.mount("http://", HTTPAdapter(pool_connections=1, pool_maxsize=20, max_retries=0))
+_SHADOW_SESSION.mount("https://", HTTPAdapter(pool_connections=1, pool_maxsize=20, max_retries=0))
+
+# (connect, read) seconds — deliberately tighter than the live proxy's 3s so a slow Rust lands in
+# `except` as `error` instead of adding latency to the user's response.
+_SHADOW_TIMEOUT = (0.3, 0.5)
+
+REMOTE_CONFIG_SHADOW_COMPARISONS = Counter(
+ "posthog_remote_config_shadow_comparisons",
+ "remote_config Django-vs-Rust shadow comparisons by outcome",
+ ["result"], # match | mismatch | error | skipped
+)
+
+# Rust only implements these two SDK credential types. Session-cookie and OAuth requests (Django's
+# own preview/decrypt UI) 401 on Rust by design, so shadowing them would log false mismatches.
+_RUST_SUPPORTED_AUTH = (TeamSecretTokenAuthentication, PersonalAPIKeyAuthentication)
+
+
+def shadow_compare_remote_config(request: Request, django_response: Response, *, project_id: int, key: str) -> None:
+ # Off by default — flip REMOTE_CONFIG_SHADOW_ENABLED per environment to start (or stop) shadowing
+ # without a deploy. Returns silently so a disabled shadow emits no metrics at all.
+ if not getattr(settings, "REMOTE_CONFIG_SHADOW_ENABLED", False):
+ return
+
+ if not isinstance(request.successful_authenticator, _RUST_SUPPORTED_AUTH):
+ REMOTE_CONFIG_SHADOW_COMPARISONS.labels(result="skipped").inc()
+ return
+
+ # Rust authenticates only the Bearer Authorization header, but Django also accepts the credential
+ # from the query string and request body. Replaying those reaches Rust with no usable credential
+ # (401), a false mismatch — so only compare header-authenticated requests.
+ authorization = request.headers.get("Authorization")
+ if not authorization:
+ REMOTE_CONFIG_SHADOW_COMPARISONS.labels(result="skipped").inc()
+ return
+
+ try:
+ # Rebuild the canonical /api/projects path Rust serves (not request.get_full_path(), which can
+ # be an /api/environments or legacy alias). Rust resolves the project from ?token= when present,
+ # else from this segment — both give the same flag.
+ url = f"{settings.FEATURE_FLAGS_SERVICE_URL}/api/projects/{project_id}/feature_flags/{key}/remote_config"
+ rust = _SHADOW_SESSION.get(
+ url,
+ params=request.query_params.dict(),
+ headers={"Authorization": authorization},
+ timeout=_SHADOW_TIMEOUT,
+ )
+ if _responses_match(django_response, rust):
+ REMOTE_CONFIG_SHADOW_COMPARISONS.labels(result="match").inc()
+ else:
+ REMOTE_CONFIG_SHADOW_COMPARISONS.labels(result="mismatch").inc()
+ # Never log the bodies — decrypted remote config payloads are secrets.
+ logger.warning(
+ "remote_config_shadow_mismatch",
+ flag=key,
+ project_id=project_id,
+ django_status=django_response.status_code,
+ rust_status=rust.status_code,
+ )
+ except Exception:
+ REMOTE_CONFIG_SHADOW_COMPARISONS.labels(result="error").inc()
+ logger.warning("remote_config_shadow_error", flag=key, project_id=project_id, exc_info=True)
+
+
+def _responses_match(django_response: Response, rust_response: Any) -> bool:
+ if django_response.status_code != rust_response.status_code:
+ return False
+ return django_response.data == _rust_body(rust_response)
+
+
+# Sentinel for a non-empty body that isn't valid JSON. Distinct from None so a garbage Rust body
+# can't compare equal to Django's empty Response(None).data and get miscounted as a match.
+_UNPARSEABLE = object()
+
+
+def _rust_body(rust_response: Any) -> Any:
+ # Both sides render a falsy/null payload as an empty 200 body; treat empty as None so it
+ # equals Django's Response(None).data.
+ if not rust_response.content:
+ return None
+ try:
+ return rust_response.json()
+ except ValueError:
+ return _UNPARSEABLE
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 7ea3e4be6b2e..cbf4d1c367e4 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -77,6 +77,13 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
r = redis.get_client()
for key in r.scan_iter("*"):
r.delete(key)
+
+ # Temporary: keep the remote_config Rust shadow (phase 2) inert so endpoint tests never make
+ # a real outbound call. Delete with remote_config_shadow.py at the phase-3 cutover.
+ shadow_patcher = patch("products.feature_flags.backend.api.feature_flag.shadow_compare_remote_config")
+ shadow_patcher.start()
+ self.addCleanup(shadow_patcher.stop)
+
return super().setUp()
@staticmethod
@@ -2101,6 +2108,35 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json(), '{"test": true}')
+ def test_remote_config_returns_response_even_if_shadow_raises(self):
+ # The throwaway Rust shadow (phase 2) must never break the live endpoint, even if it raises.
+ self.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="my-remote-config-flag",
+ name="Remote Config Flag",
+ active=True,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {"true": '{"test": true}'},
+ },
+ is_remote_configuration=True,
+ )
+ self.client.logout()
+ with patch(
+ "products.feature_flags.backend.api.feature_flag.shadow_compare_remote_config",
+ side_effect=RuntimeError("boom"),
+ ) as shadow:
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config",
+ headers={"authorization": f"Bearer {self.team.secret_api_token}"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), '{"test": true}')
+ shadow.assert_called_once()
+ self.assertEqual(shadow.call_args.kwargs["key"], "my-remote-config-flag")
+ self.assertIn("project_id", shadow.call_args.kwargs)
+
# Encrypted remote config payloads are decrypted only for personal API keys; project
# secret keys get the redacted marker. This is the parity oracle for the Rust port,
# which must replicate both.
diff --git a/products/feature_flags/backend/api/test/test_remote_config_shadow.py b/products/feature_flags/backend/api/test/test_remote_config_shadow.py
new file mode 100644
index 000000000000..cbbcbc85d3b5
--- /dev/null
+++ b/products/feature_flags/backend/api/test/test_remote_config_shadow.py
@@ -0,0 +1,154 @@
+# Temporary — delete with remote_config_shadow.py at the Rust port phase-3 cutover.
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+from rest_framework.response import Response
+
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, TeamSecretTokenAuthentication
+
+from products.feature_flags.backend.api import remote_config_shadow as shadow
+
+# Matches REDACTED_PAYLOAD_VALUE on the Django and Rust sides: a quoted string returned to a
+# secret-key caller on an encrypted flag — the most parity-sensitive value the shadow compares.
+REDACTED = '"********* (encrypted)"'
+
+
+def _request(authenticator=TeamSecretTokenAuthentication, authorization="Bearer phs_x", query=None):
+ req = MagicMock()
+ req.successful_authenticator = MagicMock(spec=authenticator) if authenticator else None
+ req.headers = {"Authorization": authorization} if authorization else {}
+ req.query_params.dict.return_value = query or {}
+ return req
+
+
+def _rust_response(status_code=200, content=b"", json_value=None):
+ resp = MagicMock()
+ resp.status_code = status_code
+ resp.content = content
+ resp.json.return_value = json_value
+ return resp
+
+
[email protected](autouse=True)
+def _enable_shadow(settings):
+ # The shadow is off by default in production; turn it on so these tests exercise the comparison.
+ settings.REMOTE_CONFIG_SHADOW_ENABLED = True
+
+
+def test_disabled_is_inert(settings):
+ settings.REMOTE_CONFIG_SHADOW_ENABLED = False
+ with (
+ patch.object(shadow, "_SHADOW_SESSION") as session,
+ patch.object(shadow, "REMOTE_CONFIG_SHADOW_COMPARISONS") as counter,
+ ):
+ shadow.shadow_compare_remote_config(_request(), Response("v"), project_id=1, key="f")
+ session.get.assert_not_called()
+ counter.labels.assert_not_called()
+
+
[email protected]("authenticator", [None, OAuthAccessTokenAuthentication])
+def test_unsupported_auth_is_skipped(authenticator):
+ with (
+ patch.object(shadow, "_SHADOW_SESSION") as session,
+ patch.object(shadow, "REMOTE_CONFIG_SHADOW_COMPARISONS") as counter,
+ ):
+ shadow.shadow_compare_remote_config(_request(authenticator=authenticator), Response("v"), project_id=1, key="f")
+ session.get.assert_not_called()
+ counter.labels.assert_called_once_with(result="skipped")
+
+
[email protected]("authenticator", [TeamSecretTokenAuthentication, PersonalAPIKeyAuthentication])
+def test_supported_auth_is_compared(authenticator):
+ with (
+ patch.object(shadow, "_SHADOW_SESSION") as session,
+ patch.object(shadow, "REMOTE_CONFIG_SHADOW_COMPARISONS") as counter,
+ ):
+ session.get.return_value = _rust_response(200, b'"v"', "v")
+ shadow.shadow_compare_remote_config(_request(authenticator=authenticator), Response("v"), project_id=1, key="f")
+ session.get.assert_called_once()
+ counter.labels.assert_called_once_with(result="match")
+
+
[email protected]("authenticator", [TeamSecretTokenAuthentication, PersonalAPIKeyAuthentication])
+def test_non_header_credential_is_skipped(authenticator):
+ # Django also authenticates via ?personal_api_key= / request body, but Rust reads only the
+ # Authorization header — so a non-header credential 401s on Rust. Skip rather than log a false mismatch.
+ with (
+ patch.object(shadow, "_SHADOW_SESSION") as session,
+ patch.object(shadow, "REMOTE_CONFIG_SHADOW_COMPARISONS") as counter,
+ ):
+ shadow.shadow_compare_remote_config(
+ _request(authenticator=authenticator, authorization=None), Response("v"), project_id=1, key="f"
+ )
+ session.get.assert_not_called()
+ counter.labels.assert_called_once_with(result="skipped")
+
+
+@override_settings(FEATURE_FLAGS_SERVICE_URL="http://rust:3001")
+def test_builds_canonical_rust_url():
+ with patch.object(shadow, "_SHADOW_SESSION") as session, patch.object(shadow, "REMOTE_CONFIG_SHADOW_COMPARISONS"):
+ session.get.return_value = _rust_response(200, b'"v"', "v")
+ shadow.shadow_compare_remote_config(_request(query={"token": "phc_x"}), Response("v"), project_id=7, key="flag")
+ assert session.get.call_args.args[0] == "http://rust:3001/api/projects/7/feature_flags/flag/remote_config"
+ assert session.get.call_args.kwargs["params"] == {"token": "phc_x"}
+ assert session.get.call_args.kwargs["headers"] == {"Authorization": "Bearer phs_x"}
+
+
+ "django_response, rust_response, expected",
+ [
+ (Response("v", status=200), _rust_response(200, b'"v"', "v"), "match"),
+ (Response("v", status=200), _rust_response(200, b'"other"', "other"), "mismatch"),
+ (Response(status=404), _rust_response(200, b'"v"', "v"), "mismatch"),
+ (Response(None, status=200), _rust_response(200, b"", None), "match"),
+ (Response(status=404), _rust_response(404, b"", None), "match"),
+ (Response(REDACTED, status=200), _rust_response(200, REDACTED.encode(), REDACTED), "match"),
+ (Response({"a": 1}, status=200), _rust_response(200, b'{"a": 1}', {"a": 1}), "match"),
+ (Response({"a": 1}, status=200), _rust_response(200, b'{"a": 2}', {"a": 2}), "mismatch"),
+ ],
+)
+def test_compare_outcomes(django_response, rust_response, expected):
+ with (
+ patch.object(shadow, "_SHADOW_SESSION") as session,
+ patch.object(shadow, "REMOTE_CONFIG_SHADOW_COMPARISONS") as counter,
+ ):
+ session.get.return_value = rust_response
+ shadow.shadow_compare_remote_config(_request(), django_response, project_id=1, key="f")
+ counter.labels.assert_called_once_with(result=expected)
+
+
+def test_mismatch_logs_only_metadata_not_bodies():
+ # Decrypted remote config payloads are secrets — the mismatch log carries only flag/project/statuses.
+ with (
+ patch.object(shadow, "_SHADOW_SESSION") as session,
+ patch.object(shadow, "REMOTE_CONFIG_SHADOW_COMPARISONS"),
+ patch.object(shadow, "logger") as log,
+ ):
+ session.get.return_value = _rust_response(404, b"", None)
+ shadow.shadow_compare_remote_config(_request(), Response("secret-plaintext", status=200), project_id=1, key="f")
+ log.warning.assert_called_once()
+ assert set(log.warning.call_args.kwargs) == {"flag", "project_id", "django_status", "rust_status"}
+
+
+def test_rust_error_is_swallowed():
+ with (
+ patch.object(shadow, "_SHADOW_SESSION") as session,
+ patch.object(shadow, "REMOTE_CONFIG_SHADOW_COMPARISONS") as counter,
+ ):
+ session.get.side_effect = RuntimeError("boom")
+ shadow.shadow_compare_remote_config(_request(), Response("v"), project_id=1, key="f")
+ counter.labels.assert_called_once_with(result="error")
+
+
+def test_non_json_rust_body_is_a_mismatch_not_a_false_match():
+ rust = _rust_response(200, b"<html>502 Bad Gateway</html>")
+ rust.json.side_effect = ValueError("not json")
+ with (
+ patch.object(shadow, "_SHADOW_SESSION") as session,
+ patch.object(shadow, "REMOTE_CONFIG_SHADOW_COMPARISONS") as counter,
+ ):
+ session.get.return_value = rust
+ shadow.shadow_compare_remote_config(_request(), Response(None, status=200), project_id=1, key="f")
+ counter.labels.assert_called_once_with(result="mismatch")