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): publish shadow invalidations for celery-owned teams (#88585)

James Gillec38db2dbdcf
diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.py
index 1986574d6ba1..7bd446cdd626 100644
--- a/products/feature_flags/backend/flags_cache.py
+++ b/products/feature_flags/backend/flags_cache.py
@@ -50,6 +50,7 @@ from posthog.kafka_client.routing import producer_scope
from posthog.kafka_client.topics import KAFKA_FLAGS_CACHE_INVALIDATION
from posthog.metrics import TOMBSTONE_COUNTER
from posthog.models.team import Team
+from posthog.ph_client import feature_enabled_or_false
from posthog.storage.cache_expiry_manager import (
CacheRefreshCounts,
cleanup_stale_expiry_tracking as cleanup_generic,
@@ -1040,9 +1041,12 @@ def get_cache_stats() -> dict[str, Any]:
#
# Transitional surface: KAFKA_ROUTING_FLAG, _evaluate_kafka_routing_flag,
# _route_to_kafka, get_team_primary_flags_writer (and its config binding on
-# FLAGS_HYPERCACHE_MANAGEMENT_CONFIG), _produce_invalidation,
-# _enqueue_invalidation, and the Kafka branch inside it.
-# The signal handlers themselves stay; their tails simplify at cutover.
+# FLAGS_HYPERCACHE_MANAGEMENT_CONFIG), SHADOW_COMPARE_FLAG, _shadow_compare_enabled,
+# publish_shadow_invalidation, _produce_invalidation, _enqueue_invalidation,
+# and the Kafka branch inside it.
+# The signal handlers themselves stay; their tails simplify at cutover. The one
+# call site outside this block is the tail of update_team_service_flags_cache in
+# tasks.py, which goes with it.
# Per-team gate that routes invalidation to Kafka instead of Celery — see
# _enqueue_invalidation for why the two paths are mutually exclusive. The key
@@ -1138,7 +1142,98 @@ def _route_to_kafka(team_id: int) -> bool:
return bool(result)
-def _produce_invalidation(team_id: int) -> None:
+# Per-team gate for shadow parity publishing. A different flag from
+# KAFKA_ROUTING_FLAG on purpose: this one never decides which writer serves a
+# team, so the two ramp independently. See flags_cache_messages for what the
+# consumer does with a shadow message.
+SHADOW_COMPARE_FLAG = "flags-cache-shadow-compare"
+
+
+def _shadow_compare_enabled(team_id: int) -> bool:
+ """Return True if shadow parity comparison is enabled for this team.
+
+ Every failure mode returns False, because shadow publishing is telemetry: an
+ outage here must cost parity evidence and never a cache build.
+
+ Unlike `_route_to_kafka`, an unresolvable flag ticks no TOMBSTONE_COUNTER.
+ Local evaluation cannot resolve SHADOW_COMPARE_FLAG for as long as the flag
+ does not exist in PostHog, so a tick would fire on every Celery-owned rebuild,
+ holding a constant high rate on a panel that means "rare anomaly". A client
+ that is actually broken raises instead, and `publish_shadow_invalidation`
+ logs that.
+ """
+ try:
+ return feature_enabled_or_false(
+ SHADOW_COMPARE_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:
+ # Log so a fleet-wide silent disable is visible in Sentry rather than
+ # showing up only as parity evidence that never arrives.
+ logger.warning(
+ "flags_cache_shadow_compare_flag_evaluation_failed",
+ team_id=team_id,
+ flag=SHADOW_COMPARE_FLAG,
+ exc_info=True,
+ )
+ return False
+
+
+def publish_shadow_invalidation(team_id: int) -> None:
+ """Publish a parity-telemetry message for a team the Celery builder just rebuilt.
+
+ Called from the tail of `update_team_service_flags_cache` rather than from
+ `_enqueue_invalidation`, so the Rust builder diffs its build against a cache
+ entry Python has already written. Publishing at invalidation time races that
+ rebuild: the builder reads fresh Postgres against a pre-rebuild Redis entry
+ and reports the gap as drift. The consumer suppresses a one-off mismatch by
+ content hash, but two invalidations that both land inside one stale window
+ hash the same, which promotes pure Celery lag to a confirmed parity defect.
+
+ The Kafka-routing decision still applies, because this task also serves teams
+ Rust owns: `cohort_changed_flags_cache` and the cohort backfill finalizer
+ dispatch it for every team, and a shadow build for a Rust-owned team would
+ diff the Rust output against itself.
+
+ It reads `_evaluate_kafka_routing_flag` rather than `_route_to_kafka` so those
+ callers do not start ticking the routing gate's cold-cache tombstone counter.
+ Neither of them consulted that gate before, so a backfill on a freshly booted
+ worker would otherwise spike a panel that means the flag polling thread is
+ wedged.
+
+ Both steps swallow their own failures, so a shadow publish cannot fail the
+ build that precedes it.
+ """
+ try:
+ routed_to_kafka = _evaluate_kafka_routing_flag(team_id)
+ except Exception:
+ # A raising client means something is broken, unlike an unresolved flag,
+ # which is routine while SHADOW_COMPARE_FLAG does not exist. This is the
+ # only signal that shadow volume went to zero on the worker, because the
+ # web process runs a separate client and reports under its own event.
+ logger.warning(
+ "flags_cache_shadow_routing_evaluation_failed",
+ team_id=team_id,
+ flag=KAFKA_ROUTING_FLAG,
+ exc_info=True,
+ )
+ return
+
+ # Only an explicit False means Celery owns this team. `None` means local
+ # evaluation cannot resolve ownership, and shadow-building a team Rust owns
+ # would diff the Rust output against itself.
+ if routed_to_kafka is not False:
+ return
+
+ if _shadow_compare_enabled(team_id):
+ _produce_invalidation(team_id, shadow=True)
+
+
+def _produce_invalidation(team_id: int, shadow: bool = False) -> None:
"""Produce a single invalidation message; swallow Kafka errors.
A produce failure must not raise out of a signal handler and is deliberately
@@ -1154,7 +1249,7 @@ def _produce_invalidation(team_id: int) -> None:
`mode="json"` converts `datetime` to ISO string.
"""
try:
- msg = FlagsCacheInvalidation(team_id=team_id, emitted_at=datetime.now(UTC))
+ msg = FlagsCacheInvalidation(team_id=team_id, emitted_at=datetime.now(UTC), shadow=shadow)
with producer_scope(topic=KAFKA_FLAGS_CACHE_INVALIDATION, flush_timeout=0) as producer:
producer.produce(
topic=KAFKA_FLAGS_CACHE_INVALIDATION,
@@ -1164,7 +1259,9 @@ def _produce_invalidation(team_id: int) -> None:
log_key_on_delivery_failure=True,
)
except Exception as e:
- logger.warning("flags_cache_invalidation_produce_failed", team_id=team_id, error=str(e), exc_info=True)
+ logger.warning(
+ "flags_cache_invalidation_produce_failed", team_id=team_id, shadow=shadow, error=str(e), exc_info=True
+ )
def _enqueue_invalidation(team_id: int) -> None:
@@ -1188,6 +1285,10 @@ def _enqueue_invalidation(team_id: int) -> None:
TTL. Celery's `.delay()` may raise when the flag is off, since it is the
sole path then and operators want broker failures loud.
+ Shadow parity messages are not produced here. They are produced after the
+ Celery build writes the cache, in `publish_shadow_invalidation`, which
+ explains why.
+
Guarded on FLAGS_REDIS_URL here rather than at each call site so every
caller gets the same no-op-when-unconfigured behavior.
"""
diff --git a/products/feature_flags/backend/flags_cache_messages.py b/products/feature_flags/backend/flags_cache_messages.py
index 06704e83e136..991bccecf504 100644
--- a/products/feature_flags/backend/flags_cache_messages.py
+++ b/products/feature_flags/backend/flags_cache_messages.py
@@ -11,19 +11,19 @@ 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.
-The Rust consumer additionally understands an optional ``shadow: bool`` field
-(fixture: flags_cache_invalidation_v1_shadow.json): on ``shadow: true`` it
-builds the payload but never writes the cache, diffing the build against the
-live entry instead (parity telemetry for teams Celery still owns). The shadow
-publisher will add the field here when it lands; until then this model stays
-without it so no producer can emit shadow messages before every deployed
-consumer understands them. When adding it, serialize ``shadow=False`` by
-*omitting* the key to keep real invalidations byte-identical to v1.
+The optional ``shadow: bool`` field (fixture:
+flags_cache_invalidation_v1_shadow.json) marks a parity-telemetry message. On
+``shadow: true`` the Rust consumer builds the team's payload but never writes
+the cache, and diffs the build against the live entry instead. Django produces
+these for teams the Celery builder still owns, behind the shadow gate in
+flags_cache.py. ``shadow=False`` is omitted from the wire, so a real
+invalidation stays byte-identical to v1 and any consumer that predates the
+field can still read it.
"""
-from typing import Literal
+from typing import Any, Literal
-from pydantic import AwareDatetime, BaseModel, ConfigDict
+from pydantic import AwareDatetime, BaseModel, ConfigDict, SerializerFunctionWrapHandler, StrictBool, model_serializer
class FlagsCacheInvalidation(BaseModel):
@@ -35,3 +35,16 @@ class FlagsCacheInvalidation(BaseModel):
# AwareDatetime rejects naive datetimes — the wire contract is UTC and the
# Rust consumer expects a timezone offset.
emitted_at: AwareDatetime
+ # StrictBool, not bool: pydantic's lax mode reads `1` as True, and the Rust
+ # consumer rejects a non-bool `shadow`. Both sides must reject the same
+ # payloads, because this field decides whether a build writes the cache.
+ shadow: StrictBool = False
+
+ @model_serializer(mode="wrap")
+ def _omit_default_shadow(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
+ # Pydantic has no per-field `skip_serializing_if`, so the omission lives on
+ # the model to cover every dump rather than one call site.
+ data = handler(self)
+ if not self.shadow:
+ data.pop("shadow", None)
+ return data
diff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.py
index 9497e3a698a5..9440181e4dae 100644
--- a/products/feature_flags/backend/tasks.py
+++ b/products/feature_flags/backend/tasks.py
@@ -25,6 +25,7 @@ from products.feature_flags.backend.flags_cache import (
cleanup_stale_expiry_tracking,
clear_flags_cache,
get_cache_stats,
+ publish_shadow_invalidation,
refresh_expiring_flags_caches,
update_flags_cache,
)
@@ -112,6 +113,13 @@ def update_team_service_flags_cache(team_id: int) -> None:
namespace="feature_flags", cache_name="flags", operation="update", result="success" if success else "failure"
).inc()
+ # KAFKA-CUTOVER TRANSITIONAL CODE — remove with the block it belongs to in
+ # flags_cache.py. Gated on `success` because a shadow build must diff against
+ # the entry this task just wrote. After a failed write the live entry is the
+ # stale one, and the diff would report Python's failure as Rust drift.
+ if success:
+ publish_shadow_invalidation(team_id)
+
@shared_task(
ignore_result=True,
diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.py
index f8d4fc0382c1..0a52705863fc 100644
--- a/products/feature_flags/backend/test/test_flags_cache.py
+++ b/products/feature_flags/backend/test/test_flags_cache.py
@@ -22,7 +22,7 @@ from unittest.mock import MagicMock, patch
from django.conf import settings
from django.core.management.base import OutputWrapper
from django.db import connection
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
@@ -35,6 +35,8 @@ from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.flags_cache import (
FLAGS_HYPERCACHE_MANAGEMENT_CONFIG,
+ KAFKA_ROUTING_FLAG,
+ SHADOW_COMPARE_FLAG,
_blank_inactive_filters,
_compare_flag_fields,
_compute_flag_dependencies,
@@ -52,6 +54,7 @@ from products.feature_flags.backend.flags_cache import (
get_team_ids_with_recently_updated_flags,
get_team_primary_flags_writer,
get_teams_with_flags_queryset,
+ publish_shadow_invalidation,
update_flags_cache,
verify_team_flags,
)
@@ -914,6 +917,163 @@ class TestServiceFlagsKafkaRouting(BaseTest):
mock_produce.assert_not_called()
+class TestShadowInvalidationPublishing(SimpleTestCase):
+ """Shadow parity publishing. It runs at the tail of the Celery build rather
+ than at invalidation time, so the Rust builder diffs against a cache entry
+ Python has already written."""
+
+ TEAM_ID = 7
+
+ @parameterized.expand([("gate_off", False), ("gate_on", True)])
+ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")
+ @patch("products.feature_flags.backend.flags_cache._shadow_compare_enabled")
+ @patch("products.feature_flags.backend.flags_cache._evaluate_kafka_routing_flag", return_value=False)
+ def test_publishes_only_when_the_shadow_gate_is_open(
+ self, name, shadow_gate_open, mock_gate, mock_shadow_gate, mock_produce
+ ):
+ mock_shadow_gate.return_value = shadow_gate_open
+
+ publish_shadow_invalidation(self.TEAM_ID)
+
+ mock_shadow_gate.assert_called_once_with(self.TEAM_ID)
+ if shadow_gate_open:
+ mock_produce.assert_called_once_with(self.TEAM_ID, shadow=True)
+ else:
+ mock_produce.assert_not_called()
+
+ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")
+ @patch("products.feature_flags.backend.flags_cache._shadow_compare_enabled", return_value=True)
+ @patch("products.feature_flags.backend.flags_cache._evaluate_kafka_routing_flag", return_value=True)
+ def test_kafka_owned_team_never_shadow_publishes(self, mock_gate, mock_shadow_gate, mock_produce):
+ # Cohort invalidation dispatches this build task for every team, so a team
+ # Rust already serves reaches here and would diff Rust output against itself.
+ publish_shadow_invalidation(self.TEAM_ID)
+
+ mock_shadow_gate.assert_not_called()
+ mock_produce.assert_not_called()
+
+ @patch("products.feature_flags.backend.flags_cache.producer_scope")
+ @patch("products.feature_flags.backend.flags_cache._shadow_compare_enabled", return_value=True)
+ @patch("products.feature_flags.backend.flags_cache._evaluate_kafka_routing_flag", return_value=False)
+ def test_shadow_message_carries_the_shadow_flag_on_the_wire(self, mock_gate, mock_shadow_gate, mock_producer_scope):
+ mock_producer = MagicMock()
+ mock_producer_scope.return_value.__enter__.return_value = mock_producer
+
+ publish_shadow_invalidation(self.TEAM_ID)
+
+ # The consumer reads this field to decide whether to write the cache, so a
+ # dropped `shadow` would make the Rust builder overwrite an entry Celery owns.
+ envelope = FlagsCacheInvalidation.model_validate(mock_producer.produce.call_args.kwargs["data"])
+ assert envelope.shadow is True
+
+ @patch(
+ "products.feature_flags.backend.flags_cache.producer_scope",
+ side_effect=RuntimeError("kafka cluster unreachable"),
+ )
+ @patch("products.feature_flags.backend.flags_cache._shadow_compare_enabled", return_value=True)
+ @patch("products.feature_flags.backend.flags_cache._evaluate_kafka_routing_flag", return_value=False)
+ @patch("products.feature_flags.backend.flags_cache.logger")
+ def test_produce_failure_does_not_raise_into_the_build(
+ self, mock_logger, mock_gate, mock_shadow_gate, mock_producer_scope
+ ):
+ # Parity evidence is telemetry, so an unhealthy Kafka must not raise back
+ # into the task that just wrote the cache.
+ publish_shadow_invalidation(self.TEAM_ID)
+
+ mock_producer_scope.assert_called_once()
+ # Real and shadow invalidations share a topic and a log event, so this field
+ # is the only thing telling on-call the lost message was telemetry.
+ assert mock_logger.warning.call_args.args[0] == "flags_cache_invalidation_produce_failed"
+ assert mock_logger.warning.call_args.kwargs["shadow"] is True
+
+ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")
+ @patch("products.feature_flags.backend.flags_cache.posthoganalytics.feature_enabled")
+ def test_inert_while_the_shadow_flag_does_not_exist(self, mock_feature_enabled, mock_produce):
+ # The state this ships in. The routing flag resolves, because it is live for
+ # the canary projects. SHADOW_COMPARE_FLAG does not exist yet, so local
+ # evaluation cannot resolve it and returns None.
+ mock_feature_enabled.side_effect = lambda key, *a, **kw: False if key == KAFKA_ROUTING_FLAG else None
+
+ publish_shadow_invalidation(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._shadow_compare_enabled")
+ @patch("products.feature_flags.backend.flags_cache._evaluate_kafka_routing_flag", return_value=None)
+ def test_unresolved_ownership_skips_without_ticking_the_routing_tombstone(
+ self, mock_gate, mock_shadow_gate, mock_produce, mock_tombstone
+ ):
+ publish_shadow_invalidation(self.TEAM_ID)
+
+ # Cohort invalidation and the backfill finalizer dispatch this build task
+ # without reading the routing gate, so ticking its cold-cache counter here
+ # would spike a panel that means the flag polling thread is wedged.
+ mock_tombstone.labels.assert_not_called()
+ # Ownership is unknown, and shadow-building a team Rust owns would diff the
+ # Rust output against itself.
+ mock_shadow_gate.assert_not_called()
+ mock_produce.assert_not_called()
+
+ @patch("products.feature_flags.backend.flags_cache.logger")
+ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")
+ @patch("products.feature_flags.backend.flags_cache._shadow_compare_enabled")
+ @patch(
+ "products.feature_flags.backend.flags_cache._evaluate_kafka_routing_flag",
+ side_effect=RuntimeError("flag client down"),
+ )
+ def test_routing_evaluation_failure_publishes_nothing(self, mock_gate, mock_shadow_gate, mock_produce, mock_logger):
+ # Not raising is the assertion. The task sets no autoretry_for, so an escape
+ # does not re-run the build. It marks the task FAILURE and posts a Sentry
+ # error per rebuild, fleet-wide, for a telemetry failure.
+ publish_shadow_invalidation(self.TEAM_ID)
+
+ mock_shadow_gate.assert_not_called()
+ mock_produce.assert_not_called()
+ # The shadow gate never runs, so its own warning cannot fire. This is the
+ # only record that the worker stopped publishing.
+ assert mock_logger.warning.call_args.args[0] == "flags_cache_shadow_routing_evaluation_failed"
+
+ @patch("products.feature_flags.backend.flags_cache.logger")
+ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")
+ @patch(
+ "products.feature_flags.backend.flags_cache.posthoganalytics.feature_enabled",
+ side_effect=RuntimeError("flag client down"),
+ )
+ @patch("products.feature_flags.backend.flags_cache._evaluate_kafka_routing_flag", return_value=False)
+ def test_shadow_gate_failure_publishes_nothing_and_warns(
+ self, mock_gate, mock_feature_enabled, mock_produce, mock_logger
+ ):
+ publish_shadow_invalidation(self.TEAM_ID)
+
+ mock_produce.assert_not_called()
+ # The warning is the only signal for a fleet-wide silent disable, because
+ # the gate reports its own failure as "shadow off".
+ assert mock_logger.warning.call_args.args[0] == "flags_cache_shadow_compare_flag_evaluation_failed"
+
+ @patch("products.feature_flags.backend.flags_cache._produce_invalidation")
+ # `_shadow_compare_enabled` reaches the SDK through ph_client rather than this
+ # module's import. Patching here still covers it, because both names resolve to
+ # the same posthoganalytics module object.
+ @patch("products.feature_flags.backend.flags_cache.posthoganalytics.feature_enabled", return_value=False)
+ def test_both_gates_evaluate_locally_and_capture_nothing(self, mock_feature_enabled, mock_produce):
+ publish_shadow_invalidation(self.TEAM_ID)
+
+ # A remote evaluation would put a blocking flags-API call inside every cache
+ # build, and an event capture would bill each rebuild as product usage.
+ assert {call.args[0] for call in mock_feature_enabled.call_args_list} == {
+ KAFKA_ROUTING_FLAG,
+ SHADOW_COMPARE_FLAG,
+ }
+ for call in mock_feature_enabled.call_args_list:
+ assert call.kwargs["only_evaluate_locally"] is True
+ assert call.kwargs["send_feature_flag_events"] is False
+ # Inert at 0%. This is the only test that runs the real gate, so nothing
+ # else catches it publishing while SHADOW_COMPARE_FLAG is off.
+ mock_produce.assert_not_called()
+
+
class TestGetTeamPrimaryFlagsWriter(unittest.TestCase):
@parameterized.expand(
[
@@ -987,6 +1147,24 @@ class TestServiceFlagsCeleryTasks(BaseTest):
assert len(flags) == 1
assert flags[0]["key"] == "test-flag"
+ @parameterized.expand([("build_succeeded", True), ("build_failed", False)])
+ @patch("products.feature_flags.backend.flags_cache.producer_scope")
+ @patch("products.feature_flags.backend.flags_cache._shadow_compare_enabled", return_value=True)
+ @patch("products.feature_flags.backend.flags_cache._evaluate_kafka_routing_flag", return_value=False)
+ @patch("products.feature_flags.backend.tasks.update_flags_cache")
+ def test_task_publishes_shadow_invalidation_only_after_a_successful_build(
+ self, name, build_succeeded, mock_update, mock_gate, mock_shadow_gate, mock_producer_scope
+ ):
+ from products.feature_flags.backend.tasks import update_team_service_flags_cache
+
+ mock_update.return_value = build_succeeded
+
+ update_team_service_flags_cache(self.team.id)
+
+ # A failed build leaves the stale entry live, so a shadow diff against it
+ # would report Python's failure as Rust drift.
+ assert mock_producer_scope.called is build_succeeded
+
def test_update_team_service_flags_cache_task_team_not_found(self):
"""Test the Celery task handles missing team gracefully."""
from products.feature_flags.backend.tasks import update_team_service_flags_cache
diff --git a/products/feature_flags/backend/test/test_flags_cache_messages.py b/products/feature_flags/backend/test/test_flags_cache_messages.py
index 69c014eb8312..80fee5258e78 100644
--- a/products/feature_flags/backend/test/test_flags_cache_messages.py
+++ b/products/feature_flags/backend/test/test_flags_cache_messages.py
@@ -10,27 +10,38 @@ 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"
-)
+# Both this test and the Rust consumer's round-trip test read these fixtures; if
+# they move, both fail.
+FIXTURE_DIR = Path(settings.BASE_DIR) / "rust" / "feature-flags" / "tests" / "fixtures"
-def test_fixture_round_trip() -> None:
- raw = FIXTURE_PATH.read_text()
+ ("fixture_name", "expected_shadow"),
+ [
+ pytest.param("flags_cache_invalidation_v1.json", False, id="real_invalidation"),
+ pytest.param("flags_cache_invalidation_v1_shadow.json", True, id="shadow_invalidation"),
+ ],
+)
+def test_fixture_round_trip(fixture_name: str, expected_shadow: bool) -> None:
+ raw = (FIXTURE_DIR / fixture_name).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)
+ assert parsed.shadow is expected_shadow
# 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())
+ serialized = parsed.model_dump_json()
+ reparsed = FlagsCacheInvalidation.model_validate_json(serialized)
assert reparsed == parsed
+ # `shadow=False` must stay off the wire, so a real invalidation keeps exactly
+ # the v1 key set and any consumer that predates the field can still read it.
+ assert ("shadow" in json.loads(serialized)) is expected_shadow
+
@pytest.mark.parametrize(
"overrides",
@@ -39,6 +50,7 @@ def test_fixture_round_trip() -> None:
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"),
+ pytest.param({"shadow": 1}, id="rejects_non_bool_shadow"),
],
)
def test_rejects_invalid_payload(overrides: dict) -> None: