: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): read last_called_at sync calls from flag_evaluations behind a setting (#110150)
Phil Haackfe2d6a92fad9
diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 47adca53db9c..354fb4b0a513 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -51,8 +51,13 @@ FEATURE_FLAG_LAST_CALLED_AT_SYNC_MAX_LOOKBACK_HOURS: int = max(1,get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_MAX_LOOKBACK_HOURS", 6, type_cast=int),)-# The sync reads distributed_events_recent, which either replica of the batch-export shard can-# answer, so rows inserted moments ago may be missing from whichever one serves a given query.+# Use "flag_evaluations" only where ingestion forks every team's flag calls into that table. The historical+# and async ingestion lanes never fork, so calls ingested on them do not move last_called_at with this source.+# Disabling the fork also stops last_called_at with this source, and the checkpoint keeps moving past the missed+# calls. Switch this back to "events" before disabling the fork.+FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE: str = get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE", "events")+# Both source tables are Distributed reads that either replica of a shard can answer, so rows+# inserted moments ago may be missing from whichever one serves a given query.# Ending the scan window this far before now keeps the checkpoint from advancing past those# rows, so a row still missing at read time is picked up by the next run instead of being# skipped for good.@@ -60,6 +65,13 @@ FEATURE_FLAG_LAST_CALLED_AT_SYNC_REPLICATION_BUFFER_SECONDS: int = max(0,get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_REPLICATION_BUFFER_SECONDS", 60, type_cast=int),)+# Replaces the buffer above when the source is flag_evaluations. That table stamps inserted_at with the Kafka+# message time, before ClickHouse writes the row, so this buffer must also cover the ClickHouse consumer lag.+# A row that ClickHouse writes later than this falls behind the checkpoint and is never read.+FEATURE_FLAG_LAST_CALLED_AT_SYNC_FLAG_EVALUATIONS_BUFFER_SECONDS: int = max(+ 0,+ get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_FLAG_EVALUATIONS_BUFFER_SECONDS", 900, type_cast=int),+)# Per-chunk ClickHouse execution cap. sync_execute sets no max_execution_time of its own, so# without this a hung query is bounded only by the server profile, and a run can outlive the# 30-minute lock that stops two of these from overlapping. Prod chunks take a few seconds eachdiff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 94df81ea697a..dc43ec75948f 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -1284,6 +1284,7 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:- No time limits - task runs until completeConfiguration (via settings.feature_flags):+ - FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE: "events" or "flag_evaluations" (default: "events")- FEATURE_FLAG_LAST_CALLED_AT_SYNC_BATCH_SIZE: Bulk update batch size (default: 1000)- FEATURE_FLAG_LAST_CALLED_AT_SYNC_CLICKHOUSE_LIMIT: Max ClickHouse results per chunk (default: 100000)- FEATURE_FLAG_LAST_CALLED_AT_SYNC_LOOKBACK_DAYS: Fallback lookback period (default: 1)@@ -1295,9 +1296,12 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:from django.core.cache import cachefrom posthog.clickhouse.client import sync_execute+ from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_TABLEfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+ # Both sources share this checkpoint, so a source switch resumes where the old source stopped.+ # last_called_at only moves forward, so a call that both sources read at the switch changes nothing.FEATURE_FLAG_LAST_CALLED_SYNC_KEY = "posthog:feature_flag_last_called_sync:last_timestamp"LOCK_KEY = "posthog:feature_flag_last_called_sync:lock"LOCK_TIMEOUT = 1800 # 30 minutes = schedule interval (prevents concurrent execution)@@ -1310,6 +1314,11 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:start_time = timezone.now()+ source = settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE+ if source not in ("events", "flag_evaluations"):+ logger.warning("Unknown feature flag sync source, reading events instead", source=source)+ source = "events"+tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.ENRICHMENT, name="sync_feature_flag_last_called")# Create metrics gauges for this task run@@ -1366,15 +1375,19 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:)last_sync_timestamp = max_lookback- # Stop short of now so rows that have not reached the replica answering this query yet- # fall into the next run's window rather than being skipped for good.- current_sync_timestamp = now - timedelta(- seconds=settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_REPLICATION_BUFFER_SECONDS+ # Stop short of now so rows that have not reached ClickHouse or the replica answering this+ # query yet fall into the next run's window rather than being skipped for good.+ buffer_seconds = (+ settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_FLAG_EVALUATIONS_BUFFER_SECONDS+ if source == "flag_evaluations"+ else settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_REPLICATION_BUFFER_SECONDS)+ current_sync_timestamp = now - timedelta(seconds=buffer_seconds)window_seconds = (current_sync_timestamp - last_sync_timestamp).total_seconds()logger.info("Starting feature flag sync",+ source=source,last_sync_timestamp=last_sync_timestamp.isoformat(),current_sync_timestamp=current_sync_timestamp.isoformat(),window_seconds=window_seconds,@@ -1405,7 +1418,7 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:# `posthog/models/event/sql.py` defines the two identically, so dev and CI cannot# tell them apart and no test covers the difference. Check the live offline host# rather than this repo before changing the table.- chunk_query = """+ events_query = """SELECTteam_id,JSONExtractString(properties, '$feature_flag') as flag_key,@@ -1421,6 +1434,22 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:ORDER BY last_called_at DESCLIMIT %(limit)s"""+ flag_evaluations_query = f"""+ SELECT+ team_id,+ flag_key,+ max(timestamp) as last_called_at,+ count() as call_count+ FROM {FLAG_EVALUATIONS_TABLE}+ PREWHERE inserted_at > %(last_sync_timestamp)s+ AND inserted_at <= %(current_sync_timestamp)s+ WHERE flag_key != ''+ AND timestamp <= %(current_sync_timestamp)s+ GROUP BY team_id, flag_key+ ORDER BY last_called_at DESC+ LIMIT %(limit)s+ """+ chunk_query = flag_evaluations_query if source == "flag_evaluations" else events_querylimit_hit = Falsechunk_failures = 0diff --git a/products/feature_flags/backend/test/test_feature_flag_sync.py b/products/feature_flags/backend/test/test_feature_flag_sync.pyindex da76f017e72d..79120a507c66 100644--- a/products/feature_flags/backend/test/test_feature_flag_sync.py+++ b/products/feature_flags/backend/test/test_feature_flag_sync.py@@ -1,7 +1,9 @@-from datetime import datetime+import json+import uuid+from datetime import datetime, timedeltaimport time_machine-from posthog.test.base import BaseTest+from posthog.test.base import BaseTest, ClickhouseTestMixinfrom unittest.mock import MagicMock, Mock, patchfrom django.core.cache import cache@@ -13,8 +15,15 @@ from parameterized import parameterizedfrom prometheus_client import REGISTRYfrom redis.exceptions import ConnectionError as RedisConnectionError+from posthog.clickhouse.client import sync_executefrom posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorTooManyBytes, CHQueryErrorUnknownTablefrom posthog.exceptions import ClickHouseAtCapacity+from posthog.models.event.sql import EVENTS_RECENT_DATA_TABLE, SHARDED_EVENTS_RECENT_DATA_TABLE+from posthog.models.flag_evaluations.sql import (+ FLAG_EVALUATIONS_DATA_TABLE,+ FLAG_EVALUATIONS_SOURCE_EVENT,+ FLAG_EVALUATIONS_WRITABLE_TABLE,+)from posthog.tasks.tasks import sync_feature_flag_last_calledfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -770,3 +779,111 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):# A retry that fails is not a recoveryassert (REGISTRY.get_sample_value(recoveries_metric) or 0.0) == recoveries_before + 1+++FLAG_CALL_INSERT_TABLE = {"events": EVENTS_RECENT_DATA_TABLE(), "flag_evaluations": FLAG_EVALUATIONS_WRITABLE_TABLE}+++@override_settings(+ FEATURE_FLAG_LAST_CALLED_AT_SYNC_CHUNK_MINUTES=1440,+ FEATURE_FLAG_LAST_CALLED_AT_SYNC_MAX_LOOKBACK_HOURS=24,+)+class TestSyncFeatureFlagLastCalledSource(ClickhouseTestMixin, BaseTest):+ def setUp(self) -> None:+ super().setUp()+ cache.clear()+ redis_patcher = patch("posthog.tasks.tasks.get_client", return_value=mock_redis_client())+ redis_patcher.start()+ self.addCleanup(redis_patcher.stop)++ # The task reads every team, so rows that earlier tests left in these tables compete for the row limit.+ sync_execute(f"TRUNCATE TABLE {SHARDED_EVENTS_RECENT_DATA_TABLE()}")+ sync_execute(f"TRUNCATE TABLE {FLAG_EVALUATIONS_DATA_TABLE}")++ FeatureFlag.objects.create(team=self.team, key="called-in-events", created_by=self.user)+ FeatureFlag.objects.create(team=self.team, key="called-in-flag-evaluations", created_by=self.user)++ def tearDown(self) -> None:+ cache.clear()+ super().tearDown()++ def _insert_flag_call(self, source: str, flag_key: str, called_at: datetime, inserted_at: datetime) -> None:+ sync_execute(+ f"INSERT INTO {FLAG_CALL_INSERT_TABLE[source]} (uuid, event, properties, timestamp, team_id, distinct_id, inserted_at) VALUES",+ [+ (+ str(uuid.uuid4()),+ FLAG_EVALUATIONS_SOURCE_EVENT,+ json.dumps({"$feature_flag": flag_key}),+ called_at,+ self.team.pk,+ "some-distinct-id",+ inserted_at,+ )+ ],+ )++ def _last_called_at_by_key(self) -> dict[str, datetime | None]:+ return dict(FeatureFlag.objects.filter(team=self.team).values_list("key", "last_called_at"))++ @parameterized.expand(+ [+ ("default_setting", {}, "events"),+ ("flag_evaluations", {"FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE": "flag_evaluations"}, "flag_evaluations"),+ ("unknown_value", {"FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE": "not-a-source"}, "events"),+ ]+ )+ def test_reads_flag_calls_from_the_configured_source(+ self, _name: str, source_settings: dict[str, str], read_source: str+ ) -> None:+ now = tz.now()+ # The call happened before the scan window opened and reached ClickHouse inside it.+ # Only a filter on inserted_at reads it.+ called_at = (now - timedelta(days=2)).replace(microsecond=0)+ inserted_at = now - timedelta(minutes=20)+ self._insert_flag_call("events", "called-in-events", called_at, inserted_at)+ self._insert_flag_call("flag_evaluations", "called-in-flag-evaluations", called_at, inserted_at)++ with self.settings(**source_settings):+ sync_feature_flag_last_called()++ assert self._last_called_at_by_key() == {+ "called-in-events": called_at if read_source == "events" else None,+ "called-in-flag-evaluations": called_at if read_source == "flag_evaluations" else None,+ }++ @parameterized.expand([("events", "called-in-events"), ("flag_evaluations", "called-in-flag-evaluations")])+ def test_call_without_a_flag_key_does_not_take_the_row_limit(self, source: str, flag_key: str) -> None:+ now = tz.now()+ called_at = (now - timedelta(minutes=30)).replace(microsecond=0)+ inserted_at = now - timedelta(minutes=20)+ self._insert_flag_call(source, flag_key, called_at, inserted_at)+ # The query sorts the newest call first. Without the empty-key filter, this call takes the only row.+ self._insert_flag_call(source, "", now - timedelta(minutes=25), inserted_at)++ with self.settings(+ FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE=source,+ FEATURE_FLAG_LAST_CALLED_AT_SYNC_CLICKHOUSE_LIMIT=1,+ ):+ sync_feature_flag_last_called()++ assert self._last_called_at_by_key()[flag_key] == called_at++ @parameterized.expand(+ [("events", "called-in-events", True), ("flag_evaluations", "called-in-flag-evaluations", False)]+ )+ def test_call_inside_the_buffer_waits_for_a_later_run(+ self, source: str, flag_key: str, read_on_first_run: bool+ ) -> None:+ now = tz.now()+ called_at = (now - timedelta(minutes=5)).replace(microsecond=0)+ self._insert_flag_call(source, flag_key, called_at, now - timedelta(minutes=5))++ with self.settings(FEATURE_FLAG_LAST_CALLED_AT_SYNC_SOURCE=source):+ sync_feature_flag_last_called()+ assert self._last_called_at_by_key()[flag_key] == (called_at if read_on_first_run else None)++ with time_machine.travel(now + timedelta(minutes=16)):+ sync_feature_flag_last_called()++ assert self._last_called_at_by_key()[flag_key] == called_at