: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): attribute hypercache verifier fixes to the primary writer (#87049)
James Gill34c85a83630d
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex b18cc81f5ec1..3fc2b602df63 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -120,6 +120,7 @@ A referenced entry is load-bearing: the matcher pre-seeds its id as false, so a`_drop_unreferenced_unevaluable_flags` removes the rest, `evaluation_metadata` is computed on the surviving set, and `_blank_inactive_filters` replaces the kept unevaluable flags' `filters` with an empty `{"groups": []}` before the payload is written.`build_flags_cache` in `rust/feature-flags/src/flags/cache_builder.rs` writes the same entry and applies the same drop and blanking.Parity is per team, not per byte: each team has one primary writer (teams whose invalidation routes to Kafka via `KAFKA_ROUTING_FLAG` get the Rust builder, every other team Python), the Python verifier remains a repair writer for every team, and the two serializers order keys differently — so what must match is the flag set, fields, and metadata, not the bytes or etag.+Verifier fixes on the flags cache carry a `writer` label (`posthog_hypercache_verify_fixes_total{cache_type="flags", writer="rust"|"python"|"unknown"}`), attributed by evaluating the same routing flag (`get_team_primary_flags_writer` in `flags_cache.py`): a fix on a rust-routed team is the parity signal that the Rust builder diverged, which the unattributed counter blends into Python's baseline repair noise. `unknown` means the routing flag couldn't be evaluated at fix time, so an attribution outage can't masquerade as a clean Rust ramp.Old-shape entries that still carry unreferenced inactive rows stay valid: the matcher never reads those rows, and `verify_team_flags` suppresses them instead of reporting `STALE_IN_CACHE`, so they converge through flag edits and TTL rather than a fleet-wide repair.Deploy Django ahead of the Rust images: an older Python verifier reports a Rust-written entry's dropped rows as missing, repairs them back, and the next Rust build removes them again. The reverse skew is safe — the newer verifier tolerates the extra rows old writers leave.diff --git a/posthog/storage/hypercache_manager.py b/posthog/storage/hypercache_manager.pyindex c7e0de466554..b20e1812e058 100644--- a/posthog/storage/hypercache_manager.py+++ b/posthog/storage/hypercache_manager.py@@ -13,7 +13,6 @@ Operations include:import randomimport statisticsfrom collections.abc import Callable-from dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Protocolif TYPE_CHECKING:@@ -26,6 +25,7 @@ import structlogfrom posthoganalytics import capture_exceptionfrom prometheus_client import Counter, Gauge+from posthog.dataclasses import frozenfrom posthog.metrics import pushed_metrics_registryfrom posthog.models.team.team import Teamfrom posthog.redis import get_client@@ -171,7 +171,7 @@ class UpdateFn(Protocol):def __call__(self, team: Team | int, ttl: int | None = None) -> bool: ...-@dataclass+@frozenclass HyperCacheManagementConfig:"""Configuration for batch HyperCache management operations.@@ -225,6 +225,14 @@ class HyperCacheManagementConfig:# veto is neither a fix nor a failure. `update_fn` paths already guard internally.should_skip_write: Callable[[Any, dict], bool] | None = None+ # Optional attribution of a team's primary cache writer, used to label verifier+ # fixes. During a dual-writer migration (Python Celery builder vs Rust Kafka+ # builder) the verifier is the parity oracle: a fix on a team owned by one writer+ # signals that writer diverged, which an unattributed fix counter blends into the+ # other writer's baseline repair noise. Takes a team id, returns a short static+ # label value (e.g. "python", "rust", "unknown"). None labels every fix "python".+ get_primary_writer_fn: Callable[[int], str] | None = None+# Derived properties (computed from required properties using conventions)@propertydef namespace(self) -> str:diff --git a/posthog/storage/hypercache_verifier.py b/posthog/storage/hypercache_verifier.pyindex 5b18ce542218..04531aa17547 100644--- a/posthog/storage/hypercache_verifier.py+++ b/posthog/storage/hypercache_verifier.py@@ -32,11 +32,13 @@ VerifyTeamFn = Callable[[Team, dict | None, dict | None], dict]# batches gives us ~48 progress logs total.PROGRESS_LOG_BATCH_INTERVAL = 20-# Prometheus counter for tracking fixes during scheduled verification+# Prometheus counter for tracking fixes during scheduled verification. `writer`+# attributes the fix to the team's primary cache writer (see+# HyperCacheManagementConfig.get_primary_writer_fn); "python" when unattributed.HYPERCACHE_VERIFY_FIX_COUNTER = Counter("posthog_hypercache_verify_fixes_total","Cache entries fixed during scheduled verification",- labelnames=["cache_type", "issue_type"],+ labelnames=["cache_type", "issue_type", "writer"],)# Maximum number of team IDs to store for logging@@ -404,8 +406,21 @@ def _fix_and_record(If it contains a "db_data" key, that data is written directly tocache to avoid a redundant DB query."""+ writer = "python"+ if config.get_primary_writer_fn is not None:+ try:+ writer = config.get_primary_writer_fn(team.id)+ except SoftTimeLimitExceeded:+ # The task ran out of time during attribution, not an attribution+ # failure. Let it propagate so the run winds down, matching the write+ # path below and the other guards in this file.+ raise+ except Exception:+ # Attribution must never fail the repair itself.+ writer = "unknown"+# Log what's being fixed, including diff details for mismatches- log_kwargs: dict = {"team_id": team.id, "issue_type": issue_type, "cache_type": cache_type}+ log_kwargs: dict = {"team_id": team.id, "issue_type": issue_type, "cache_type": cache_type, "writer": writer}if "diff_fields" in verification:log_kwargs["diff_fields"] = verification["diff_fields"]if "diff_flags" in verification:@@ -447,7 +462,7 @@ def _fix_and_record(result.fixed_team_ids.append(team.id)# Update Prometheus metric- HYPERCACHE_VERIFY_FIX_COUNTER.labels(cache_type=cache_type, issue_type=issue_type).inc()+ HYPERCACHE_VERIFY_FIX_COUNTER.labels(cache_type=cache_type, issue_type=issue_type, writer=writer).inc()else:result.fix_failed += 1diff --git a/posthog/storage/test/test_hypercache_verifier.py b/posthog/storage/test/test_hypercache_verifier.pyindex d4d40d61cf51..a681eff3c4d1 100644--- a/posthog/storage/test/test_hypercache_verifier.py+++ b/posthog/storage/test/test_hypercache_verifier.py@@ -138,6 +138,7 @@ class TestFixAndRecord(BaseTest):"""Test that successful fix increments the correct counter for each issue type."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.update_fn.return_value = Trueresult = VerificationResult()@@ -165,6 +166,7 @@ class TestFixAndRecord(BaseTest):"""Test that failed fix increments fix_failed counter."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.update_fn.return_value = Falseresult = VerificationResult()@@ -190,6 +192,7 @@ class TestFixAndRecord(BaseTest):)def test_fix_detail_info_log_respects_cap(self, _name, initial_logs_emitted, should_log):mock_config = MagicMock()+ mock_config.get_primary_writer_fn = Nonemock_config.update_fn.return_value = Trueresult = VerificationResult(fix_detail_info_logs_emitted=initial_logs_emitted)@@ -212,6 +215,7 @@ class TestFixAndRecord(BaseTest):team_id=self.team.id,issue_type="cache_mismatch",cache_type="test_cache",+ writer="python",diff_fields=["payload"],)if should_log:@@ -220,10 +224,43 @@ class TestFixAndRecord(BaseTest):assert fix_detail_call not in mock_info.call_args_listassert result.fix_detail_info_logs_emitted == 1+ @parameterized.expand(+ [+ ("unattributed_defaults_to_python", None, "python"),+ ("attribution_fn_value_used", lambda team_id: "rust", "rust"),+ ("attribution_failure_is_unknown", MagicMock(side_effect=Exception("flag client down")), "unknown"),+ ]+ )+ def test_fix_metric_carries_primary_writer_label(self, _name, writer_fn, expected_writer):+ mock_config = MagicMock()+ mock_config.get_primary_writer_fn = writer_fn+ mock_config.should_skip_write = None+ mock_config.update_fn.return_value = True++ result = VerificationResult()++ with patch("posthog.storage.hypercache_verifier.HYPERCACHE_VERIFY_FIX_COUNTER") as mock_counter:+ _fix_and_record(+ team=self.team,+ config=mock_config,+ issue_type="cache_mismatch",+ cache_type="flags",+ result=result,+ verification={"status": "mismatch"},+ )++ mock_counter.labels.assert_called_once_with(+ cache_type="flags", issue_type="cache_mismatch", writer=expected_writer+ )+ # An attribution failure must not fail the repair itself.+ assert result.cache_mismatch_fixed == 1+ assert result.fix_failed == 0+def test_exception_in_update_fn_increments_fix_failed(self):"""Test that exception in update_fn increments fix_failed."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.update_fn.side_effect = Exception("Update failed")result = VerificationResult()@@ -244,6 +281,7 @@ class TestFixAndRecord(BaseTest):"""Test that _fix_and_record uses verification['db_data'] to set cache directly, bypassing update_fn."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonedb_data = {"flags": ["flag1", "flag2"]}result = VerificationResult()@@ -295,6 +333,7 @@ class TestFixAndRecord(BaseTest):"""Test that _fix_and_record falls back to update_fn when verification has no db_data."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.update_fn.return_value = Trueresult = VerificationResult()@@ -318,6 +357,7 @@ class TestFixAndRecord(BaseTest):"""Test that exceptions in set_cache_value (db_data path) increment fix_failed."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.set_cache_value.side_effect = Exception("Redis error")db_data = {"flags": ["flag1"]}@@ -347,6 +387,7 @@ class TestFixAndRecord(BaseTest):previously happened because it subclasses Exception)."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Noneverification: dict = {"status": "miss"}if use_db_data:@@ -379,6 +420,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that cache match status doesn't trigger a fix."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.hypercache.get_cache_identifier.return_value = str(self.team.id)@@ -413,6 +455,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that miss/mismatch status triggers the appropriate fix."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.update_fn.return_value = True@@ -449,6 +492,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_grace_period_repair_miss_is_config_gated(self, repair_miss_during_grace_period, expect_fixed):mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.update_fn.return_value = True@@ -483,6 +527,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that missing expiry tracking triggers fix even when cache matches."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.hypercache.get_cache_identifier.return_value = str(self.team.id)@@ -515,6 +560,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that verification errors are counted."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}@@ -543,6 +589,7 @@ class TestVerifyAndFixBatch(BaseTest):Exception)."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}@@ -584,6 +631,7 @@ class TestVerifyAndFixBatch(BaseTest):loop."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.hypercache.batch_load_fn.return_value = {}mock_config.get_team_ids_to_skip_fix_fn.return_value = set()@@ -612,6 +660,7 @@ class TestVerifyAndFixBatch(BaseTest):def test_batch_load_fn_called_when_available(self) -> None:mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_db_batch_data: dict = {self.team.id: {"flags": []}}mock_config.hypercache.batch_load_fn.return_value = mock_db_batch_datamock_config.hypercache.batch_get_from_cache.return_value = {}@@ -649,6 +698,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that fixes use db_data from verify_fn result to avoid redundant DB queries."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn.return_value = {self.team.id: {"flags": ["flag1", "flag2"]}}mock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.get_team_ids_to_skip_fix_fn = None@@ -677,6 +727,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that expiry_missing fixes use batch-loaded db_data even when verify_fn omits it."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn.return_value = {self.team.id: {"flags": ["flag1", "flag2"]}}mock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.hypercache.get_cache_identifier.return_value = str(self.team.id)@@ -715,6 +766,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that fixes use preloaded batch data via set_cache_value when available."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonedb_data = {"flags": ["flag1", "flag2"]}mock_db_batch_data: dict = {self.team.id: db_data}mock_config.hypercache.batch_load_fn.return_value = mock_db_batch_data@@ -745,6 +797,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that fixes fall back to update_fn when batch_load_fn is not available."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.update_fn.return_value = True@@ -773,6 +826,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that batch_get_from_cache errors fall back to empty dict (individual lookups)."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.side_effect = Exception("Redis connection failed")mock_config.hypercache.get_cache_identifier.return_value = str(self.team.id)@@ -805,6 +859,7 @@ class TestVerifyAndFixBatch(BaseTest):async rebuild. (A miss is the exception — see test_grace_period_repair_miss_is_config_gated.)"""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}# Return team ID in the skip set@@ -836,6 +891,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that when get_team_ids_to_skip_fix_fn is None, fixes proceed normally."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.get_team_ids_to_skip_fix_fn = None # No skip function@@ -865,6 +921,7 @@ class TestVerifyAndFixBatch(BaseTest):"""Test that when get_team_ids_to_skip_fix_fn returns empty set, fixes proceed."""mock_config = MagicMock()mock_config.should_skip_write = None # default: no write guard+ mock_config.get_primary_writer_fn = Nonemock_config.hypercache.batch_load_fn = Nonemock_config.hypercache.batch_get_from_cache.return_value = {}mock_config.get_team_ids_to_skip_fix_fn.return_value = set() # Empty set - don't skip@@ -898,6 +955,7 @@ def _make_verifier_config(teams_queryset: QuerySet[Team], refresh_only_fields: lconfig.refresh_only_fields = refresh_only_fieldsconfig.should_skip_write = Noneconfig.get_team_ids_to_skip_fix_fn = None+ config.get_primary_writer_fn = Noneconfig.get_teams_queryset.return_value = teams_querysetconfig.narrow_team_queryset.side_effect = partial(HyperCacheManagementConfig.narrow_team_queryset, config)config.hypercache.batch_load_fn = Nonediff --git a/posthog/tasks/hypercache_verification.py b/posthog/tasks/hypercache_verification.pyindex fe6b2d4a0fb4..84def1eb4f56 100644--- a/posthog/tasks/hypercache_verification.py+++ b/posthog/tasks/hypercache_verification.py@@ -27,7 +27,12 @@ from posthog.celery_task_names import ()from posthog.exceptions_capture import capture_exceptionfrom posthog.storage.hypercache_manager import HyperCacheManagementConfig-from posthog.storage.hypercache_verifier import TeamBatchFetchError, VerifyTeamFn, _run_verification_for_cache+from posthog.storage.hypercache_verifier import (+ HYPERCACHE_VERIFY_FIX_COUNTER,+ TeamBatchFetchError,+ VerifyTeamFn,+ _run_verification_for_cache,+)from posthog.tasks.utils import CeleryQueue, PushGatewayTaskfrom products.feature_flags.backend.local_evaluation import (@@ -77,6 +82,22 @@ for _cache_type in (*get_args(CacheType), FLAG_DEFINITIONS_CACHE_TYPE):for _reason in get_args(IncompleteRunReason):HYPERCACHE_VERIFICATION_INCOMPLETE_RUNS_COUNTER.labels(cache_type=_cache_type, reason=_reason)+_FIX_ISSUE_TYPES = ("cache_miss", "cache_mismatch", "expiry_missing")+# Only the flags cache has a second writer (the Rust Kafka builder); the other+# caches are Python-written, so pre-creating rust/unknown series for them would+# publish zero-valued series that can never increment.+_FIX_WRITERS_BY_CACHE_TYPE = {+ cache_type: ("python", "rust", "unknown") if cache_type == "flags" else ("python",)+ for cache_type in (*get_args(CacheType), FLAG_DEFINITIONS_CACHE_TYPE)+}+# Same pre-creation rationale as above. It matters most for writer="rust": a+# rust-attributed fix is the rare parity signal the Kafka-builder ramp gates on,+# and its first increment must not be invisible to increase().+for _cache_type, _writers in _FIX_WRITERS_BY_CACHE_TYPE.items():+ for _issue_type in _FIX_ISSUE_TYPES:+ for _writer in _writers:+ HYPERCACHE_VERIFY_FIX_COUNTER.labels(cache_type=_cache_type, issue_type=_issue_type, writer=_writer)+def _record_incomplete_run(cache_type: str, reason: IncompleteRunReason) -> None:HYPERCACHE_VERIFICATION_INCOMPLETE_RUNS_COUNTER.labels(cache_type=cache_type, reason=reason).inc()@@ -251,7 +272,7 @@ def verify_and_fix_flags_cache_task(self: PushGatewayTask) -> None:Expected duration: ~8 minutes (observed 2026-08-21); the hard limit stays under the30-minute schedule so a run always finishes before the next one is due.- Metrics: posthog_hypercache_verify_fixes_total{cache_type="flags", issue_type="..."},+ Metrics: posthog_hypercache_verify_fixes_total{cache_type="flags", issue_type="...", writer="..."},posthog_hypercache_verification_incomplete_runs_total{cache_type="flags", reason="..."}"""_run_cache_verification(diff --git a/posthog/tasks/test/test_hypercache_verification.py b/posthog/tasks/test/test_hypercache_verification.pyindex 0d4eac1a4cf7..e8c7ed35ac49 100644--- a/posthog/tasks/test/test_hypercache_verification.py+++ b/posthog/tasks/test/test_hypercache_verification.py@@ -37,6 +37,27 @@ def _incomplete_runs(cache_type: str, reason: str) -> float:)+class TestFixCounterSeries(SimpleTestCase):+ def test_every_label_triple_is_pre_created_at_import(self) -> None:+ # Expectations are literals, not _FIX_WRITERS_BY_CACHE_TYPE: deriving them+ # from the dict would let a dropped writer (the rust series the ramp gates+ # on) shrink the test along with the code.+ for cache_type, writers in (+ ("flags", ("python", "rust", "unknown")),+ ("team_metadata", ("python",)),+ ("flag_definitions", ("python",)),+ ):+ for issue_type in ("cache_miss", "cache_mismatch", "expiry_missing"):+ for writer in writers:+ assert (+ REGISTRY.get_sample_value(+ "posthog_hypercache_verify_fixes_total",+ {"cache_type": cache_type, "issue_type": issue_type, "writer": writer},+ )+ is not None+ ), f"series not pre-created: cache_type={cache_type}, issue_type={issue_type}, writer={writer}"++class TestIncompleteRunsCounterSeries(SimpleTestCase):def test_every_label_pair_is_pre_created_at_import(self) -> None:for cache_type in ("flags", "team_metadata", "flag_definitions"):diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 9561ecbd23b9..c1ab80f699eb 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -51,7 +51,6 @@1 posthog/persons_seed.py1 posthog/session/backfill.py1 posthog/storage/auth_token_cache_verifier.py-1 posthog/storage/hypercache_manager.py1 posthog/storage/hypercache_verifier.py1 posthog/tasks/alerts/detector.py1 posthog/tasks/alerts/detectors/base.pydiff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex ddec0e2fa983..1986574d6ba1 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -43,6 +43,7 @@ from django.utils import timezoneimport structlogimport posthoganalytics+from celery.exceptions import SoftTimeLimitExceededfrom posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIASfrom posthog.kafka_client.routing import producer_scope@@ -924,6 +925,10 @@ FLAGS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig(cache_name="flags",get_teams_queryset_fn=get_teams_with_flags_queryset,get_team_ids_to_skip_fix_fn=get_team_ids_with_recently_updated_flags,+ # Late-bound via lambda: the attribution fn lives in the transitional+ # Kafka-routing block further down this module and is deleted with it at+ # cutover, so it isn't defined yet when this config is constructed.+ get_primary_writer_fn=lambda team_id: get_team_primary_flags_writer(team_id),# The refresh loads flags by team id/project_id; it reads no other Team columns.# Narrowing the SELECT keeps it resilient to newly added Team columns the read# replica may not have applied yet (organization_id keeps the select_related valid).@@ -1033,8 +1038,10 @@ def get_cache_stats() -> dict[str, Any]:# 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: KAFKA_ROUTING_FLAG, _route_to_kafka,-# _produce_invalidation, _enqueue_invalidation, and the Kafka branch inside it.+# 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.# Per-team gate that routes invalidation to Kafka instead of Celery — see@@ -1044,6 +1051,56 @@ def get_cache_stats() -> dict[str, Any]:KAFKA_ROUTING_FLAG = "flags-cache-kafka-dual-write"+def _evaluate_kafka_routing_flag(team_id: int) -> bool | None:+ # The SDK annotates feature_enabled as returning bool, but it returns+ # None when local evaluation can't resolve the flag. Widen the type so+ # callers can handle the None branch under type checking.+ result: bool | None = posthoganalytics.feature_enabled(+ KAFKA_ROUTING_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,+ )+ return result+++def get_team_primary_flags_writer(team_id: int) -> str:+ """Which writer owns this team's flags.json entry: "rust" when the routing+ flag sends its invalidations to the Kafka builder, otherwise "python".++ Attributes verifier fixes to the writer whose output needed fixing. During+ the Kafka-builder ramp, a fix on a rust-routed team is the signal that the+ Rust builder diverged from the Python one, which the unattributed fix+ counter cannot separate from baseline repair noise. Evaluation failures+ resolve to "unknown" rather than "python" so an attribution outage cannot+ masquerade as a clean Rust ramp.+ """+ try:+ result = _evaluate_kafka_routing_flag(team_id)+ except SoftTimeLimitExceeded:+ # A Celery soft-time-limit is a task-control signal, not an attribution+ # failure. Let it propagate so the verify sweep winds down, matching the+ # other SoftTimeLimitExceeded guards in the verifier.+ raise+ except Exception:+ # Mirror _route_to_kafka's evaluation-failure logging so a broken+ # attribution client is diagnosable in Sentry, because otherwise it only+ # shows up as a rise in writer="unknown" that cannot be told apart from a+ # cold local flag cache (which returns None below and is expected at boot).+ logger.warning(+ "flags_cache_writer_attribution_flag_evaluation_failed",+ team_id=team_id,+ flag=KAFKA_ROUTING_FLAG,+ exc_info=True,+ )+ return "unknown"+ if result is None:+ return "unknown"+ return "rust" if result else "python"++def _route_to_kafka(team_id: int) -> bool:"""Return True if this team's invalidation should route to Kafka instead of Celery.@@ -1054,17 +1111,7 @@ def _route_to_kafka(team_id: int) -> bool: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(- KAFKA_ROUTING_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,- )+ result = _evaluate_kafka_routing_flag(team_id)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.diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex 38b2ce77cf0d..f8d4fc0382c1 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -34,6 +34,7 @@ from posthog.storage.cache_expiry_manager import CacheRefreshCountsfrom products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import Experimentfrom products.feature_flags.backend.flags_cache import (+ FLAGS_HYPERCACHE_MANAGEMENT_CONFIG,_blank_inactive_filters,_compare_flag_fields,_compute_flag_dependencies,@@ -49,6 +50,7 @@ from products.feature_flags.backend.flags_cache import (flags_hypercache,get_flags_from_cache,get_team_ids_with_recently_updated_flags,+ get_team_primary_flags_writer,get_teams_with_flags_queryset,update_flags_cache,verify_team_flags,@@ -912,6 +914,50 @@ class TestServiceFlagsKafkaRouting(BaseTest):mock_produce.assert_not_called()+class TestGetTeamPrimaryFlagsWriter(unittest.TestCase):+ @parameterized.expand(+ [+ ("routed_to_kafka", True, "rust"),+ ("routed_to_celery", False, "python"),+ ("flag_cache_cold", None, "unknown"),+ ]+ )+ def test_maps_routing_flag_result_to_writer(self, _name, flag_result, expected_writer):+ with (+ patch(+ "products.feature_flags.backend.flags_cache.posthoganalytics.feature_enabled",+ return_value=flag_result,+ ),+ patch("products.feature_flags.backend.flags_cache.logger") as mock_logger,+ ):+ assert get_team_primary_flags_writer(42) == expected_writer+ # A cold flag cache is expected at boot and must stay silent; only a raising+ # client warrants the evaluation-failed warning.+ mock_logger.warning.assert_not_called()++ def test_flag_evaluation_error_is_unknown_and_warns(self):+ with (+ patch(+ "products.feature_flags.backend.flags_cache.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("posthoganalytics borked"),+ ),+ patch("products.feature_flags.backend.flags_cache.logger") as mock_logger,+ ):+ assert get_team_primary_flags_writer(42) == "unknown"+ mock_logger.warning.assert_called_once()+ assert mock_logger.warning.call_args.args[0] == "flags_cache_writer_attribution_flag_evaluation_failed"+ assert mock_logger.warning.call_args.kwargs["team_id"] == 42++ def test_flags_config_attributes_fixes_via_the_routing_gate(self):+ with patch(+ "products.feature_flags.backend.flags_cache.posthoganalytics.feature_enabled",+ return_value=True,+ ) as mock_feature_enabled:+ assert FLAGS_HYPERCACHE_MANAGEMENT_CONFIG.get_primary_writer_fn is not None+ assert FLAGS_HYPERCACHE_MANAGEMENT_CONFIG.get_primary_writer_fn(42) == "rust"+ assert mock_feature_enabled.call_args.args[1] == "team-42"++@override_settings(FLAGS_REDIS_URL="redis://test")class TestServiceFlagsCeleryTasks(BaseTest):"""Test Celery task integration for service flags cache updates."""