: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): produce flags-cache invalidations to Kafka (dual-write) (#62817)
Phil Haack57f74c7e4f6a
diff --git a/posthog/kafka_client/routing.py b/posthog/kafka_client/routing.pyindex 013138e92b97..a60f50de0be0 100644--- a/posthog/kafka_client/routing.py+++ b/posthog/kafka_client/routing.py@@ -42,6 +42,7 @@ from posthog.kafka_client.topics import (KAFKA_ERROR_TRACKING_ISSUE_FINGERPRINT,KAFKA_ERROR_TRACKING_ISSUE_FINGERPRINT_EMBEDDINGS,KAFKA_EVENTS_JSON,+ KAFKA_FLAGS_CACHE_INVALIDATION,KAFKA_GROUPS,KAFKA_LOG_ENTRIES,KAFKA_METRICS_TIME_TO_SEE_DATA,@@ -85,6 +86,9 @@ _DEFAULT_TOPIC_ROUTING: dict[str, KafkaClusterProfile] = {KAFKA_DOCUMENT_EMBEDDING_RESULTS_TOPIC: KafkaClusterProfile.SHARED,KAFKA_NOTIFICATION_EVENTS: KafkaClusterProfile.SHARED,KAFKA_SIGNALS_REPORT_COMPLETED: KafkaClusterProfile.SHARED,+ # KAFKA_FLAGS_CACHE_INVALIDATION_DLQ is produced only by the Rust consumer,+ # so it needs no Django producer routing entry.+ KAFKA_FLAGS_CACHE_INVALIDATION: KafkaClusterProfile.SHARED,# --- WAREHOUSE_SOURCES (Warpstream warehouse-pipelines) ---KAFKA_WAREHOUSE_SOURCES_JOBS: KafkaClusterProfile.WAREHOUSE_SOURCES,KAFKA_WAREHOUSE_SOURCES_JOBS_DLQ: KafkaClusterProfile.WAREHOUSE_SOURCES,diff --git a/posthog/kafka_client/topics.py b/posthog/kafka_client/topics.pyindex ac0cd4004f99..01522088b1ce 100644--- a/posthog/kafka_client/topics.py+++ b/posthog/kafka_client/topics.py@@ -83,3 +83,9 @@ KAFKA_WAREHOUSE_SOURCES_JOBS_DLQ = f"{KAFKA_PREFIX}data_warehouse_sources_jobs_dKAFKA_NOTIFICATION_EVENTS = f"{KAFKA_PREFIX}notification_events{SUFFIX}"KAFKA_SIGNALS_REPORT_COMPLETED = f"{KAFKA_PREFIX}signals_report_completed{SUFFIX}"++# Producer: Django signal handlers in products/feature_flags/backend/flags_cache.py.+# Consumer: rust/feature-flags flags-cache-builder bin. Not a plugin-server+# concern — no Node-side mirror needed.+KAFKA_FLAGS_CACHE_INVALIDATION = f"{KAFKA_PREFIX}flags_cache_invalidation{SUFFIX}"+KAFKA_FLAGS_CACHE_INVALIDATION_DLQ = f"{KAFKA_PREFIX}flags_cache_invalidation_dlq{SUFFIX}"diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 5507160f13b3..ce471e1ef95d 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -27,7 +27,7 @@ Manual operations:"""from collections import defaultdict-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom typing import TYPE_CHECKING, Anyif TYPE_CHECKING:@@ -42,8 +42,11 @@ from django.dispatch import receiverfrom django.utils import timezoneimport structlog+import posthoganalyticsfrom posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS+from posthog.kafka_client.routing import producer_scope+from posthog.kafka_client.topics import KAFKA_FLAGS_CACHE_INVALIDATIONfrom posthog.metrics import TOMBSTONE_COUNTERfrom posthog.models.team import Teamfrom posthog.storage.cache_expiry_manager import (@@ -59,6 +62,7 @@ from posthog.storage.hypercache_manager import (from products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.dependencies import extract_cohort_dependencies+from products.feature_flags.backend.flags_cache_messages import FlagsCacheInvalidationfrom products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags, serialize_feature_flags@@ -912,6 +916,115 @@ def get_cache_stats() -> dict[str, Any]:# Signal handlers for automatic cache invalidation+# DUAL-WRITE TRANSITIONAL CODE — remove at cutover.+# Stages: producer (this block) at 0% → Rust consumer ships → ramp gate to 100%+# → Kafka becomes primary, this block is deleted and the signal handlers call+# the Kafka path directly. The Celery task `update_team_service_flags_cache`+# outlives cutover — `cohort_changed_flags_cache` still calls it directly until+# cohort invalidation gets its own topic. Throwaway code by design; don't polish.+#+# Transitional surface: DUAL_WRITE_FLAG, _kafka_dual_write_enabled,+# _produce_invalidation, _enqueue_invalidation, and the Kafka branch inside it.+# The signal handlers themselves stay; their tails simplify at cutover.++# Per-team gate for the Kafka producer side of dual-write. Celery remains the+# authoritative path until cutover; the Kafka produce is fire-and-forget.+DUAL_WRITE_FLAG = "flags-cache-kafka-dual-write"+++def _kafka_dual_write_enabled(team_id: int) -> bool:+ """Return True if this team should also produce a Kafka invalidation message.++ A `None` return from `feature_enabled` means the local-eval cache hasn't+ loaded the flag definition yet. Treated as disabled, but ticks+ TOMBSTONE_COUNTER so a fleet-wide silent disable (polling thread wedged)+ is visible on existing Grafana dashboards: a short burst at boot is+ expected; a sustained non-zero rate means polling is broken.+ """+ try:+ # The SDK annotates feature_enabled as returning bool, but it returns+ # None when local evaluation can't resolve the flag. Widen the type so+ # the None branch below survives type checking.+ result: bool | None = posthoganalytics.feature_enabled(+ DUAL_WRITE_FLAG,+ f"team-{team_id}",+ groups={"project": str(team_id)},+ group_properties={"project": {"id": str(team_id)}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ except Exception:+ # If the flag client misbehaves, default to Celery-only — never block the signal handler.+ # Log so a silent disable across the fleet during rollout is visible in Sentry.+ logger.warning(+ "flags_cache_kafka_dual_write_flag_evaluation_failed",+ team_id=team_id,+ flag=DUAL_WRITE_FLAG,+ exc_info=True,+ )+ return False++ if result is None:+ TOMBSTONE_COUNTER.labels(+ namespace="flags",+ operation="dual_write_gate_cache_cold",+ component="flags_cache",+ ).inc()+ return False++ return bool(result)+++def _produce_invalidation(team_id: int) -> None:+ """Produce a single invalidation message; swallow Kafka errors.++ Celery is the source of truth during dual-write — a Kafka produce failure+ here must not break flag editing. Per-message delivery success/failure is+ also counted in KAFKA_PRODUCER_MESSAGES_COUNTER (wired in `_KafkaProducer.produce`).++ `data` must be a dict (not pre-encoded bytes): `_KafkaProducer.produce`+ runs it through `json_serializer` (`json.dumps` + utf-8 encode). Passing+ bytes would `TypeError` inside `json.dumps` and silently fail the swallow+ path. `mode="json"` converts `datetime` to ISO string.++ `flush_timeout=0` keeps this off the request hot path — librdkafka's+ background thread drains the singleton's queue, and the next call flushes+ again. A blocking flush would stall every flag-edit on-commit hook on an+ unhealthy cluster.+ """+ try:+ msg = FlagsCacheInvalidation(team_id=team_id, emitted_at=datetime.now(UTC))+ with producer_scope(topic=KAFKA_FLAGS_CACHE_INVALIDATION, flush_timeout=0) as producer:+ producer.produce(+ topic=KAFKA_FLAGS_CACHE_INVALIDATION,+ data=msg.model_dump(mode="json"),+ key=str(team_id),+ )+ except Exception as e:+ logger.warning("flags_cache_invalidation_produce_failed", team_id=team_id, error=str(e), exc_info=True)+++def _enqueue_invalidation(team_id: int) -> None:+ """Run from `transaction.on_commit`: dual-write to Kafka if enabled, then fire Celery.++ Deferring until commit avoids race conditions where the Celery worker reads+ pre-commit state. Shared by all three signal handlers wired to the+ flag-invalidation topic. Cohort invalidation is intentionally not routed+ here — cohort changes flow through their own topic.++ Kafka runs first so a Celery-broker outage (Redis down) does not suppress+ the rollout-observability signal we're trying to gather. The Kafka path+ swallows its own errors, so it cannot block Celery. Celery's `.delay()`+ is allowed to raise — it's the authoritative path during dual-write and+ operators want broker failures loud.+ """+ from products.feature_flags.backend.tasks import update_team_service_flags_cache++ if _kafka_dual_write_enabled(team_id):+ _produce_invalidation(team_id)+ update_team_service_flags_cache.delay(team_id)++@receiver(post_save, sender=FeatureFlag)@receiver(post_delete, sender=FeatureFlag)def feature_flag_changed_flags_cache(sender, instance: "FeatureFlag", **kwargs):@@ -924,11 +1037,8 @@ def feature_flag_changed_flags_cache(sender, instance: "FeatureFlag", **kwargs):if not settings.FLAGS_REDIS_URL:return- from products.feature_flags.backend.tasks import update_team_service_flags_cache-- # Defer task execution until after the transaction commits to avoid race conditions- # Note: Metric tracking happens in the task itself to capture actual success/failure result- transaction.on_commit(lambda: update_team_service_flags_cache.delay(instance.team_id))+ team_id = instance.team_id+ transaction.on_commit(lambda: _enqueue_invalidation(team_id))@receiver(post_save, sender=Team)@@ -942,11 +1052,8 @@ def team_created_flags_cache(sender, instance: "Team", created: bool, **kwargs):if not created or not settings.FLAGS_REDIS_URL:return- from products.feature_flags.backend.tasks import update_team_service_flags_cache-- # Defer task execution until after the transaction commits- # Note: Metric tracking happens in the task itself to capture actual success/failure result- transaction.on_commit(lambda: update_team_service_flags_cache.delay(instance.id))+ team_id = instance.id+ transaction.on_commit(lambda: _enqueue_invalidation(team_id))@receiver(post_delete, sender=Team)@@ -978,10 +1085,8 @@ def evaluation_context_changed_flags_cache(sender, instance: "FeatureFlagEvaluatif not settings.FLAGS_REDIS_URL:return- from products.feature_flags.backend.tasks import update_team_service_flags_cache-team_id = instance.feature_flag.team_id- transaction.on_commit(lambda: update_team_service_flags_cache.delay(team_id))+ transaction.on_commit(lambda: _enqueue_invalidation(team_id))@receiver(post_save, sender=Cohort)@@ -1003,4 +1108,6 @@ def cohort_changed_flags_cache(sender, instance: "Cohort", **kwargs):from products.feature_flags.backend.tasks import update_team_service_flags_cache+ # Intentionally bypasses _enqueue_invalidation: cohort changes do not+ # share the flag-invalidation Kafka topic.transaction.on_commit(lambda: update_team_service_flags_cache.delay(instance.team_id))diff --git a/products/feature_flags/backend/flags_cache_messages.py b/products/feature_flags/backend/flags_cache_messages.pynew file mode 100644index 000000000000..d484118b07a7--- /dev/null+++ b/products/feature_flags/backend/flags_cache_messages.py@@ -0,0 +1,28 @@+"""Wire schema for flags_cache_invalidation Kafka messages.++Producer: Django signal handlers in products/feature_flags/backend/flags_cache.py.+Consumer: rust/feature-flags flags-cache-builder.++The fixture at rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1.json+is the contract. The Python side round-trips against it in+products/feature_flags/backend/test/test_flags_cache_messages.py. The Rust consumer+(PR 2) will round-trip against the same fixture so schema drift fails the build+on either side. Bumping `version` requires running both producers (old + new)+and both consumers (old + new) in parallel during the migration — do not bump+it without a written rollout plan.+"""++from typing import Literal++from pydantic import AwareDatetime, BaseModel, ConfigDict+++class FlagsCacheInvalidation(BaseModel):+ model_config = ConfigDict(extra="forbid")++ version: Literal[1] = 1+ team_id: int+ operation: Literal["invalidate"] = "invalidate"+ # AwareDatetime rejects naive datetimes — the wire contract is UTC and the+ # Rust consumer expects a timezone offset.+ emitted_at: AwareDatetimediff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex 4753b69ba59b..9276cf908e53 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -13,6 +13,7 @@ from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any+import pytestimport unittestfrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -23,6 +24,7 @@ from django.test import override_settingsfrom parameterized import parameterized+from posthog.kafka_client.topics import KAFKA_FLAGS_CACHE_INVALIDATIONfrom posthog.models import Teamfrom products.cohorts.backend.models.cohort import Cohort@@ -43,6 +45,7 @@ from products.feature_flags.backend.flags_cache import (get_teams_with_flags_queryset,update_flags_cache,)+from products.feature_flags.backend.flags_cache_messages import FlagsCacheInvalidationfrom products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -638,6 +641,211 @@ class TestServiceFlagsSignals(BaseTest):# In production, this prevents stale cache entries+@override_settings(FLAGS_REDIS_URL="redis://test")+class TestServiceFlagsKafkaDualWrite(BaseTest):+ """Kafka dual-write side of the signal handlers. Celery enqueue stays+ unchanged; the Kafka produce sits behind a per-team feature flag and+ never breaks the signal handler if Kafka is unhappy."""++ def setUp(self):+ super().setUp()+ clear_flags_cache(self.team, kinds=["redis", "s3"])++ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=False)+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_dual_write_off_skips_kafka_produce(self, mock_task, mock_gate, mock_produce):+ FeatureFlag.objects.create(+ team=self.team,+ key="dual-write-off",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ mock_task.delay.assert_called_once_with(self.team.id)+ mock_produce.assert_not_called()++ @patch("products.feature_flags.backend.flags_cache.producer_scope")+ @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_dual_write_on_produces_to_kafka(self, mock_task, mock_gate, mock_producer_scope):+ mock_producer = MagicMock()+ mock_producer_scope.return_value.__enter__.return_value = mock_producer++ FeatureFlag.objects.create(+ team=self.team,+ key="dual-write-on",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ mock_task.delay.assert_called_once_with(self.team.id)+ mock_producer_scope.assert_called_once()+ scope_kwargs = mock_producer_scope.call_args.kwargs+ assert scope_kwargs["topic"] == KAFKA_FLAGS_CACHE_INVALIDATION+ assert scope_kwargs["flush_timeout"] == 0++ mock_producer.produce.assert_called_once()+ produce_kwargs = mock_producer.produce.call_args.kwargs+ assert produce_kwargs["topic"] == KAFKA_FLAGS_CACHE_INVALIDATION+ # team_id-keyed partitioning gives the future consumer per-team ordering.+ assert produce_kwargs["key"] == str(self.team.id)++ # `data` must be a dict — the producer's default serializer does+ # `json.dumps(data)` and would `TypeError` on bytes.+ data = produce_kwargs["data"]+ assert isinstance(data, dict), f"expected dict, got {type(data).__name__}"+ envelope = FlagsCacheInvalidation.model_validate(data)+ assert envelope.version == 1+ assert envelope.team_id == self.team.id+ assert envelope.operation == "invalidate"++ @patch("products.feature_flags.backend.flags_cache.producer_scope")+ @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_dual_write_swallows_produce_errors(self, mock_task, mock_gate, mock_producer_scope):+ mock_producer_scope.side_effect = RuntimeError("kafka cluster unreachable")++ # Should not raise — Kafka outage must not break flag editing.+ FeatureFlag.objects.create(+ team=self.team,+ key="dual-write-error",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ mock_task.delay.assert_called_once_with(self.team.id)+ mock_gate.assert_called_once_with(self.team.id)+ mock_producer_scope.assert_called_once()++ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_kafka_produces_before_celery_enqueue(self, mock_task, mock_gate, mock_produce):+ parent = MagicMock()+ parent.attach_mock(mock_produce, "produce")+ parent.attach_mock(mock_task.delay, "celery")++ FeatureFlag.objects.create(+ team=self.team,+ key="dual-write-order",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ call_names = [c[0] for c in parent.mock_calls]+ assert call_names == ["produce", "celery"], f"expected produce before celery, got {call_names}"++ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_kafka_produces_even_when_celery_broker_raises(self, mock_task, mock_gate, mock_produce):+ mock_task.delay.side_effect = RuntimeError("celery broker unreachable")++ with pytest.raises(RuntimeError, match="celery broker unreachable"):+ FeatureFlag.objects.create(+ team=self.team,+ key="dual-write-celery-down",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ mock_gate.assert_called_once_with(self.team.id)+ mock_produce.assert_called_once_with(self.team.id)++ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch(+ "products.feature_flags.backend.flags_cache.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("posthoganalytics borked"),+ )+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_gate_exception_falls_back_to_celery_only(self, mock_task, mock_feature_enabled, mock_produce):+ FeatureFlag.objects.create(+ team=self.team,+ key="gate-broken",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ mock_task.delay.assert_called_once_with(self.team.id)+ mock_produce.assert_not_called()++ @patch("products.feature_flags.backend.flags_cache.TOMBSTONE_COUNTER")+ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch(+ "products.feature_flags.backend.flags_cache.posthoganalytics.feature_enabled",+ return_value=None,+ )+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_gate_cache_cold_falls_back_to_celery_and_increments_tombstone(+ self, mock_task, mock_feature_enabled, mock_produce, mock_tombstone+ ):+ FeatureFlag.objects.create(+ team=self.team,+ key="gate-cache-cold",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ mock_task.delay.assert_called_once_with(self.team.id)+ mock_produce.assert_not_called()+ mock_tombstone.labels.assert_called_once_with(+ namespace="flags",+ operation="dual_write_gate_cache_cold",+ component="flags_cache",+ )+ mock_tombstone.labels.return_value.inc.assert_called_once()++ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_team_create_dual_writes(self, mock_task, mock_gate, mock_produce):+ new_team = Team.objects.create(organization=self.organization, name="Dual-Write Team")+ mock_task.delay.assert_called_with(new_team.id)+ mock_produce.assert_called_with(new_team.id)++ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_evaluation_context_save_dual_writes(self, mock_task, mock_gate, mock_produce):+ flag = FeatureFlag.objects.create(+ team=self.team,+ key="dual-write-ctx-save",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ # Ignore signals from the FeatureFlag create — only assert on the context save.+ mock_task.reset_mock()+ mock_produce.reset_mock()++ ctx = EvaluationContext.objects.create(team=self.team, name="ctx-dual-write")+ FeatureFlagEvaluationContext.objects.create(feature_flag=flag, evaluation_context=ctx)++ mock_task.delay.assert_called_with(self.team.id)+ mock_produce.assert_called_with(self.team.id)++ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")+ @patch("products.feature_flags.backend.flags_cache._kafka_dual_write_enabled", return_value=True)+ @patch("products.feature_flags.backend.tasks.update_team_service_flags_cache")+ @patch("django.db.transaction.on_commit", lambda fn: fn())+ def test_cohort_change_does_not_dual_write(self, mock_task, mock_gate, mock_produce):+ """Cohort changes flow through their own topic — must bypass _enqueue_invalidation."""+ Cohort.objects.create(+ team=self.team,+ name="cohort-no-kafka",+ filters={"properties": {"type": "AND", "values": []}},+ )+ mock_task.delay.assert_called_with(self.team.id)+ mock_gate.assert_not_called()+ mock_produce.assert_not_called()++@override_settings(FLAGS_REDIS_URL="redis://test")class TestServiceFlagsCeleryTasks(BaseTest):"""Test Celery task integration for service flags cache updates."""diff --git a/products/feature_flags/backend/test/test_flags_cache_messages.py b/products/feature_flags/backend/test/test_flags_cache_messages.pynew file mode 100644index 000000000000..69c014eb8312--- /dev/null+++ b/products/feature_flags/backend/test/test_flags_cache_messages.py@@ -0,0 +1,52 @@+import json+from datetime import UTC, datetime+from pathlib import Path++import pytest++from django.conf import settings++from pydantic import ValidationError++from products.feature_flags.backend.flags_cache_messages import FlagsCacheInvalidation++# Both this test and the Rust consumer's round-trip test (PR 2) read this+# fixture; if it moves, both fail.+FIXTURE_PATH = (+ Path(settings.BASE_DIR) / "rust" / "feature-flags" / "tests" / "fixtures" / "flags_cache_invalidation_v1.json"+)+++def test_fixture_round_trip() -> None:+ raw = FIXTURE_PATH.read_text()++ parsed = FlagsCacheInvalidation.model_validate_json(raw)+ assert parsed.version == 1+ assert parsed.team_id == 12345+ assert parsed.operation == "invalidate"+ assert parsed.emitted_at == datetime(2026, 4, 23, 10, 37, 0, tzinfo=UTC)++ # Reserialize and reparse — proves the schema survives a full round-trip even+ # when Pydantic's datetime output (`+00:00`) differs from the fixture's `Z`.+ reparsed = FlagsCacheInvalidation.model_validate_json(parsed.model_dump_json())+ assert reparsed == parsed+++ "overrides",+ [+ pytest.param({"version": 2}, id="rejects_unknown_version"),+ pytest.param({"operation": "clear"}, id="rejects_unknown_operation"),+ pytest.param({"emitted_at": "2026-04-23T10:37:00"}, id="rejects_naive_datetime"),+ pytest.param({"unknown_field": "oops"}, id="rejects_extra_field"),+ ],+)+def test_rejects_invalid_payload(overrides: dict) -> None:+ base = {+ "version": 1,+ "team_id": 12345,+ "operation": "invalidate",+ "emitted_at": "2026-04-23T10:37:00Z",+ }+ with pytest.raises(ValidationError):+ FlagsCacheInvalidation.model_validate_json(json.dumps({**base, **overrides}))diff --git a/rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1.json b/rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1.jsonnew file mode 100644index 000000000000..2dde2a9437b8--- /dev/null+++ b/rust/feature-flags/tests/fixtures/flags_cache_invalidation_v1.json@@ -0,0 +1,6 @@+{+ "version": 1,+ "team_id": 12345,+ "operation": "invalidate",+ "emitted_at": "2026-04-23T10:37:00.000Z"+}