: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): cache database sources for editor-assist queries (#90911)
George Munyoro4737d328f19f
diff --git a/posthog/api/services/query.py b/posthog/api/services/query.pyindex a4b5ba3a23e5..1c2ebe02fc48 100644--- a/posthog/api/services/query.py+++ b/posthog/api/services/query.py@@ -306,6 +306,8 @@ def process_query_model(user=user,error_factory=ValidationError,modifiers=create_default_modifiers_for_team(team),+ # Editor-assist only: query execution never reads cached sources.+ use_cached_sources=True,)return get_hogql_autocomplete(query=query, team=team, database_arg=database, user=user)diff --git a/posthog/hogql/context.py b/posthog/hogql/context.pyindex 6346effd37e4..4df18f7359e3 100644--- a/posthog/hogql/context.py+++ b/posthog/hogql/context.py@@ -65,6 +65,10 @@ class HogQLContext:# Every call site that sets this MUST include an inline comment explaining why.bypass_warehouse_access_control: bool = False+ # Lets the lazy database build reuse recently fetched per-team sources (TTL-bounded staleness).+ # Set ONLY by editor-assist paths (autocomplete, metadata); query execution must build fresh.+ use_cached_sources: bool = False+# Virtual database we're querying, will be populated from team_id if not presentdatabase: Optional["Database"] = None# Metadata discovered for a direct Postgres connection, if one is selecteddiff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex be5f5bdcd2f6..b23d35e4cfe5 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -151,6 +151,12 @@ from posthog.hogql.database.schema.web_stats_frustration_preaggregated import Wefrom posthog.hogql.database.schema.web_stats_paths_preaggregated import WebStatsPathsPreaggregatedTablefrom posthog.hogql.database.schema.web_stats_preaggregated import WebStatsPreaggregatedTablefrom posthog.hogql.database.schema.web_vitals_paths_preaggregated import WebVitalsPathsPreaggregatedTable+from posthog.hogql.database.sources_cache import (+ SOURCES_CACHE_EVENTS,+ SourcesCacheKey,+ get_or_fetch_sources,+ modifiers_fingerprint,+)from posthog.hogql.database.utils import get_join_field_chain, qualify_join_key_exprfrom posthog.hogql.database.warehouse_join_resolvers import data_warehouse_resolver_paramsfrom posthog.hogql.editor_assist_metrics import HOGQL_DATABASE_BUILD_DURATION_SECONDS, HOGQL_DATABASE_BUILD_TOTAL@@ -252,6 +258,41 @@ class HogQLDatabaseSources:virtual_source: Optional[ExternalDataSource] = Nonevirtual_schemas: list[ExternalDataSchema] = dataclasses.field(default_factory=list)+ def copy_for_request(+ self,+ team: Team,+ user: Optional[User | SyntheticUser | SharedLinkUser],+ *,+ user_access_control: Optional[UserAccessControl],+ denied_system_table_names: set[str],+ ) -> HogQLDatabaseSources:+ """A copy safe to hand out from the sources cache: the request's own team, user, and+ freshly computed access-control decision, a private modifiers copy, and fresh top-level+ containers so an in-place mutation downstream cannot leak into other requests. The+ contained ORM rows stay shared — the build reads them only. Revenue views are the+ exception: they are pre-built table objects the build installs directly and then mutates+ (saved-expression fields land in their `fields` dicts), so each request gets deep copies."""+ return dataclasses.replace(+ self,+ team=team,+ user=user,+ user_access_control=user_access_control,+ denied_system_table_names=denied_system_table_names,+ modifiers=self.modifiers.model_copy(deep=True),+ direct_connection_metadata=(+ dict(self.direct_connection_metadata) if self.direct_connection_metadata is not None else None+ ),+ group_types=list(self.group_types),+ saved_queries=list(self.saved_queries),+ endpoint_saved_queries=list(self.endpoint_saved_queries),+ revenue_views=[view.model_copy(deep=True) for view in self.revenue_views],+ warehouse_tables=list(self.warehouse_tables),+ data_warehouse_joins=list(self.data_warehouse_joins),+ data_warehouse_expressions=list(self.data_warehouse_expressions),+ event_modifier_saved_queries=dict(self.event_modifier_saved_queries),+ virtual_schemas=list(self.virtual_schemas),+ )+type DatabaseSchemaTable = (DatabaseSchemaPostHogTable@@ -1393,6 +1434,7 @@ class Database(BaseModel):connection_id: str | None = None,bypass_warehouse_access_control: bool = False,build_postgres_foreign_keys: bool = True,+ use_cached_sources: bool = False,trigger: str = "direct",allowed_system_tables: Collection[str] | None = None,) -> Database:@@ -1400,23 +1442,87 @@ class Database(BaseModel):timings = HogQLTimings()HOGQL_DATABASE_BUILD_TOTAL.labels(trigger=trigger).inc()- with HOGQL_DATABASE_BUILD_DURATION_SECONDS.labels(phase="fetch_sources").time():- sources = Database._fetch_sources(- team_id,++ def fetch_fresh() -> HogQLDatabaseSources:+ with HOGQL_DATABASE_BUILD_DURATION_SECONDS.labels(phase="fetch_sources").time():+ return Database._fetch_sources(+ team_id,+ team=team,+ user=user,+ user_access_control=user_access_control,+ modifiers=modifiers,+ timings=timings,+ connection_id=connection_id,+ bypass_warehouse_access_control=bypass_warehouse_access_control,+ allowed_system_tables=allowed_system_tables,+ )++ cache_key = None+ if use_cached_sources:+ cache_key = Database._sources_cache_key(team=team,user=user,user_access_control=user_access_control,modifiers=modifiers,- timings=timings,connection_id=connection_id,bypass_warehouse_access_control=bypass_warehouse_access_control,allowed_system_tables=allowed_system_tables,)+ if cache_key is None:+ SOURCES_CACHE_EVENTS.labels(result="bypass").inc()++ if cache_key is None:+ sources = fetch_fresh()+ else:+ cached_sources = get_or_fetch_sources(cache_key, fetch_fresh)+ # Entries are shared across users; the access-control decision is recomputed per+ # request so a permission change applies immediately, never after the TTL.+ fresh_access_control, fresh_denied = _compute_system_table_access_decision(cast("Team", team), user)+ sources = cached_sources.copy_for_request(+ cast("Team", team),+ user,+ user_access_control=fresh_access_control,+ denied_system_table_names=fresh_denied,+ )+with HOGQL_DATABASE_BUILD_DURATION_SECONDS.labels(phase="build_from_sources").time():return Database._build_from_sources(sources, timings=timings, build_postgres_foreign_keys=build_postgres_foreign_keys)+ @staticmethod+ def _sources_cache_key(+ *,+ team: Optional[Team],+ user: Optional[User | SyntheticUser | SharedLinkUser],+ user_access_control: Optional[UserAccessControl],+ modifiers: HogQLQueryModifiers | None,+ connection_id: str | None,+ bypass_warehouse_access_control: bool,+ allowed_system_tables: Collection[str] | None,+ ) -> SourcesCacheKey | None:+ """The cache key for this build, or None when the build must fetch fresh sources.++ The key is team-scoped: entries hold only team-level catalog rows, and the per-user+ access-control decision is recomputed on every handout. Only real users (or no user)+ hit the cache: SyntheticUser/SharedLinkUser carry request-specific access semantics.+ A preloaded user_access_control or an allowed_system_tables override is likewise+ per-request state, so those bypass too.+ """+ from posthog.models.user import User # noqa: PLC0415 — keeps the Django ORM off this module's import path++ if team is None or user_access_control is not None or allowed_system_tables:+ return None+ if user is not None and not isinstance(user, User):+ return None+ normalized_modifiers = create_default_modifiers_for_team(team, modifiers)+ return SourcesCacheKey(+ team_id=team.pk,+ connection_id=connection_id,+ modifiers_fingerprint=modifiers_fingerprint(normalized_modifiers),+ bypass_warehouse_access_control=bypass_warehouse_access_control,+ )+@staticmethoddef create_for_posthog_tables(team: Team, *, modifiers: HogQLQueryModifiers | None = None, timings: HogQLTimings | None = Nonediff --git a/posthog/hogql/database/sources_cache.py b/posthog/hogql/database/sources_cache.pynew file mode 100644index 000000000000..fdea4f931314--- /dev/null+++ b/posthog/hogql/database/sources_cache.py@@ -0,0 +1,149 @@+import time+import hashlib+import threading+from collections.abc import Callable+from typing import TYPE_CHECKING++from cachetools import TTLCache+from prometheus_client import Counter++from posthog.dataclasses import frozen++if TYPE_CHECKING:+ from posthog.schema import HogQLQueryModifiers++ from posthog.hogql.database.database import HogQLDatabaseSources++# Editor-assist queries (autocomplete, metadata) fire on every keystroke and each one pays the+# full Postgres + feature-flag cost of Database._fetch_sources. A short TTL bounds staleness:+# a just-created view appears in suggestions within this window, while query execution always+# builds fresh sources and is never affected.+SOURCES_CACHE_TTL_SECONDS = 60++# Entries hold a team's warehouse catalog (ORM rows), whose size varies by orders of magnitude+# across teams, so the cache is bounded by total row weight rather than entry count. Teams whose+# catalog exceeds the per-entry limit skip the cache instead of evicting everyone else.+SOURCES_CACHE_WEIGHT_BUDGET = 16_384+SOURCES_CACHE_MAX_ENTRY_WEIGHT = 4_096++SOURCES_CACHE_EVENTS = Counter(+ "hogql_database_sources_cache_events_total",+ "HogQL database sources-cache lookups: hit/miss/bypass are lookup outcomes; oversized counts "+ "fetches whose result was too large to store.",+ labelnames=["result"],+)++# Indirection so tests can advance the cache clock without waiting out the TTL.+_time_source: Callable[[], float] = time.monotonic+++def _cache_timer() -> float:+ return _time_source()+++@frozen+class SourcesCacheKey:+ team_id: int+ connection_id: str | None+ modifiers_fingerprint: str+ bypass_warehouse_access_control: bool+++def sources_weight(sources: "HogQLDatabaseSources") -> int:+ """Cache weight of a sources bundle: the number of ORM rows it retains."""+ return 1 + sum(+ (+ len(sources.group_types),+ len(sources.saved_queries),+ len(sources.endpoint_saved_queries),+ len(sources.revenue_views),+ len(sources.warehouse_tables),+ len(sources.data_warehouse_joins),+ len(sources.data_warehouse_expressions),+ len(sources.event_modifier_saved_queries),+ len(sources.virtual_schemas),+ )+ )+++_sources_cache: TTLCache["SourcesCacheKey", "HogQLDatabaseSources"] = TTLCache(+ maxsize=SOURCES_CACHE_WEIGHT_BUDGET,+ ttl=SOURCES_CACHE_TTL_SECONDS,+ timer=_cache_timer,+ getsizeof=sources_weight,+)+# cachetools caches are not thread-safe; the lock guards threaded WSGI/Celery workers.+_sources_cache_lock = threading.Lock()+++class _InflightFetch:+ """One in-progress fetch for a key. Waiters block on `done` and consume `result` directly,+ so a result that is never admitted to the cache (oversized) still reaches every waiter."""++ __slots__ = ("done", "result")++ def __init__(self) -> None:+ self.done = threading.Event()+ self.result: HogQLDatabaseSources | None = None+++# Per-key single-flight registry: concurrent misses for one key wait for a single fetch instead+# of each running the full Postgres fetch. An entry is retired atomically with the cache store,+# so a caller always observes either a cached value or an in-flight fetch, never neither.+_inflight_fetches: dict["SourcesCacheKey", _InflightFetch] = {}+++def modifiers_fingerprint(modifiers: "HogQLQueryModifiers") -> str:+ return hashlib.sha256(modifiers.model_dump_json().encode()).hexdigest()+++def get_or_fetch_sources(key: SourcesCacheKey, fetch: Callable[[], "HogQLDatabaseSources"]) -> "HogQLDatabaseSources":+ while True:+ with _sources_cache_lock:+ cached = _sources_cache.get(key)+ if cached is not None:+ SOURCES_CACHE_EVENTS.labels(result="hit").inc()+ return cached+ flight = _inflight_fetches.get(key)+ is_owner = flight is None+ if is_owner:+ flight = _InflightFetch()+ _inflight_fetches[key] = flight+ assert flight is not None++ if not is_owner:+ flight.done.wait()+ if flight.result is not None:+ SOURCES_CACHE_EVENTS.labels(result="hit").inc()+ return flight.result+ # The owner's fetch raised; loop so one waiter becomes the new owner and retries.+ continue++ SOURCES_CACHE_EVENTS.labels(result="miss").inc()+ oversized = False+ try:+ # The fetch runs outside the global cache lock so one slow team cannot stall every+ # other team's lookups. Cache admission happens before the flight is retired in the+ # finally block, so a new caller always observes either a cached value or an+ # in-flight fetch, never neither.+ sources = fetch()+ oversized = sources_weight(sources) > SOURCES_CACHE_MAX_ENTRY_WEIGHT+ flight.result = sources+ if not oversized:+ with _sources_cache_lock:+ _sources_cache[key] = sources+ finally:+ # Waiters must always wake and the flight must always leave the registry, whatever+ # raised above — a flight that stays registered would hang this key's callers forever.+ with _sources_cache_lock:+ _inflight_fetches.pop(key, None)+ flight.done.set()+ if oversized:+ SOURCES_CACHE_EVENTS.labels(result="oversized").inc()+ return sources+++def clear_sources_cache() -> None:+ with _sources_cache_lock:+ _sources_cache.clear()+ _inflight_fetches.clear()diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.pyindex 112d9dda06e6..e105555c9255 100644--- a/posthog/hogql/database/test/test_database.py+++ b/posthog/hogql/database/test/test_database.py@@ -1,8 +1,12 @@import ioimport json+import timeimport pickle+import threadingimport dataclassesfrom collections.abc import Collection+from contextlib import suppress+from types import SimpleNamespacefrom typing import Any, castimport pytest@@ -11,7 +15,9 @@ from unittest import TestCasefrom unittest.mock import patchfrom django.conf import settings+from django.db import connectionfrom django.test import override_settings+from django.test.utils import CaptureQueriesContextfrom parameterized import parameterizedfrom pydantic import BaseModel@@ -59,6 +65,13 @@ from posthog.hogql.database.models import (from posthog.hogql.database.postgres_table import PostgresTablefrom posthog.hogql.database.s3_table import DataWarehouseTable as HogQLDataWarehouseTablefrom posthog.hogql.database.schema.sessions_v2 import RawSessionsTableV2+from posthog.hogql.database.sources_cache import (+ SOURCES_CACHE_MAX_ENTRY_WEIGHT,+ SOURCES_CACHE_TTL_SECONDS,+ SourcesCacheKey,+ clear_sources_cache,+ get_or_fetch_sources,+)from posthog.hogql.errors import ExposedHogQLError, QueryError, TableAccessDeniedErrorfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_expr, parse_select@@ -81,6 +94,7 @@ from products.access_control.backend.facade.user_access_control import UserAccesfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_tools.backend.models.expression import DataWarehouseExpressionfrom products.data_tools.backend.models.join import DataWarehouseJoin+from products.revenue_analytics.backend.views import RevenueAnalyticsChargeViewfrom products.warehouse_sources.backend.facade.models import (DataWarehouseCredential,DataWarehouseTable,@@ -1114,6 +1128,116 @@ class TestDatabase(BaseTest, QueryMatchingTest):assert "some_field" in db.get_table("events").fieldsassert "timestamp" in db.get_table("whatever0").fields+ @staticmethod+ def _ran_source_fetch_queries(ctx: CaptureQueriesContext) -> bool:+ return any("datawarehouse" in query["sql"].lower() for query in ctx.captured_queries)++ def test_cached_sources_warm_build_runs_no_queries(self):+ credential = DataWarehouseCredential.objects.create(access_key="blah", access_secret="blah", team=self.team)+ DataWarehouseTable.objects.create(+ name="cached_table", team=self.team, columns={"id": "String"}, credential=credential, url_pattern=""+ )+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="cached_view",+ query={"query": "SELECT id FROM cached_table"},+ columns={"id": "String"},+ status=DataWarehouseSavedQuery.Status.COMPLETED,+ )++ cold = Database.create_for(team=self.team, user=self.user, use_cached_sources=True)+ with CaptureQueriesContext(connection) as ctx:+ warm = Database.create_for(team=self.team, user=self.user, use_cached_sources=True)++ # The warm build only recomputes the per-request access-control decision; it never+ # refetches the catalog.+ assert not self._ran_source_fetch_queries(ctx)+ cold_serialized = cold.serialize(HogQLContext(team_id=self.team.pk, database=cold))+ warm_serialized = warm.serialize(HogQLContext(team_id=self.team.pk, database=warm))+ assert warm_serialized.keys() == cold_serialized.keys()+ assert warm.has_table("cached_table")+ assert warm.has_table("cached_view")++ def test_cached_sources_shared_across_users_with_fresh_access_control(self):+ other_user = self._create_user("[email protected]")+ Database.create_for(team=self.team, user=self.user, use_cached_sources=True)++ with CaptureQueriesContext(connection) as ctx:+ Database.create_for(team=self.team, user=other_user, use_cached_sources=True)++ assert not self._ran_source_fetch_queries(ctx)+ # The catalog is shared, but the second user's access-control decision is computed+ # fresh rather than reused from the user who warmed the cache.+ assert any("organizationmembership" in query["sql"].lower() for query in ctx.captured_queries)++ def test_sources_not_cached_by_default(self):+ Database.create_for(team=self.team, user=self.user, use_cached_sources=True)++ with CaptureQueriesContext(connection) as ctx:+ Database.create_for(team=self.team, user=self.user)++ assert self._ran_source_fetch_queries(ctx)++ def test_cached_sources_bypassed_for_synthetic_users(self):+ Database.create_for(team=self.team, user=SyntheticUser(self.team, "synthetic-1"), use_cached_sources=True)++ with CaptureQueriesContext(connection) as ctx:+ Database.create_for(team=self.team, user=SyntheticUser(self.team, "synthetic-2"), use_cached_sources=True)++ assert self._ran_source_fetch_queries(ctx)++ def test_cached_revenue_views_do_not_leak_expression_fields_between_users(self):+ other_user = self._create_user("[email protected]")+ with team_scope(self.team.id, canonical=True):+ DataWarehouseExpression.objects.create(+ team=self.team, table_name="stub_revenue_view", field_name="secret_expr", expression="1 + 1"+ )+ stub_view = RevenueAnalyticsChargeView(+ id="stub-view",+ name="stub_revenue_view",+ query="SELECT 'x' AS id",+ fields={"id": StringDatabaseField(name="id")},+ prefix="stub",+ )++ with (+ patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda key, *args, **kwargs: key == "hogql-warehouse-access-control",+ ),+ patch(+ "products.revenue_analytics.backend.views.orchestrator.build_all_revenue_analytics_views",+ return_value=[stub_view],+ ),+ patch.object(Database, "_is_warehouse_expression_denied", side_effect=[False, True]),+ ):+ allowed = Database.create_for(team=self.team, user=self.user, use_cached_sources=True)+ denied = Database.create_for(team=self.team, user=other_user, use_cached_sources=True)++ assert allowed.get_table("stub_revenue_view") is not denied.get_table("stub_revenue_view")+ assert "secret_expr" in allowed.get_table("stub_revenue_view").fields+ assert "secret_expr" not in denied.get_table("stub_revenue_view").fields++ def test_cached_sources_expire_and_pick_up_new_views(self):+ Database.create_for(team=self.team, user=self.user, use_cached_sources=True)+ DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="view_created_after_warm",+ query={"query": "SELECT event FROM events"},+ columns={"event": "String"},+ status=DataWarehouseSavedQuery.Status.COMPLETED,+ )++ within_ttl = Database.create_for(team=self.team, user=self.user, use_cached_sources=True)+ assert not within_ttl.has_table("view_created_after_warm")++ with patch(+ "posthog.hogql.database.sources_cache._time_source",+ new=lambda: time.monotonic() + SOURCES_CACHE_TTL_SECONDS + 1,+ ):+ after_ttl = Database.create_for(team=self.team, user=self.user, use_cached_sources=True)+ assert after_ttl.has_table("view_created_after_warm")+def test_materialized_backing_filter_keeps_source_tables_but_hides_backing_tables(self):credential = DataWarehouseCredential.objects.create(team=self.team, access_key="_accesskey", access_secret="_secret"@@ -4259,6 +4383,103 @@ class TestDatabase(BaseTest, QueryMatchingTest):assert ("system.activity_logs" in database.get_system_table_names()) is expected_visible+class TestSourcesCacheConcurrency(TestCase):+ def setUp(self):+ clear_sources_cache()++ def tearDown(self):+ clear_sources_cache()++ @staticmethod+ def _stub_sources(row_count: int = 0) -> Any:+ return SimpleNamespace(+ group_types=[],+ saved_queries=[],+ endpoint_saved_queries=[],+ revenue_views=[],+ warehouse_tables=[object()] * row_count,+ data_warehouse_joins=[],+ data_warehouse_expressions=[],+ event_modifier_saved_queries={},+ virtual_schemas=[],+ )++ def test_concurrent_misses_for_one_key_fetch_once(self):+ key = SourcesCacheKey(+ team_id=1, connection_id=None, modifiers_fingerprint="fp", bypass_warehouse_access_control=False+ )+ stub = self._stub_sources()+ fetch_count = 0+ fetch_entered = threading.Event()+ fetch_release = threading.Event()++ def fetch() -> Any:+ nonlocal fetch_count+ fetch_count += 1+ fetch_entered.set()+ assert fetch_release.wait(timeout=5)+ return stub++ results: list[Any] = []+ threads = [threading.Thread(target=lambda: results.append(get_or_fetch_sources(key, fetch))) for _ in range(2)]+ for thread in threads:+ thread.start()+ assert fetch_entered.wait(timeout=5)+ fetch_release.set()+ for thread in threads:+ thread.join(timeout=5)++ assert fetch_count == 1+ assert results == [stub, stub]++ def test_waiters_wake_and_retry_when_the_owner_fetch_raises(self):+ key = SourcesCacheKey(+ team_id=1, connection_id=None, modifiers_fingerprint="fp", bypass_warehouse_access_control=False+ )+ stub = self._stub_sources()+ owner_entered = threading.Event()+ owner_release = threading.Event()++ def failing_fetch() -> Any:+ owner_entered.set()+ assert owner_release.wait(timeout=5)+ raise RuntimeError("fetch failed")++ def owner() -> None:+ with suppress(RuntimeError):+ get_or_fetch_sources(key, failing_fetch)++ results: list[Any] = []+ owner_thread = threading.Thread(target=owner)+ waiter_thread = threading.Thread(target=lambda: results.append(get_or_fetch_sources(key, lambda: stub)))+ owner_thread.start()+ assert owner_entered.wait(timeout=5)+ waiter_thread.start()+ owner_release.set()+ owner_thread.join(timeout=5)+ waiter_thread.join(timeout=5)++ assert not waiter_thread.is_alive()+ assert results == [stub]++ def test_oversized_sources_are_returned_but_not_cached(self):+ key = SourcesCacheKey(+ team_id=1, connection_id=None, modifiers_fingerprint="fp", bypass_warehouse_access_control=False+ )+ fetch_count = 0++ def fetch() -> Any:+ nonlocal fetch_count+ fetch_count += 1+ return self._stub_sources(row_count=SOURCES_CACHE_MAX_ENTRY_WEIGHT + 1)++ first = get_or_fetch_sources(key, fetch)+ second = get_or_fetch_sources(key, fetch)++ assert fetch_count == 2+ assert first is not None and second is not None++class TestCreateForPosthogTables(BaseTest):def test_builds_without_postgres_and_applies_modifiers(self):modifiers = HogQLQueryModifiers(sessionTableVersion=SessionTableVersion.V2)diff --git a/posthog/hogql/direct_connection.py b/posthog/hogql/direct_connection.pyindex 1de4ab87c13f..03608f816587 100644--- a/posthog/hogql/direct_connection.py+++ b/posthog/hogql/direct_connection.py@@ -151,6 +151,7 @@ def resolve_database_for_connection(modifiers: HogQLQueryModifiers | None = None,timings: HogQLTimings | None = None,error_factory: Callable[[str], Exception],+ use_cached_sources: bool = False,) -> tuple[ExternalDataSource | None, Database]:source = get_direct_connection_source_none_or_raise(team, connection_id, user=user, error_factory=error_factory)database = Database.create_for(@@ -159,5 +160,6 @@ def resolve_database_for_connection(modifiers=modifiers,timings=timings,connection_id=str(source.id) if source else None,+ use_cached_sources=use_cached_sources,)return source, databasediff --git a/posthog/hogql/metadata.py b/posthog/hogql/metadata.pyindex a9c8a3a0113e..0d5d2a95633a 100644--- a/posthog/hogql/metadata.py+++ b/posthog/hogql/metadata.py@@ -81,6 +81,8 @@ def get_hogql_metadata(user=user,modifiers=query_modifiers,connection_id=str(source.id),+ # Editor-assist only: query execution never reads cached sources.+ use_cached_sources=True,)heuristic_warnings: list[HogQLNotice] = []@@ -89,10 +91,14 @@ def get_hogql_metadata(try:context = HogQLContext(team_id=team.pk,+ # The team object itself, so the lazy database build can key the sources cache.+ team=team,user=user,database=database,modifiers=query_modifiers,enable_select_queries=True,+ # Editor-assist only: query execution never reads cached sources.+ use_cached_sources=True,# A resolved direct-connection source prints with its engine dialect (below), so the# context must be marked direct — otherwise the ClickHouse printer's direct-table guard# fires and metadata/autocomplete reports a false "can only be queried through its direct@@ -119,6 +125,17 @@ def get_hogql_metadata(hogql_ast = parse_select(query.query)finder = find_placeholders(hogql_ast)if finder.has_filters:+ if database is None:+ # Built here (cached) and shared with the printer via the context, so the+ # filters replacement doesn't add an uncached build of its own.+ database = Database.create_for(+ team=team,+ user=user,+ modifiers=query_modifiers,+ use_cached_sources=True,+ trigger="metadata",+ )+ context.database = databasehogql_ast = replace_filters(hogql_ast, query.filters, team, database=database)if query.variables or finder.placeholder_fields or finder.placeholder_expressions:hogql_ast = replace_variables(diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex 3b6bdd9b125b..539fce0bbad9 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -192,6 +192,7 @@ def prepare_ast_for_printing(user=context.user,timings=context.timings,bypass_warehouse_access_control=context.bypass_warehouse_access_control,+ use_cached_sources=context.use_cached_sources,trigger="printer",)if context.direct_postgres_connection_metadata is None and context.database is not None:diff --git a/posthog/hogql/test/test_metadata.py b/posthog/hogql/test/test_metadata.pyindex 036779446b23..8438f81c06bf 100644--- a/posthog/hogql/test/test_metadata.py+++ b/posthog/hogql/test/test_metadata.py@@ -12,6 +12,8 @@ from parameterized import parameterizedfrom posthog.schema import (HogLanguage,+ HogQLAutocomplete,+ HogQLFilters,HogQLMetadata,HogQLMetadataResponse,HogQLQuery,@@ -24,6 +26,7 @@ from posthog.hogql.metadata import get_hogql_metadatafrom posthog.hogql.parser import parse_selectfrom posthog.hogql.taxonomy_validation import MAX_SUGGESTED_NAMES+from posthog.api.services.query import process_query_modelfrom posthog.models import EventDefinition, PropertyDefinition, Teamfrom products.cohorts.backend.models.cohort import Cohort@@ -89,6 +92,57 @@ class TestMetadata(ClickhouseTestMixin, APIBaseTest):team=self.team,)+ def test_metadata_reuses_sources_fetched_by_autocomplete(self):+ autocomplete = HogQLAutocomplete(+ kind="HogQLAutocomplete",+ query="select ",+ language=HogLanguage.HOG_QL,+ startPosition=7,+ endPosition=7,+ )+ process_query_model(self.team, autocomplete, user=self.user)++ with CaptureQueriesContext(connection) as ctx:+ response = get_hogql_metadata(+ query=HogQLMetadata(+ kind="HogQLMetadata",+ language=HogLanguage.HOG_QL,+ query="select event from events",+ response=None,+ ),+ team=self.team,+ user=self.user,+ )++ assert response.isValid+ assert not any("datawarehouse" in query["sql"].lower() for query in ctx.captured_queries)++ def test_filtered_metadata_reuses_sources_fetched_by_autocomplete(self):+ autocomplete = HogQLAutocomplete(+ kind="HogQLAutocomplete",+ query="select ",+ language=HogLanguage.HOG_QL,+ startPosition=7,+ endPosition=7,+ )+ process_query_model(self.team, autocomplete, user=self.user)++ with CaptureQueriesContext(connection) as ctx:+ response = get_hogql_metadata(+ query=HogQLMetadata(+ kind="HogQLMetadata",+ language=HogLanguage.HOG_QL,+ query="select event from events where {filters}",+ filters=HogQLFilters(),+ response=None,+ ),+ team=self.team,+ user=self.user,+ )++ assert response.isValid+ assert not any("datawarehouse" in query["sql"].lower() for query in ctx.captured_queries)+def test_metadata_valid_expr_select(self):metadata = self._expr("select 1")self.assertEqual(diff --git a/posthog/test/base.py b/posthog/test/base.pyindex 19565df6d6da..112f52089c6d 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -45,6 +45,7 @@ from posthog.hogql import ()from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.context import HogQLContext+from posthog.hogql.database.sources_cache import clear_sources_cachefrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.visitor import clone_expr@@ -713,6 +714,10 @@ class PostHogTestCase(SimpleTestCase):def setUp(self):get_instance_setting.cache_clear() # type: ignore[attr-defined]+ # The sources cache is keyed on team/user ids, which repeat across tests while the+ # rows behind them roll back, so a stale entry would leak one test's schema into the next.+ clear_sources_cache()+# Warm the new-events-schema gate settings so their cold reads don't land inside# assertNumQueries blocks: production workers serve requests with this cache warm# (60s TTL), and counting the cold reads would make every exact-count test depend