: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
perf(hogql): trim per-build I/O in database source fetching (#92325)
George Munyorod4ea871ef3aa
diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.pyindex c33dbf81f651..2774f1d9d00b 100644--- a/posthog/api/test/test_event.py+++ b/posthog/api/test/test_event.py@@ -108,8 +108,9 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):# personhog, not Postgres, so it's not in this count. Was 16 before passing team=team# into get_restricted_properties_for_team, which lets is_property_access_control_enabled# skip its per-call Team+organization lookup. +1 for the saved-expressions fetch in the- # HogQL database build.- with self.assertNumQueries(15):+ # HogQL database build. +1 for the flag-cache TTL instance setting, cold-cache here but+ # TTL-cached per worker in production.+ with self.assertNumQueries(16):response = self.client.get(f"/api/projects/{self.team.id}/events/?event=event_name").json()assert response["results"][0]["event"] == "event_name"@@ -140,8 +141,9 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):# Group-type-mapping is read via personhog, not Postgres, so it's not in this count.# Was 24 before passing team=team into get_restricted_properties_for_team, which lets# is_property_access_control_enabled skip its per-call Team+organization lookup.- # +1 for the saved-expressions fetch in the HogQL database build.- expected_queries = 22 if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA else 23+ # +1 for the saved-expressions fetch in the HogQL database build. +1 for the flag-cache+ # TTL instance setting, cold-cache here but TTL-cached per worker in production.+ expected_queries = 23 if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA else 24with self.assertNumQueries(expected_queries):response = self.client.get(diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.pyindex 1f04019f7e4e..8ded34f1b9cc 100644--- a/posthog/api/test/test_person.py+++ b/posthog/api/test/test_person.py@@ -1958,9 +1958,10 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):returned_ids = []# The property-access-control feature check reuses the request's already-loaded team,# so listing persons no longer pays a per-request Team lookup (was 16). +1 for the- # saved-expressions fetch in the HogQL database build. +1 for the shared-database- # kill-switch instance setting, cold-cache here but TTL-cached per worker in production.- with self.assertNumQueries(16):+ # saved-expressions fetch in the HogQL database build. +1 each for the shared-database+ # kill-switch and flag-cache TTL instance settings, cold-cache here but TTL-cached per+ # worker in production.+ with self.assertNumQueries(17):response = self.client.get("/api/person/?limit=10").json()self.assertEqual(len(response["results"]), 9)returned_ids += [x["distinct_ids"][0] for x in response["results"]]diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 4145681f07a7..67fd872379d7 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport ioimport copy+import timeimport pickleimport threadingimport dataclasses@@ -406,6 +407,75 @@ ROOT_TABLES__DO_NOT_ADD_ANY_MORE: dict[str, TableNode] = {_DATABASE_ROOT_NODE_BLOBS: dict[bool, bytes] = {}_DATABASE_ROOT_NODE_BLOBS_LOCK = threading.Lock()+# Every database build evaluates the same per-team feature-flag decisions, and flag evaluation+# costs property matching per call and can fall back to a network call. A short per-process TTL+# bounds that cost; a flag flip lags at most the TTL. Only flags in the allowlist below are ever+# cached: a flag that gates authorization or enforcement (who can see which data) must stay out,+# because a cached stale False holds enforcement open team-wide for the TTL. Availability flags+# (which schema surfaces exist) tolerate that lag. Entries store their evaluation time, and reads+# check freshness against the live TTL, so lowering the setting immediately shortens every existing+# entry's life and disabling it stops all reads. Expired entries are only replaced on re-request,+# so on a long-lived worker the dict grows with distinct-team count; at the cap, sweep the expired+# entries first and drop everything only if live entries alone still exceed it - simpler than an+# LRU, and fresh entries survive the sweep. Reads are lock-free (dict.get is atomic under the+# GIL); mutations and the sweep hold the lock, because the sweep iterates the dict and concurrent+# inserts would raise RuntimeError mid-iteration.+_CACHEABLE_TEAM_FLAGS = frozenset({"managed-viewsets", "data-quality-checks"})+_TEAM_FLAG_CACHE: dict[tuple[str, str], tuple[float, bool]] = {} # key -> (evaluated_at, value)+_TEAM_FLAG_CACHE_LOCK = threading.Lock()+_TEAM_FLAG_CACHE_MAX_ENTRIES = 50_000+++def _evaluate_warehouse_access_control_flag(team: Team) -> bool:+ """Never cached, in the flag cache or via cached sources: this flag gates enforcement. A stale+ False (a flag flip, or a transient SDK failure that feature_enabled_or_false reports as False)+ would keep warehouse access control off for every query on the team until a TTL expires."""+ return feature_enabled_or_false(+ "hogql-warehouse-access-control",+ str(team.uuid),+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ group_properties={+ "organization": {"id": str(team.organization_id)},+ "project": {"id": str(team.id)},+ },+ send_feature_flag_events=False,+ )+++def _cached_team_flag(flag_key: str, team: Team, evaluate: Callable[[], bool]) -> bool:+ # Not cache_for/CachedFunction: its TTL is fixed at decoration time, and this TTL is a live+ # instance setting so ops can retune or disable the cache without a redeploy.+ # Function-local: keeps the Django model import off the django.setup() path. The instance+ # setting has its own 60s in-process cache, so this read costs one query per worker per+ # minute, not one per build.+ from posthog.models.instance_setting import get_instance_setting # noqa: PLC0415++ if flag_key not in _CACHEABLE_TEAM_FLAGS:+ return evaluate()+ try:+ # int(): the setting round-trips through InstanceSetting's raw JSON storage, so a value+ # edited in the Django admin can come back as a str, float, or blank string.+ ttl = int(get_instance_setting("HOGQL_TEAM_FLAG_CACHE_TTL_SECONDS"))+ except (TypeError, ValueError):+ ttl = 0+ if ttl <= 0:+ return evaluate()+ cache_key = (str(team.uuid), flag_key)+ now = time.monotonic()+ hit = _TEAM_FLAG_CACHE.get(cache_key)+ if hit is not None and now - hit[0] < ttl:+ return hit[1]+ value = evaluate()+ with _TEAM_FLAG_CACHE_LOCK:+ if len(_TEAM_FLAG_CACHE) >= _TEAM_FLAG_CACHE_MAX_ENTRIES:+ for stale_key in [key for key, (evaluated_at, _) in _TEAM_FLAG_CACHE.items() if now - evaluated_at >= ttl]:+ _TEAM_FLAG_CACHE.pop(stale_key, None)+ if len(_TEAM_FLAG_CACHE) >= _TEAM_FLAG_CACHE_MAX_ENTRIES:+ _TEAM_FLAG_CACHE.clear()+ _TEAM_FLAG_CACHE[cache_key] = (now, value)+ return value++# We only ever load our own freshly-built blob, but restrict the unpickler anyway as defense in depth:# it can reconstruct only the classes the catalog is built from, so even a future change that fed it# untrusted bytes couldn't instantiate arbitrary code (os.system, etc.). Every catalog class lives@@ -1603,6 +1673,12 @@ class Database(BaseModel):user_access_control=fresh_access_control,denied_system_table_names=fresh_denied,)+ # Enforcement flags must not ride the cached bundle either (see+ # _evaluate_warehouse_access_control_flag); recompute per request.+ sources = dataclasses.replace(+ sources,+ is_hogql_warehouse_access_control_enabled=_evaluate_warehouse_access_control_flag(cast("Team", team)),+ )with HOGQL_DATABASE_BUILD_DURATION_SECONDS.labels(phase="build_from_sources").time():return Database._build_from_sources(@@ -1742,29 +1818,35 @@ class Database(BaseModel):is_direct_query = connection_id is not Nonewith timings.measure("feature_flags", emit_span=True):- is_managed_viewset_enabled = feature_enabled_or_false(+ is_managed_viewset_enabled = _cached_team_flag("managed-viewsets",- str(team.uuid),- groups={- "organization": str(team.organization_id),- "project": str(team.id),- },- group_properties={- "organization": {- "id": str(team.organization_id),+ team,+ lambda: feature_enabled_or_false(+ "managed-viewsets",+ str(team.uuid),+ groups={+ "organization": str(team.organization_id),+ "project": str(team.id),},- "project": {- "id": str(team.id),+ group_properties={+ "organization": {+ "id": str(team.organization_id),+ },+ "project": {+ "id": str(team.id),+ },},- },- send_feature_flag_events=False,+ send_feature_flag_events=False,+ ),)# Function-local + facade-only: keeps the products off the django.setup() path.from products.data_quality.backend.facade.flags import is_data_quality_checks_enabled # noqa: PLC0415from products.feature_flags.backend.facade.flags import is_flag_evaluations_table_enabled # noqa: PLC0415- data_quality_enabled = is_data_quality_checks_enabled(team)+ data_quality_enabled = _cached_team_flag(+ "data-quality-checks", team, lambda: is_data_quality_checks_enabled(team)+ )# A direct-connection catalog has no "posthog" node to hold the table.include_flag_evaluations_table = not is_direct_query and is_flag_evaluations_table_enabled(team)@@ -1828,16 +1910,7 @@ class Database(BaseModel):team, user, user_access_control, allowed_system_tables)- is_hogql_warehouse_access_control_enabled = feature_enabled_or_false(- "hogql-warehouse-access-control",- str(team.uuid),- groups={"organization": str(team.organization_id), "project": str(team.id)},- group_properties={- "organization": {"id": str(team.organization_id)},- "project": {"id": str(team.id)},- },- send_feature_flag_events=False,- )+ is_hogql_warehouse_access_control_enabled = _evaluate_warehouse_access_control_flag(team)with timings.measure("modifiers", emit_span=True):modifiers = create_default_modifiers_for_team(team, modifiers)@@ -1993,22 +2066,17 @@ class Database(BaseModel):_attach_decrypted_credentials(credentialed_tables, team_id=team.pk)# Prefetch the saved query each modifier may resolve against; the table models come from the- # warehouse_tables fetch.+ # warehouse_tables fetch. One query for all names: (team, name) is unique, so each name maps+ # to at most one row.event_modifier_saved_queries: dict[str, Optional[DataWarehouseSavedQuery]] = {}if modifiers.dataWarehouseEventsModifiers:with timings.measure("data_warehouse_event_modifiers_fetch", emit_span=True):- for warehouse_modifier in modifiers.dataWarehouseEventsModifiers:- name = warehouse_modifier.table_name- if name in event_modifier_saved_queries:- continue- try:- event_modifier_saved_queries[name] = (- DataWarehouseSavedQuery.objects.exclude(deleted=True)- .filter(team_id=team.pk, name=name)- .latest("created_at")- )- except DataWarehouseSavedQuery.DoesNotExist:- event_modifier_saved_queries[name] = None+ names = {warehouse_modifier.table_name for warehouse_modifier in modifiers.dataWarehouseEventsModifiers}+ event_modifier_saved_queries = dict.fromkeys(names)+ for saved_query in DataWarehouseSavedQuery.objects.exclude(deleted=True).filter(+ team_id=team.pk, name__in=names+ ):+ event_modifier_saved_queries[saved_query.name] = saved_queryreturn HogQLDatabaseSources(team=team,diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex bb4238282129..ed0509841373 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -12,7 +12,7 @@ from typing import Any, castimport pytestfrom posthog.test.base import BaseTest, FuzzyInt, QueryMatchingTest, snapshot_postgres_queriesfrom unittest import TestCase-from unittest.mock import patch+from unittest.mock import Mock, patchfrom django.conf import settingsfrom django.db import connection@@ -36,8 +36,10 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.database import (_CATALOG_PICKLE_MODULE_PREFIXES,_CATALOG_PICKLE_MODULES,+ _TEAM_FLAG_CACHE,ROOT_TABLES__DO_NOT_ADD_ANY_MORE,Database,+ _cached_team_flag,_CatalogUnpickler,_compute_system_table_access_decision,_construct_database_root_node,@@ -1155,6 +1157,41 @@ class TestDatabase(BaseTest, QueryMatchingTest):assert "some_field" in db.get_table("events").fieldsassert "timestamp" in db.get_table("whatever0").fields+ def test_event_modifier_fetch_is_one_query_for_all_names(self):+ found = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="found", query={"query": "SELECT 1 AS id"}, columns={"id": "String"}+ )+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="soft_deleted",+ query={"query": "SELECT 2 AS id"},+ columns={"id": "String"},+ deleted=True,+ )++ def modifier(name: str) -> DataWarehouseEventsModifier:+ return DataWarehouseEventsModifier(+ table_name=name, id_field="id", timestamp_field="created_at", distinct_id_field="id"+ )++ def fetch(names: list[str]) -> tuple[int, dict]:+ modifiers = create_default_modifiers_for_team(+ self.team, modifiers=HogQLQueryModifiers(dataWarehouseEventsModifiers=[modifier(n) for n in names])+ )+ with CaptureQueriesContext(connection) as context:+ sources = Database._fetch_sources(team=self.team, modifiers=modifiers)+ return len(context.captured_queries), sources.event_modifier_saved_queries++ fetch(["found"]) # warm per-process caches so the measured fetches differ only in name count+ single_count, _ = fetch(["found"])+ triple_count, saved_queries = fetch(["found", "soft_deleted", "missing"])++ # One bulk query serves any number of modifier names.+ assert triple_count == single_count+ assert saved_queries["found"].id == found.id+ assert saved_queries["soft_deleted"] is None+ assert saved_queries["missing"] is None+@staticmethoddef _ran_source_fetch_queries(ctx: CaptureQueriesContext) -> bool:return any("datawarehouse" in query["sql"].lower() for query in ctx.captured_queries)@@ -1213,6 +1250,31 @@ class TestDatabase(BaseTest, QueryMatchingTest):assert self._ran_source_fetch_queries(ctx)+ def test_cached_sources_recompute_warehouse_access_control_flag(self):+ credential = DataWarehouseCredential.objects.create(access_key="blah", access_secret="blah", team=self.team)+ DataWarehouseTable.objects.create(+ name="acl_table", team=self.team, columns={"id": "String"}, credential=credential, url_pattern=""+ )++ # Evaluated on the fetch, then re-evaluated once per request (cold and warm alike).+ acl_flag_values = iter([False, False, True])+ with (+ patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda key, *args, **kwargs: (+ next(acl_flag_values) if key == "hogql-warehouse-access-control" else False+ ),+ ),+ patch.object(Database, "_is_warehouse_table_denied", return_value=True),+ ):+ unenforced = Database.create_for(team=self.team, user=self.user, use_cached_sources=True)+ # Warm cache hit: the enforcement flag must be re-evaluated per request, never+ # served from the cached bundle, so this build sees the flag's new True.+ enforced = Database.create_for(team=self.team, user=self.user, use_cached_sources=True)++ assert unenforced.has_table("acl_table")+ assert not enforced.has_table("acl_table")+def _configure_revenue_events(self) -> None:config = self.team.revenue_analytics_configconfig.events = [REVENUE_ANALYTICS_CONFIG_SAMPLE_EVENT]@@ -4553,6 +4615,105 @@ class TestDatabase(BaseTest, QueryMatchingTest):assert ("system.activity_logs" in database.get_system_table_names()) is expected_visible+class TestCachedTeamFlag(TestCase):+ def setUp(self):+ _TEAM_FLAG_CACHE.clear()++ def tearDown(self):+ _TEAM_FLAG_CACHE.clear()++ @patch("posthog.models.instance_setting.get_instance_setting", return_value=30)+ def test_evaluates_once_within_ttl_and_isolates_teams(self, _get_setting):+ team_a = cast(Team, SimpleNamespace(uuid="team-a-uuid"))+ team_b = cast(Team, SimpleNamespace(uuid="team-b-uuid"))+ evaluate = Mock(side_effect=[True, False])++ assert _cached_team_flag("managed-viewsets", team_a, evaluate) is True+ assert _cached_team_flag("managed-viewsets", team_a, evaluate) is True+ assert evaluate.call_count == 1++ # A different team must not see team A's cached decision.+ assert _cached_team_flag("managed-viewsets", team_b, evaluate) is False+ assert evaluate.call_count == 2++ @patch("posthog.models.instance_setting.get_instance_setting", return_value=0)+ def test_zero_ttl_disables_caching(self, _get_setting):+ team = cast(Team, SimpleNamespace(uuid="team-uuid"))+ evaluate = Mock(return_value=True)++ _cached_team_flag("managed-viewsets", team, evaluate)+ _cached_team_flag("managed-viewsets", team, evaluate)+ assert evaluate.call_count == 2++ @patch("posthog.models.instance_setting.get_instance_setting", return_value=30)+ def test_flags_outside_the_allowlist_are_never_cached(self, _get_setting):+ team = cast(Team, SimpleNamespace(uuid="team-uuid"))+ evaluate = Mock(return_value=True)++ _cached_team_flag("hogql-warehouse-access-control", team, evaluate)+ _cached_team_flag("hogql-warehouse-access-control", team, evaluate)+ assert evaluate.call_count == 2+ assert _TEAM_FLAG_CACHE == {}++ @patch("posthog.models.instance_setting.get_instance_setting", return_value="")+ def test_unparseable_ttl_disables_caching_instead_of_raising(self, _get_setting):+ team = cast(Team, SimpleNamespace(uuid="team-uuid"))++ assert _cached_team_flag("managed-viewsets", team, Mock(return_value=True)) is True++ @patch("posthog.models.instance_setting.get_instance_setting", return_value=30)+ def test_cap_sweeps_expired_entries_and_keeps_fresh_ones(self, _get_setting):+ team = cast(Team, SimpleNamespace(uuid="team-uuid"))+ now = time.monotonic()+ _TEAM_FLAG_CACHE[("expired-team-uuid", "managed-viewsets")] = (now - 100, True)+ _TEAM_FLAG_CACHE[("fresh-team-uuid", "managed-viewsets")] = (now, True)++ with patch("posthog.hogql.database.database._TEAM_FLAG_CACHE_MAX_ENTRIES", 2):+ _cached_team_flag("managed-viewsets", team, Mock(return_value=True))++ assert ("expired-team-uuid", "managed-viewsets") not in _TEAM_FLAG_CACHE+ assert ("fresh-team-uuid", "managed-viewsets") in _TEAM_FLAG_CACHE+ assert (str(team.uuid), "managed-viewsets") in _TEAM_FLAG_CACHE++ @patch("posthog.models.instance_setting.get_instance_setting", return_value=30)+ def test_lowering_the_ttl_applies_to_existing_entries(self, _get_setting):+ team = cast(Team, SimpleNamespace(uuid="team-uuid"))+ # Evaluated 61s ago: fresh under the mocked 30s TTL? No - so it must re-evaluate, even+ # though a 3600s TTL was in force when the entry was written.+ _TEAM_FLAG_CACHE[(str(team.uuid), "managed-viewsets")] = (time.monotonic() - 61, True)+ evaluate = Mock(return_value=False)++ assert _cached_team_flag("managed-viewsets", team, evaluate) is False+ assert evaluate.call_count == 1++ @patch("posthog.models.instance_setting.get_instance_setting", return_value=30)+ def test_concurrent_inserts_during_cap_sweep_do_not_raise(self, _get_setting):+ now = time.monotonic()+ for index in range(64):+ _TEAM_FLAG_CACHE[(f"expired-{index}", "managed-viewsets")] = (now - 100, True)++ barrier = threading.Barrier(4)+ errors: list[Exception] = []++ def hammer(worker: int) -> None:+ try:+ barrier.wait()+ for iteration in range(200):+ team = cast(Team, SimpleNamespace(uuid=f"team-{worker}-{iteration}"))+ assert _cached_team_flag("managed-viewsets", team, Mock(return_value=True)) is True+ except Exception as e:+ errors.append(e)++ with patch("posthog.hogql.database.database._TEAM_FLAG_CACHE_MAX_ENTRIES", 32):+ threads = [threading.Thread(target=hammer, args=(worker,)) for worker in range(4)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ assert errors == []++class TestSourcesCacheConcurrency(TestCase):def setUp(self):clear_sources_cache()diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.pyindex fd39612a52a2..23a075f461a6 100644--- a/posthog/settings/dynamic_settings.py+++ b/posthog/settings/dynamic_settings.py@@ -26,6 +26,16 @@ CONSTANCE_CONFIG = {"and series threads. Disable to fall back to building a database per call.",bool,),+ "HOGQL_TEAM_FLAG_CACHE_TTL_SECONDS": (+ # Off in tests: test classes share one team while patching flag evaluation differently per+ # test, so a cached decision from one test would leak into the next.+ get_from_env("HOGQL_TEAM_FLAG_CACHE_TTL_SECONDS", 0 if TEST else 30, type_cast=int),+ "How long each HogQL database build reuses a team's feature-flag decisions (managed viewsets, "+ "data quality checks) before re-evaluating. This lag adds to the flag SDK's own definition "+ "refresh cadence, and changes to this setting reach each worker within about a minute. "+ "0 re-evaluates on every build.",+ int,+ ),"HOGQL_DEFERRED_REVENUE_VIEWS_ENABLED": (get_from_env("HOGQL_DEFERRED_REVENUE_VIEWS_ENABLED", True, type_cast=str_to_bool),"Whether HogQL database builds construct revenue-analytics views lazily, on the first query "@@ -380,6 +390,7 @@ SETTINGS_ALLOWING_API_OVERRIDE = ("GROWTH_RESCORE_WEBHOOK_SECRET","HOGQL_DEFERRED_REVENUE_VIEWS_ENABLED","HOGQL_SHARED_INSIGHT_DATABASE_ENABLED",+ "HOGQL_TEAM_FLAG_CACHE_TTL_SECONDS","RECORDINGS_PERFORMANCE_EVENTS_TTL_WEEKS","AUTO_START_ASYNC_MIGRATIONS","AGGREGATE_BY_DISTINCT_IDS_TEAMS",diff --git a/products/data_warehouse/backend/tests/api/test_view_link.py b/products/data_warehouse/backend/tests/api/test_view_link.pyindex aea73ab70f6d..3d4bead85e6f 100644--- a/products/data_warehouse/backend/tests/api/test_view_link.py+++ b/products/data_warehouse/backend/tests/api/test_view_link.py@@ -325,8 +325,8 @@ class TestViewLinkQuery(APIBaseTest):# Test that listing joins uses efficient queryingwith self.assertNumQueries(- FuzzyInt(18, 19)- ): # depends when team revenue analytisc config cache is hit in a test+ FuzzyInt(19, 21)+ ): # depends when the team revenue analytics config cache and instance-setting caches are hit in a testresponse = self.client.get(f"/api/environments/{self.team.id}/warehouse_view_links/")self.assertEqual(response.status_code, 200)