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.

perf(hogql): build revenue-analytics views on first access (#97167)

George Munyoro88b76f090810
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 0430d5f75aec..4145681f07a7 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -202,6 +202,7 @@ if TYPE_CHECKING:
from products.data_tools.backend.models.expression import DataWarehouseExpression
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.revenue_analytics.backend.views import RevenueAnalyticsBaseView
+ from products.revenue_analytics.backend.views.core import SourceHandle
from products.warehouse_sources.backend.facade.models import (
DataWarehouseCredential,
DataWarehouseTable,
@@ -250,6 +251,10 @@ class HogQLDatabaseSources:
saved_queries: list[DataWarehouseSavedQuery]
endpoint_saved_queries: list[DataWarehouseSavedQuery]
revenue_views: list[RevenueAnalyticsBaseView]
+ # Deferred mode: the inputs for revenue views instead of the views. Building a view runs the
+ # full HogQL printer, so the build waits until a query resolves a revenue table. Fetching the
+ # handles warms team.revenue_analytics_config, so the deferred build itself does no I/O.
+ revenue_source_handles: list[SourceHandle]
warehouse_tables: list[DataWarehouseTable] # filtered to what build needs, schemas preloaded
data_warehouse_joins: list[DataWarehouseJoin]
data_warehouse_expressions: list[DataWarehouseExpression]
@@ -288,6 +293,8 @@ class HogQLDatabaseSources:
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],
+ # Handles are frozen; the deferred build constructs fresh view objects per database.
+ revenue_source_handles=list(self.revenue_source_handles),
warehouse_tables=list(self.warehouse_tables),
data_warehouse_joins=list(self.data_warehouse_joins),
data_warehouse_expressions=list(self.data_warehouse_expressions),
@@ -312,6 +319,11 @@ def is_reserved_system_name(name: str) -> bool:
return name == "system" or name.startswith("system.")
+def _revenue_trigger_prefixes(handles: list[SourceHandle]) -> set[str]:
+ """Lowercased first segments of the dotted names the handles' views will get."""
+ return {"revenue_analytics" if handle.type == "events" else handle.type.lower() for handle in handles}
+
+
# READ BEFORE EDITING:
# --------------------
# Do NOT add any new table to this, add them to the `posthog` table node.
@@ -706,6 +718,15 @@ class Database(BaseModel):
# Lowercased, because Snowflake nodes resolve case-insensitively and a query may name a table with
# casing that differs from the canonical catalog name.
_foreign_key_trigger_names: Optional[set[str]] = None
+ # Deferred revenue-analytics views. Building each view runs the full HogQL printer, yet most
+ # queries never touch one, so the handles are stashed here and the views are built the first
+ # time a name under a revenue prefix fails to resolve (see has_table / get_table).
+ _deferred_revenue_handles: list[Any] = []
+ _revenue_views_built: bool = True
+ _revenue_views_building_thread: Optional[int] = None
+ _revenue_views_build_lock: Any = None
+ # Lowercased first segments of the deferred views' dotted names (e.g. revenue_analytics, stripe).
+ _revenue_view_trigger_names: Optional[set[str]] = None
# ids of the ExpressionField objects saved expressions added at build time. The deferred build
# lets a foreign key replace only these (see _ensure_foreign_keys_built), never the id/timestamp
# mappings event modifiers write, which the eager path preserved.
@@ -740,6 +761,11 @@ class Database(BaseModel):
self._foreign_keys_building_thread = None
self._foreign_keys_build_lock = threading.Lock()
self._foreign_key_trigger_names = None
+ self._deferred_revenue_handles = []
+ self._revenue_views_built = True
+ self._revenue_views_building_thread = None
+ self._revenue_views_build_lock = threading.Lock()
+ self._revenue_view_trigger_names = None
self._deferred_overridable_expression_field_ids = set()
self._serialization_errors: dict[str, str] = {} # table_key -> error_message
self.user_access_control: Optional[UserAccessControl] = None
@@ -757,7 +783,13 @@ class Database(BaseModel):
def has_table(self, table_name: str | list[str]) -> bool:
if isinstance(table_name, str):
table_name = table_name.split(".")
- return self.tables.has_child(table_name)
+ if self.tables.has_child(table_name):
+ return True
+ # A miss under a revenue prefix may just mean the deferred views are not built yet.
+ if self._should_build_revenue_views_for(table_name):
+ self._ensure_revenue_views_built()
+ return self.tables.has_child(table_name)
+ return False
def is_table_access_denied(self, table_name: str | list[str]) -> bool:
"""True if access control denied this table when the HogQL database was built.
@@ -780,6 +812,11 @@ class Database(BaseModel):
try:
table = cast(Table, self.get_table_node(table_name).get())
except ResolutionError as e:
+ # Unlike deferred foreign keys (whose tables are in the tree from the start), deferred
+ # revenue views are absent until built, so the trigger has to fire on the failed lookup.
+ if self._should_build_revenue_views_for(table_name):
+ self._ensure_revenue_views_built()
+ return self.get_table(table_name)
if isinstance(table_name, list):
table_name = ".".join(table_name)
if self.is_table_access_denied(table_name):
@@ -804,6 +841,55 @@ class Database(BaseModel):
# foreign-key fields the eager path had.
return name.lower() in trigger_names
+ def _should_build_revenue_views_for(self, table_name: str | list[str]) -> bool:
+ if self._revenue_views_built:
+ return False
+ trigger_names = self._revenue_view_trigger_names
+ if not trigger_names:
+ return False
+ # A chain element may itself contain the dotted name (the resolver passes them through
+ # unsplit), so normalize to one dotted string before taking the first segment.
+ name = ".".join(str(part) for part in table_name) if isinstance(table_name, list) else table_name
+ # First-segment match: every deferred view name starts with its handle's prefix segment.
+ # Over-triggering only costs the build we deferred.
+ return name.split(".")[0].lower() in trigger_names
+
+ def _ensure_revenue_views_built(self) -> None:
+ """Build the deferred revenue-analytics views and graft them into the tree, at most once.
+
+ Building a view resolves no tables, but the guard mirrors _ensure_foreign_keys_built: a
+ failure of the pass itself keeps the work pending for retry, and concurrent query threads
+ block on the lock until the builder finishes rather than observing a half-grafted tree.
+ A view whose own builder raises is skipped and reported, as on the eager path. Runs when
+ enumeration surfaces list tables and whenever a name under a revenue prefix fails to
+ resolve, including build-time consumers such as warehouse joins and saved expressions,
+ which reach the views through has_table / get_table.
+ """
+ if self._revenue_views_built or self._revenue_views_building_thread == threading.get_ident():
+ return
+ with self._revenue_views_build_lock:
+ if self._revenue_views_built:
+ return # type: ignore[unreachable]
+ self._revenue_views_building_thread = threading.get_ident()
+ try:
+ # Function-local + product import: keeps revenue analytics off the django.setup() path.
+ from products.revenue_analytics.backend.views.orchestrator import ( # noqa: PLC0415
+ build_revenue_views_for_handles,
+ )
+
+ with tracer.start_as_current_span("revenue_analytics_views_deferred"):
+ views_node: TableNode = TableNode()
+ for view in build_revenue_views_for_handles(self._deferred_revenue_handles):
+ try:
+ views_node.add_child(TableNode.create_nested_for_chain(view.name.split("."), view))
+ except Exception as e:
+ capture_exception(e)
+ self._add_views(views_node)
+ finally:
+ self._revenue_views_building_thread = None
+ self._revenue_views_built = True
+ self._deferred_revenue_handles = []
+
def _ensure_foreign_keys_built(self) -> None:
"""Wire the deferred Postgres foreign-key lazy joins, at most once.
@@ -862,6 +948,9 @@ class Database(BaseModel):
import difflib
try:
+ # A typo can miss the deferred-revenue trigger (its first segment matches no prefix),
+ # so build the views here to keep them suggestable, as they were on the eager path.
+ self._ensure_revenue_views_built()
candidates = set(self.get_posthog_table_names())
candidates.update(self._warehouse_table_names)
candidates.update(self._warehouse_self_managed_table_names)
@@ -886,6 +975,8 @@ class Database(BaseModel):
return difflib.get_close_matches(name, sorted(candidates), n=limit, cutoff=0.7)
def get_all_table_names(self) -> list[str]:
+ # Enumeration surfaces (autocomplete, AI table listings) must see the full catalog.
+ self._ensure_revenue_views_built()
warehouse_table_names: list[str] = []
for table_name in self._warehouse_table_names:
try:
@@ -937,6 +1028,7 @@ class Database(BaseModel):
return self._warehouse_table_names + self._warehouse_self_managed_table_names
def get_view_names(self) -> list[str]:
+ self._ensure_revenue_views_built()
return self._view_table_names
def _add_warehouse_tables(self, node: TableNode):
@@ -1111,6 +1203,11 @@ class Database(BaseModel):
include_hidden_posthog_tables: bool = False,
include_fields: bool = True,
) -> dict[str, DatabaseSchemaTable]:
+ # The schema browser and editor list every table, so deferred revenue views must exist
+ # here. A partial request (the sidebar hydrating one table's fields) skips the build
+ # unless a requested name falls under a revenue prefix.
+ if include_only is None or any(self._should_build_revenue_views_for(name) for name in include_only):
+ self._ensure_revenue_views_built()
from posthog.schema import ( # noqa: PLC0415
DatabaseSchemaDataWarehouseTable,
DatabaseSchemaEndpointTable,
@@ -1178,7 +1275,9 @@ class Database(BaseModel):
# Data Warehouse Tables and Views - Fetch all related data in one go
warehouse_table_names = self.get_warehouse_table_names()
- views = [] if self._is_direct_query() else self.get_view_names()
+ # Raw name cache, not get_view_names(): whether deferred revenue views belong in this
+ # serialization was decided once at the top, and get_view_names would force the build.
+ views = [] if self._is_direct_query() else list(self._view_table_names)
direct_query_source_ids = [self._connection_id] if self._is_direct_query() and self._connection_id else None
warehouse_tables_query = (
@@ -1459,20 +1558,6 @@ class Database(BaseModel):
HOGQL_DATABASE_BUILD_TOTAL.labels(trigger=trigger).inc()
- 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(
@@ -1487,6 +1572,24 @@ class Database(BaseModel):
if cache_key is None:
SOURCES_CACHE_EVENTS.labels(result="bypass").inc()
+ 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,
+ # Cached sources store built views: the cache serves editor assist, which
+ # enumerates every table on each request, so deferral would rebuild the views
+ # per request instead of amortizing them across the TTL.
+ defer_revenue_views=cache_key is None,
+ )
+
if cache_key is None:
sources = fetch_fresh()
else:
@@ -1575,6 +1678,7 @@ class Database(BaseModel):
saved_queries=[],
endpoint_saved_queries=[],
revenue_views=[],
+ revenue_source_handles=[],
warehouse_tables=[],
data_warehouse_joins=[],
data_warehouse_expressions=[],
@@ -1594,6 +1698,7 @@ class Database(BaseModel):
connection_id: str | None = None,
bypass_warehouse_access_control: bool = False,
allowed_system_tables: Collection[str] | None = None,
+ defer_revenue_views: bool = True,
) -> HogQLDatabaseSources:
"""Run every Postgres query / feature-flag check / external request needed to build the
database, returning a bundle that Database._build_from_sources turns into tables with no I/O."""
@@ -1772,14 +1877,26 @@ class Database(BaseModel):
with timings.measure("revenue_analytics_views", emit_span=True):
revenue_views: list[RevenueAnalyticsBaseView] = []
+ revenue_source_handles: list[SourceHandle] = []
if not is_direct_query:
try:
if not is_managed_viewset_enabled:
+ # Building a view runs the full HogQL printer per view kind per source, on
+ # every build, whether or not the query touches a revenue table. Fetch only
+ # the handles here and let the first revenue-table access build the views
+ # (see _ensure_revenue_views_built).
+ # Function-local: keeps the Django model import off the django.setup() path.
+ from posthog.models.instance_setting import get_instance_setting # noqa: PLC0415
+
from products.revenue_analytics.backend.views.orchestrator import ( # noqa: PLC0415
build_all_revenue_analytics_views,
+ list_revenue_source_handles,
)
- revenue_views = list(build_all_revenue_analytics_views(team, timings))
+ if defer_revenue_views and get_instance_setting("HOGQL_DEFERRED_REVENUE_VIEWS_ENABLED"):
+ revenue_source_handles = list_revenue_source_handles(team, timings)
+ else:
+ revenue_views = list(build_all_revenue_analytics_views(team, timings))
except Exception as e:
capture_exception(e)
@@ -1919,6 +2036,7 @@ class Database(BaseModel):
saved_queries=saved_queries,
endpoint_saved_queries=endpoint_saved_queries,
revenue_views=revenue_views,
+ revenue_source_handles=revenue_source_handles,
warehouse_tables=warehouse_tables,
data_warehouse_joins=data_warehouse_joins,
data_warehouse_expressions=data_warehouse_expressions,
@@ -2141,13 +2259,30 @@ class Database(BaseModel):
capture_exception(e)
with timings.measure("revenue_analytics_views", emit_span=True):
+ revenue_views_to_add = list(sources.revenue_views)
+ deferred_revenue_handles = list(sources.revenue_source_handles) if not database._is_direct_query() else []
+ if deferred_revenue_handles and modifiers.dataWarehouseEventsModifiers:
+ trigger_prefixes = _revenue_trigger_prefixes(deferred_revenue_handles)
+ if any(
+ wm.table_name.split(".")[0].lower() in trigger_prefixes
+ for wm in modifiers.dataWarehouseEventsModifiers
+ ):
+ # A modifier names a revenue view, so this query uses it: deferral saves
+ # nothing, and the define_mappings pass below must see the view or the
+ # configured id/timestamp/distinct_id mappings are silently dropped.
+ from products.revenue_analytics.backend.views.orchestrator import ( # noqa: PLC0415
+ build_revenue_views_for_handles,
+ )
+
+ revenue_views_to_add = build_revenue_views_for_handles(deferred_revenue_handles, timings)
+ deferred_revenue_handles = []
if not database._is_direct_query():
# Each view will have a name similar to `stripe.<prefix>.<table_name>`
# We want to create a nested table group where `stripe` is the parent,
# `<prefix>` is the child of `stripe`, and `<table_name>` is the child of `<prefix>`
# allowing you to access the table as `stripe[prefix][table_name]` in a dict fashion
# but still allowing the bare `stripe.prefix.table_name` string access
- for view in sources.revenue_views:
+ for view in revenue_views_to_add:
try:
views.add_child(TableNode.create_nested_for_chain(view.name.split("."), view))
except Exception as e:
@@ -2444,6 +2579,13 @@ class Database(BaseModel):
database._add_warehouse_self_managed_tables(self_managed_warehouse_tables)
database._add_views(views)
+ if deferred_revenue_handles:
+ # Armed before the joins and saved-expressions passes below: a join or expression that
+ # names a revenue view reaches it through has_table / get_table, which build on demand.
+ database._deferred_revenue_handles = deferred_revenue_handles
+ database._revenue_view_trigger_names = _revenue_trigger_prefixes(deferred_revenue_handles)
+ database._revenue_views_built = False
+
if build_postgres_foreign_keys:
# Stash the work now; _ensure_foreign_keys_built wires it on first warehouse-table access.
# Arming (below, after apply_schema_scope) is deliberately deferred so build-time
diff --git a/posthog/hogql/database/sources_cache.py b/posthog/hogql/database/sources_cache.py
index fdea4f931314..c4ecc9778fff 100644
--- a/posthog/hogql/database/sources_cache.py
+++ b/posthog/hogql/database/sources_cache.py
@@ -57,6 +57,7 @@ def sources_weight(sources: "HogQLDatabaseSources") -> int:
len(sources.saved_queries),
len(sources.endpoint_saved_queries),
len(sources.revenue_views),
+ len(sources.revenue_source_handles),
len(sources.warehouse_tables),
len(sources.data_warehouse_joins),
len(sources.data_warehouse_expressions),
diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.py
index f7776dc9fac2..bb4238282129 100644
--- a/posthog/hogql/database/test/test_database.py
+++ b/posthog/hogql/database/test/test_database.py
@@ -80,7 +80,9 @@ from posthog.hogql.query import execute_hogql_query
from posthog.hogql.test.utils import pretty_print_in_tests
from posthog.constants import AvailableFeature
+from posthog.models import PropertyDefinition
from posthog.models.group_type_mapping import invalidate_group_types_cache
+from posthog.models.instance_setting import override_instance_config
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.scoping import team_scope
from posthog.models.team.team import Team
@@ -95,6 +97,9 @@ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.data_tools.backend.models.expression import DataWarehouseExpression
from products.data_tools.backend.models.join import DataWarehouseJoin
from products.revenue_analytics.backend.views import RevenueAnalyticsChargeView
+from products.revenue_analytics.backend.views.core import SourceHandle
+from products.revenue_analytics.backend.views.orchestrator import build_revenue_views_for_handles
+from products.revenue_analytics.backend.views.test.data.structure import REVENUE_ANALYTICS_CONFIG_SAMPLE_EVENT
from products.warehouse_sources.backend.facade.models import (
DataWarehouseCredential,
DataWarehouseTable,
@@ -1208,19 +1213,156 @@ class TestDatabase(BaseTest, QueryMatchingTest):
assert self._ran_source_fetch_queries(ctx)
+ def _configure_revenue_events(self) -> None:
+ config = self.team.revenue_analytics_config
+ config.events = [REVENUE_ANALYTICS_CONFIG_SAMPLE_EVENT]
+ config.save()
+ # Team.revenue_analytics_config memoizes by team pk in a module-level lru_cache, so the
+ # configured object would outlive this test's transaction and leak into later tests
+ # in this class, which share the team pk.
+ self.addCleanup(Team.__dict__["revenue_analytics_config"].fget.cache_clear)
+
+ def test_revenue_views_build_only_on_revenue_table_access(self):
+ self._configure_revenue_events()
+ with patch(
+ "products.revenue_analytics.backend.views.orchestrator.build_revenue_views_for_handles",
+ wraps=build_revenue_views_for_handles,
+ ) as builder:
+ database = Database.create_for(team=self.team)
+ database.get_table("events")
+ assert builder.call_count == 0
+
+ table = database.get_table("revenue_analytics.events.purchase.charge_events_revenue_view")
+ assert builder.call_count == 1
+ assert isinstance(table, RevenueAnalyticsChargeView)
+
+ # The first access built every deferred view; later lookups reuse them.
+ database.get_table("revenue_analytics.events.purchase.mrr_events_revenue_view")
+ assert builder.call_count == 1
+
+ def test_deferred_revenue_views_serialize_identically_to_eager(self):
+ self._configure_revenue_events()
+ with override_instance_config("HOGQL_DEFERRED_REVENUE_VIEWS_ENABLED", False):
+ eager = Database.create_for(team=self.team)
+ deferred = Database.create_for(team=self.team)
+
+ eager_tables = eager.serialize(HogQLContext(team_id=self.team.pk, database=eager))
+ deferred_tables = deferred.serialize(HogQLContext(team_id=self.team.pk, database=deferred))
+
+ assert eager_tables.keys() == deferred_tables.keys()
+ view_name = "revenue_analytics.events.purchase.charge_events_revenue_view"
+ assert deferred_tables[view_name] == eager_tables[view_name]
+
+ def test_event_modifier_on_revenue_view_gets_id_mappings(self):
+ self._configure_revenue_events()
+ view_name = "revenue_analytics.events.purchase.charge_events_revenue_view"
+ modifiers = create_default_modifiers_for_team(
+ self.team,
+ modifiers=HogQLQueryModifiers(
+ dataWarehouseEventsModifiers=[
+ DataWarehouseEventsModifier(
+ table_name=view_name,
+ id_field="id",
+ timestamp_field="timestamp",
+ distinct_id_field="customer_id",
+ )
+ ]
+ ),
+ )
+
+ deferred_default = Database.create_for(team=self.team, modifiers=modifiers)
+ with override_instance_config("HOGQL_DEFERRED_REVENUE_VIEWS_ENABLED", False):
+ eager = Database.create_for(team=self.team, modifiers=modifiers)
+
+ deferred_fields = deferred_default.get_table(view_name).fields
+ eager_fields = eager.get_table(view_name).fields
+ assert "distinct_id" in deferred_fields
+ assert "person_id" in deferred_fields
+ assert deferred_fields.keys() == eager_fields.keys()
+
+ def test_deferred_revenue_view_build_runs_no_queries(self):
+ self._configure_revenue_events()
+ # A boolean test-account filter makes filter preparation resolve property types from
+ # Postgres; that lookup must happen when handles are fetched, not at resolution time.
+ PropertyDefinition.objects.create(
+ team=self.team, name="is_internal", type=PropertyDefinition.Type.EVENT, property_type="Boolean"
+ )
+ self.team.test_account_filters = [
+ {"key": "is_internal", "type": "event", "value": ["true"], "operator": "exact"}
+ ]
+ self.team.save()
+ config = self.team.revenue_analytics_config
+ config.filter_test_accounts = True
+ config.save()
+
+ database = Database.create_for(team=self.team)
+ with CaptureQueriesContext(connection) as context:
+ table = database.get_table("revenue_analytics.events.purchase.charge_events_revenue_view")
+
+ assert isinstance(table, RevenueAnalyticsChargeView)
+ assert len(context.captured_queries) == 0
+
+ def test_partial_serialize_skips_revenue_view_build(self):
+ self._configure_revenue_events()
+ database = Database.create_for(team=self.team)
+ context = HogQLContext(team_id=self.team.pk, database=database)
+
+ with patch(
+ "products.revenue_analytics.backend.views.orchestrator.build_revenue_views_for_handles",
+ wraps=build_revenue_views_for_handles,
+ ) as builder:
+ # The sidebar hydrates one table's fields at a time; that request must not build
+ # every revenue view only to discard them.
+ partial = database.serialize(context, include_only={"events"})
+ assert builder.call_count == 0
+
+ full = database.serialize(context)
+ assert builder.call_count == 1
+
+ assert "events" in partial
+ assert "revenue_analytics.events.purchase.charge_events_revenue_view" in full
+
+ def test_warm_cached_serialize_reuses_prebuilt_revenue_views(self):
+ self._configure_revenue_events()
+ Database.create_for(team=self.team, user=self.user, use_cached_sources=True)
+
+ with patch(
+ "products.revenue_analytics.backend.views.orchestrator.build_revenue_views_for_handles",
+ wraps=build_revenue_views_for_handles,
+ ) as builder:
+ warm = Database.create_for(team=self.team, user=self.user, use_cached_sources=True)
+ warm.serialize(HogQLContext(team_id=self.team.pk, database=warm))
+ assert builder.call_count == 0
+
+ def test_join_on_deferred_revenue_view_is_wired(self):
+ self._configure_revenue_events()
+ DataWarehouseJoin.objects.create(
+ team=self.team,
+ source_table_name="events",
+ source_table_key="event",
+ joining_table_name="revenue_analytics.events.purchase.charge_events_revenue_view",
+ joining_table_key="id",
+ field_name="purchase_charge",
+ )
+
+ database = Database.create_for(team=self.team)
+
+ assert "purchase_charge" in database.get_table("events").fields
+
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"
+ team=self.team, table_name="stripe.stub.charges", field_name="secret_expr", expression="1 + 1"
)
stub_view = RevenueAnalyticsChargeView(
id="stub-view",
- name="stub_revenue_view",
+ name="stripe.stub.charges",
query="SELECT 'x' AS id",
fields={"id": StringDatabaseField(name="id")},
prefix="stub",
)
+ stub_handle = SourceHandle(type="stripe", team=self.team)
with (
patch(
@@ -1228,17 +1370,23 @@ class TestDatabase(BaseTest, QueryMatchingTest):
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],
+ "products.revenue_analytics.backend.views.orchestrator.list_revenue_source_handles",
+ return_value=[stub_handle],
+ ),
+ patch(
+ "products.revenue_analytics.backend.views.orchestrator.build_revenue_views_for_handles",
+ side_effect=lambda *args, **kwargs: [stub_view.model_copy(deep=True)],
),
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
+ # Inside the patch context: resolving the view on `denied` builds its deferred views,
+ # which must go through the patched builder.
+ assert allowed.get_table("stripe.stub.charges") is not denied.get_table("stripe.stub.charges")
+ assert "secret_expr" in allowed.get_table("stripe.stub.charges").fields
+ assert "secret_expr" not in denied.get_table("stripe.stub.charges").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)
@@ -4419,6 +4567,7 @@ class TestSourcesCacheConcurrency(TestCase):
saved_queries=[],
endpoint_saved_queries=[],
revenue_views=[],
+ revenue_source_handles=[],
warehouse_tables=[object()] * row_count,
data_warehouse_joins=[],
data_warehouse_expressions=[],
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.py
index ce7a715091a7..8725f53b79db 100644
--- a/posthog/settings/dynamic_settings.py
+++ b/posthog/settings/dynamic_settings.py
@@ -26,6 +26,12 @@ CONSTANCE_CONFIG = {
"and series threads. Disable to fall back to building a database per call.",
bool,
),
+ "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 "
+ "that resolves a revenue table. Disable to fall back to building them on every database build.",
+ bool,
+ ),
"MATERIALIZED_COLUMNS_ENABLED": (
get_from_env("MATERIALIZED_COLUMNS_ENABLED", True, type_cast=str_to_bool),
"Whether materialized columns should be created or used at query time.",
@@ -365,6 +371,7 @@ CONSTANCE_CONFIG = {
SETTINGS_ALLOWING_API_OVERRIDE = (
"GROWTH_SIGNUP_ENRICHMENT_ENABLED",
"GROWTH_ICP_REENRICH_DAILY_CAP",
+ "HOGQL_DEFERRED_REVENUE_VIEWS_ENABLED",
"HOGQL_SHARED_INSIGHT_DATABASE_ENABLED",
"RECORDINGS_PERFORMANCE_EVENTS_TTL_WEEKS",
"AUTO_START_ASYNC_MIGRATIONS",
diff --git a/posthog/test/base.py b/posthog/test/base.py
index 6455a565ea53..0146d2220d0e 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -711,9 +711,11 @@ class PostHogTestCase(SimpleTestCase):
# 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
- # on which events-schema mode CI is running.
+ # on which events-schema mode CI is running. The deferred-revenue-views gate is read
+ # on the same database-build path, so it is warmed for the same reason.
get_instance_setting("CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA")
get_instance_setting("CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA_TEAMS")
+ get_instance_setting("HOGQL_DEFERRED_REVENUE_VIEWS_ENABLED")
if get_instance_setting("PERSON_ON_EVENTS_ENABLED"):
from posthog.models.team import util
diff --git a/products/revenue_analytics/backend/views/core.py b/products/revenue_analytics/backend/views/core.py
index f8914fa92a1c..c8e5c2c7980d 100644
--- a/products/revenue_analytics/backend/views/core.py
+++ b/products/revenue_analytics/backend/views/core.py
@@ -19,6 +19,10 @@ class SourceHandle:
team: Team
source: Optional[RevenueSource] = None
event: Optional[RevenueAnalyticsEventItem] = None
+ # Prepared test-account filter expression for events handles. Resolving filter property types
+ # queries Postgres, so it is computed once when handles are fetched; builders must then run
+ # without I/O so views can be built lazily at table-resolution time.
+ events_filter_expr: Optional[ast.Expr] = None
@dataclass
diff --git a/products/revenue_analytics/backend/views/orchestrator.py b/products/revenue_analytics/backend/views/orchestrator.py
index 9d0cd92b0a54..3783d47a9396 100644
--- a/products/revenue_analytics/backend/views/orchestrator.py
+++ b/products/revenue_analytics/backend/views/orchestrator.py
@@ -13,6 +13,7 @@ from posthog.models.team.team import Team
from products.revenue_analytics.backend.views import KIND_TO_CLASS, RevenueAnalyticsBaseView
from products.revenue_analytics.backend.views.core import BuiltQuery, SourceHandle
from products.revenue_analytics.backend.views.schemas import SCHEMAS
+from products.revenue_analytics.backend.views.sources.helpers import events_expr_for_team
from products.revenue_analytics.backend.views.sources.registry import BUILDERS
from products.warehouse_sources.backend.facade.api import list_revenue_sources
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
@@ -22,8 +23,20 @@ SUPPORTED_SOURCES: list[ExternalDataSourceType] = [ExternalDataSourceType.STRIPE
def _iter_source_handles(team: Team, timings: HogQLTimings) -> Iterable[SourceHandle]:
with timings.measure("for_events", emit_span=True):
- for event in team.revenue_analytics_config.events:
- yield SourceHandle(type="events", team=team, event=event)
+ events = team.revenue_analytics_config.events
+ if events:
+ # Prepared here, once per team: resolving filter property types queries Postgres, and
+ # handles must carry everything the builders need so deferred building does no I/O.
+ try:
+ events_filter_expr = events_expr_for_team(team)
+ except Exception as e:
+ # A test-account filter that cannot resolve, for example one naming a deleted
+ # cohort, must cost only the events views. Skip them so the external sources
+ # below still yield their handles.
+ capture_exception(e, {"team_id": team.pk, "handle_type": "events"})
+ else:
+ for event in events:
+ yield SourceHandle(type="events", team=team, event=event, events_filter_expr=events_filter_expr)
with timings.measure("for_schema_sources", emit_span=True):
for source in list_revenue_sources(team.pk, source_types=SUPPORTED_SOURCES):
@@ -59,6 +72,17 @@ def _query_to_view(
)
+def list_revenue_source_handles(team: Team, timings: Optional[HogQLTimings] = None) -> list[SourceHandle]:
+ """The I/O half of view building: one handle per configured revenue event and enabled source.
+
+ Callers that defer view construction fetch these up front and run
+ `build_revenue_views_for_handles` later, off the fetch path.
+ """
+ if timings is None:
+ timings = HogQLTimings()
+ return list(_iter_source_handles(team, timings))
+
+
def build_all_revenue_analytics_views(
team: Team, timings: Optional[HogQLTimings] = None
) -> list[RevenueAnalyticsBaseView]:
@@ -71,8 +95,21 @@ def build_all_revenue_analytics_views(
if timings is None:
timings = HogQLTimings()
+ return build_revenue_views_for_handles(list(_iter_source_handles(team, timings)), timings)
+
+
+def build_revenue_views_for_handles(
+ handles: list[SourceHandle], timings: Optional[HogQLTimings] = None
+) -> list[RevenueAnalyticsBaseView]:
+ """The pure half of view building: run the registered builders for already-fetched handles.
+
+ Does no I/O beyond what each handle carries, so it can run lazily at table-resolution time.
+ """
+ if timings is None:
+ timings = HogQLTimings()
+
views: list[RevenueAnalyticsBaseView] = []
- for handle in _iter_source_handles(team, timings):
+ for handle in handles:
identifier = handle.event.eventName if handle.event else handle.source.id if handle.source else None
with timings.measure(f"builder.{handle.type}.{identifier}"):
per_kind = BUILDERS.get(handle.type, {})
diff --git a/products/revenue_analytics/backend/views/sources/events/charge.py b/products/revenue_analytics/backend/views/sources/events/charge.py
index a0ab6849796d..bf383c9eadcc 100644
--- a/products/revenue_analytics/backend/views/sources/events/charge.py
+++ b/products/revenue_analytics/backend/views/sources/events/charge.py
@@ -8,7 +8,7 @@ from products.revenue_analytics.backend.views.core import BuiltQuery, SourceHand
from products.revenue_analytics.backend.views.sources.helpers import (
currency_aware_amount,
currency_aware_divider,
- events_expr_for_team,
+ events_expr_for_handle,
is_zero_decimal_in_stripe,
)
@@ -20,7 +20,7 @@ def build(handle: SourceHandle) -> BuiltQuery:
if event is None:
raise ValueError("Event is required")
- generic_team_expr = events_expr_for_team(team)
+ generic_team_expr = events_expr_for_handle(handle)
prefix = view_prefix_for_event(event.eventName)
diff --git a/products/revenue_analytics/backend/views/sources/events/customer.py b/products/revenue_analytics/backend/views/sources/events/customer.py
index 82a6b71153ad..ea41dbfbd890 100644
--- a/products/revenue_analytics/backend/views/sources/events/customer.py
+++ b/products/revenue_analytics/backend/views/sources/events/customer.py
@@ -1,11 +1,10 @@
from posthog.hogql import ast
from products.revenue_analytics.backend.views.core import BuiltQuery, SourceHandle, view_prefix_for_event
-from products.revenue_analytics.backend.views.sources.helpers import events_expr_for_team, get_cohort_expr
+from products.revenue_analytics.backend.views.sources.helpers import events_expr_for_handle, get_cohort_expr
def build(handle: SourceHandle) -> BuiltQuery:
- team = handle.team
event = handle.event
if event is None:
@@ -17,7 +16,7 @@ def build(handle: SourceHandle) -> BuiltQuery:
distinct=True,
select=[ast.Alias(alias="person_id", expr=ast.Field(chain=["events", "person", "id"]))],
select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
- where=events_expr_for_team(team),
+ where=events_expr_for_handle(handle),
)
query = ast.SelectQuery(
diff --git a/products/revenue_analytics/backend/views/sources/events/product.py b/products/revenue_analytics/backend/views/sources/events/product.py
index bf69121af714..ec9b067e67bb 100644
--- a/products/revenue_analytics/backend/views/sources/events/product.py
+++ b/products/revenue_analytics/backend/views/sources/events/product.py
@@ -2,11 +2,10 @@ from posthog.hogql import ast
from products.revenue_analytics.backend.views.core import BuiltQuery, SourceHandle, view_prefix_for_event
from products.revenue_analytics.backend.views.schemas.product import SCHEMA as PRODUCT_SCHEMA
-from products.revenue_analytics.backend.views.sources.helpers import events_expr_for_team
+from products.revenue_analytics.backend.views.sources.helpers import events_expr_for_handle
def build(handle: SourceHandle) -> BuiltQuery:
- team = handle.team
event = handle.event
if event is None:
@@ -26,7 +25,7 @@ def build(handle: SourceHandle) -> BuiltQuery:
distinct=True,
select=[ast.Alias(alias="product_id", expr=ast.Field(chain=["events", "properties", event.productProperty]))],
select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
- where=events_expr_for_team(team),
+ where=events_expr_for_handle(handle),
)
query = ast.SelectQuery(
diff --git a/products/revenue_analytics/backend/views/sources/events/revenue_item.py b/products/revenue_analytics/backend/views/sources/events/revenue_item.py
index 021645ff9f21..6604fb39b326 100644
--- a/products/revenue_analytics/backend/views/sources/events/revenue_item.py
+++ b/products/revenue_analytics/backend/views/sources/events/revenue_item.py
@@ -8,7 +8,7 @@ from products.revenue_analytics.backend.views.core import BuiltQuery, SourceHand
from products.revenue_analytics.backend.views.sources.helpers import (
currency_aware_amount,
currency_aware_divider,
- events_expr_for_team,
+ events_expr_for_handle,
is_zero_decimal_in_stripe,
)
@@ -20,7 +20,7 @@ def build(handle: SourceHandle) -> BuiltQuery:
if event is None:
raise ValueError("Event is required")
- generic_team_expr = events_expr_for_team(team)
+ generic_team_expr = events_expr_for_handle(handle)
revenue_exprs = revenue_comparison_and_value_exprs_for_events(team, event, do_currency_conversion=False)
currency_aware_amount_expr = revenue_comparison_and_value_exprs_for_events(
diff --git a/products/revenue_analytics/backend/views/sources/events/subscription.py b/products/revenue_analytics/backend/views/sources/events/subscription.py
index 36272d753bb0..aa8f2969315b 100644
--- a/products/revenue_analytics/backend/views/sources/events/subscription.py
+++ b/products/revenue_analytics/backend/views/sources/events/subscription.py
@@ -4,11 +4,10 @@ from posthog.hogql import ast
from products.revenue_analytics.backend.views.core import BuiltQuery, SourceHandle, view_prefix_for_event
from products.revenue_analytics.backend.views.schemas.subscription import SCHEMA as SUBSCRIPTION_SCHEMA
-from products.revenue_analytics.backend.views.sources.helpers import events_expr_for_team
+from products.revenue_analytics.backend.views.sources.helpers import events_expr_for_handle
def build(handle: SourceHandle) -> BuiltQuery:
- team = handle.team
event = handle.event
if event is None:
@@ -50,7 +49,7 @@ def build(handle: SourceHandle) -> BuiltQuery:
select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
where=ast.And(
exprs=[
- events_expr_for_team(team),
+ events_expr_for_handle(handle),
ast.Call(name="isNotNull", args=[ast.Field(chain=["subscription_id"])]),
]
),
diff --git a/products/revenue_analytics/backend/views/sources/helpers.py b/products/revenue_analytics/backend/views/sources/helpers.py
index 47c61c45ee5a..176bdb96d3d4 100644
--- a/products/revenue_analytics/backend/views/sources/helpers.py
+++ b/products/revenue_analytics/backend/views/sources/helpers.py
@@ -1,4 +1,5 @@
from datetime import datetime
+from typing import cast
from django.conf import settings
@@ -10,6 +11,8 @@ from posthog.hogql.parser import parse_expr
from posthog.models.exchange_rate.sql import EXCHANGE_RATE_DECIMAL_PRECISION
from posthog.models.team.team import Team
+from products.revenue_analytics.backend.views.core import SourceHandle
+
# Stripe represents most currencies with integer amounts multiplied by 100,
# since most currencies have its smallest unit as 1/100 of their base unit
# It just so happens that some currencies don't have that concept, so they're listed here
@@ -93,6 +96,20 @@ def events_expr_for_team(team: Team) -> ast.Expr:
return ast.And(exprs=exprs)
+def events_expr_for_handle(handle: SourceHandle) -> ast.Expr:
+ """The handle's prepared filter expression, or a fresh one when the handle carries none.
+
+ Cloned because the resolver mutates ASTs in place and one handle builds several views.
+ Property-type resolution queries Postgres, so builders must prefer the prepared expression;
+ the fallback keeps direct builder invocations (tests, scripts) working.
+ """
+ from posthog.hogql.visitor import clone_expr
+
+ if handle.events_filter_expr is not None:
+ return cast(ast.Expr, clone_expr(handle.events_filter_expr))
+ return events_expr_for_team(handle.team)
+
+
def get_cohort_expr(field: str) -> ast.Expr:
return parse_expr(f"formatDateTime(toStartOfMonth({field}), '%Y-%m')")
diff --git a/products/revenue_analytics/backend/views/test/test_orchestrator.py b/products/revenue_analytics/backend/views/test/test_orchestrator.py
index c7a2ba4cb418..dda3b104c3c7 100644
--- a/products/revenue_analytics/backend/views/test/test_orchestrator.py
+++ b/products/revenue_analytics/backend/views/test/test_orchestrator.py
@@ -14,6 +14,7 @@ from products.revenue_analytics.backend.views import (
)
from products.revenue_analytics.backend.views.orchestrator import build_all_revenue_analytics_views
from products.revenue_analytics.backend.views.sources.helpers import ZERO_DECIMAL_CURRENCIES_IN_STRIPE
+from products.revenue_analytics.backend.views.test.data.structure import REVENUE_ANALYTICS_CONFIG_SAMPLE_EVENT
from products.warehouse_sources.backend.facade.models import (
DataWarehouseCredential,
DataWarehouseTable,
@@ -97,6 +98,19 @@ class TestRevenueAnalyticsViews(BaseTest):
self.assertEqual(len(mrr_views), 1)
self.assertEqual(mrr_views[0].name, "stripe.mrr_revenue_view")
+ def test_unresolvable_test_account_filter_keeps_source_views(self):
+ self.team.test_account_filters = [{"type": "cohort", "key": "id", "value": 987654321}]
+ self.team.save()
+ self.team.revenue_analytics_config.filter_test_accounts = True
+ self.team.revenue_analytics_config.events = [REVENUE_ANALYTICS_CONFIG_SAMPLE_EVENT]
+ self.team.revenue_analytics_config.save()
+
+ views = build_all_revenue_analytics_views(self.team, self.timings)
+
+ source_views = [v for v in views if v.source_id == str(self.source.id)]
+ self.assertEqual(len(source_views), 6)
+ self.assertEqual([v for v in views if v.source_id is None], [])
+
def test_revenue_view_with_disabled_source(self):
"""Test that the orchestrator returns None for disabled sources"""
self.source.revenue_analytics_config.enabled = False