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): read flag last_called_at for data freshness (#110143)

Phil Haack8975d4bf584c
diff --git a/posthog/data_freshness.py b/posthog/data_freshness.py
index c3320babd24b..b3a5edec56c8 100644
--- a/posthog/data_freshness.py
+++ b/posthog/data_freshness.py
@@ -21,7 +21,7 @@ from enum import StrEnum
from functools import lru_cache, partial
from typing import Optional
-from django.db.models import BigIntegerField, Case, CharField, Max, Value, When
+from django.db.models import BigIntegerField, Case, CharField, Max, Model, QuerySet, Value, When
from django.db.models.functions import Coalesce
import structlog
@@ -81,6 +81,20 @@ class ProbeWindow:
SourceProbe = Callable[[list[int], ProbeWindow], dict[int, datetime]]
+def latest_per_team(
+ queryset: QuerySet[Model], field: str, team_ids: list[int], window: ProbeWindow
+) -> dict[int, datetime]:
+ """The newest `field` value per team within the window."""
+ rows = (
+ queryset.filter(team_id__in=team_ids, **{f"{field}__gte": window.cutoff, f"{field}__lte": window.horizon})
+ .values("team_id")
+ .annotate(latest=Max(field))
+ )
+ # The timeout is transaction-local, so the queryset must run inside this block.
+ with execute_with_timeout(POSTGRES_TIMEOUT_MS):
+ return {row["team_id"]: row["latest"] for row in rows}
+
+
@dataclass(frozen=True, kw_only=True)
class DataSourceSpec:
"""How one product tells whether a project received its kind of data recently.
diff --git a/posthog/test/test_data_freshness.py b/posthog/test/test_data_freshness.py
index e75b23b78165..03e0d0ac99f8 100644
--- a/posthog/test/test_data_freshness.py
+++ b/posthog/test/test_data_freshness.py
@@ -1,13 +1,30 @@
from datetime import UTC, datetime, timedelta
+from typing import Optional
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
from django.test import SimpleTestCase
from parameterized import parameterized
-from posthog.data_freshness import Freshness, ProjectFreshness, derive_freshness, reportable
+from posthog.data_freshness import (
+ LOOKBACK_DAYS,
+ DataSourceSpec,
+ Freshness,
+ ProjectFreshness,
+ SourceFreshness,
+ _compute,
+ derive_freshness,
+ reportable,
+)
from posthog.models.team.team import Team
from posthog.schema_enums import ProductKey
+from products.event_definitions.backend.models.event_definition import EventDefinition
+from products.feature_flags.backend.data_freshness import DATA_SOURCES as FEATURE_FLAGS_DATA_SOURCES
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
NOW = datetime(2026, 8, 3, 12, 0, tzinfo=UTC)
QUIET_BEFORE = NOW - timedelta(days=7)
@@ -90,3 +107,89 @@ class TestDeriveFreshness(SimpleTestCase):
self.assertEqual(reportable(results, degraded=False), results)
self.assertEqual([r.team_id for r in reportable(results, degraded=True)], [1])
+
+
+class TestFeatureFlagsFreshness(BaseTest):
+ other_team: Team
+ other_team_called_at: datetime
+
+ @classmethod
+ def setUpTestData(cls) -> None:
+ super().setUpTestData()
+ cls.other_team = Team.objects.create(organization=cls.organization)
+ cls.other_team_called_at = datetime.now(UTC) - timedelta(minutes=5)
+ FeatureFlag.objects.create(
+ team=cls.other_team, key="busy-flag", created_by=cls.user, last_called_at=cls.other_team_called_at
+ )
+
+ def setUp(self) -> None:
+ super().setUp()
+ # Production also runs the product analytics residual. It takes `$feature_flag_called`
+ # when the flags spec stops claiming the event.
+ residual = DataSourceSpec(product=ProductKey.PRODUCT_ANALYTICS, is_residual=True)
+ patcher = patch(
+ "posthog.data_freshness.discover_data_sources",
+ return_value=(*FEATURE_FLAGS_DATA_SOURCES, residual),
+ )
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ @parameterized.expand(
+ [
+ (
+ "latest call across flags without an event definition",
+ [None, timedelta(days=3), timedelta(hours=1)],
+ False,
+ None,
+ timedelta(hours=1),
+ ),
+ ("soft-deleted flag still called", [timedelta(hours=1)], True, None, timedelta(hours=1)),
+ ("event definition for a key with no flag", [], False, timedelta(hours=2), timedelta(hours=2)),
+ (
+ "event definition newer than the latest flag call",
+ [timedelta(days=3)],
+ False,
+ timedelta(hours=2),
+ timedelta(hours=2),
+ ),
+ (
+ "flag call newer than the event definition",
+ [timedelta(hours=1)],
+ False,
+ timedelta(hours=2),
+ timedelta(hours=1),
+ ),
+ ("last call before the lookback window", [timedelta(days=LOOKBACK_DAYS + 1)], False, None, None),
+ ]
+ )
+ def test_flag_calls(
+ self,
+ _name: str,
+ called_ago: list[Optional[timedelta]],
+ deleted: bool,
+ event_definition_ago: Optional[timedelta],
+ expected_ago: Optional[timedelta],
+ ) -> None:
+ now = datetime.now(UTC)
+ for index, ago in enumerate(called_ago):
+ FeatureFlag.objects.create(
+ team=self.team,
+ key=f"flag-{index}",
+ created_by=self.user,
+ last_called_at=None if ago is None else now - ago,
+ deleted=deleted,
+ )
+ if event_definition_ago is not None:
+ EventDefinition.objects.create(
+ team=self.team, name="$feature_flag_called", last_seen_at=now - event_definition_ago
+ )
+
+ results = {result.team_id: result for result in _compute([self.team, self.other_team])}
+
+ expected_sources = (
+ [SourceFreshness(data_source=ProductKey.FEATURE_FLAGS, last_data_at=now - expected_ago)]
+ if expected_ago is not None
+ else []
+ )
+ self.assertEqual(results[self.team.id].sources, expected_sources)
+ self.assertEqual(results[self.other_team.id].last_data_at, self.other_team_called_at)
diff --git a/products/feature_flags/backend/data_freshness.py b/products/feature_flags/backend/data_freshness.py
index 55dc348b313a..259e1db6eb62 100644
--- a/products/feature_flags/backend/data_freshness.py
+++ b/products/feature_flags/backend/data_freshness.py
@@ -1,6 +1,25 @@
-from posthog.data_freshness import DataSourceSpec
+from datetime import datetime
+
+from posthog.data_freshness import DataSourceSpec, ProbeWindow, latest_per_team
from posthog.schema_enums import ProductKey
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+
+def last_flag_call_at(team_ids: list[int], window: ProbeWindow) -> dict[int, datetime]:
+ """Read the per-flag call stamp that the `last_called_at` sync writes.
+
+ No event definition records flag calls for organizations on `FLAG_EVALUATIONS_ONLY`, because
+ their `$feature_flag_called` events skip `events`. This stamp covers them only when the sync
+ reads `flag_evaluations`. A soft-deleted flag keeps the stamp of calls made before deletion.
+ """
+ return latest_per_team(FeatureFlag.objects_including_soft_deleted.all(), "last_called_at", team_ids, window)
+
+
# Flag evaluations, not flag edits: a project with flags configured but nothing calling them
-# is not receiving data.
-DATA_SOURCES = [DataSourceSpec(product=ProductKey.FEATURE_FLAGS, event_names=("$feature_flag_called",))]
+# is not receiving data. The spec also claims the event name, because otherwise the product
+# analytics residual would count it. The event definition also catches calls for keys with no
+# undeleted flag, because the sync only stamps undeleted flags it finds by key.
+DATA_SOURCES = [
+ DataSourceSpec(product=ProductKey.FEATURE_FLAGS, event_names=("$feature_flag_called",), probe=last_flag_call_at)
+]
diff --git a/products/warehouse_sources/backend/data_freshness.py b/products/warehouse_sources/backend/data_freshness.py
index 7b573be1afd9..a56e92fc26e8 100644
--- a/products/warehouse_sources/backend/data_freshness.py
+++ b/products/warehouse_sources/backend/data_freshness.py
@@ -1,9 +1,6 @@
from datetime import datetime
-from django.db.models import Max
-
-from posthog.data_freshness import POSTGRES_TIMEOUT_MS, DataSourceSpec, ProbeWindow
-from posthog.models.utils import execute_with_timeout
+from posthog.data_freshness import DataSourceSpec, ProbeWindow, latest_per_team
from posthog.schema_enums import ProductKey
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
@@ -17,17 +14,7 @@ def last_sync_at(team_ids: list[int], window: ProbeWindow) -> dict[int, datetime
one row per schema off the team FK, and is what the rest of the codebase treats as "last
successful sync".
"""
- rows = (
- ExternalDataSchema.objects.filter(
- team_id__in=team_ids,
- last_synced_at__gte=window.cutoff,
- last_synced_at__lte=window.horizon,
- )
- .values("team_id")
- .annotate(last_synced=Max("last_synced_at"))
- )
- with execute_with_timeout(POSTGRES_TIMEOUT_MS):
- return {row["team_id"]: row["last_synced"] for row in rows}
+ return latest_per_team(ExternalDataSchema.objects.all(), "last_synced_at", team_ids, window)
DATA_SOURCES = [DataSourceSpec(product=ProductKey.DATA_WAREHOUSE, probe=last_sync_at)]