Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(autoresearch): cut accounts list query latency by ~70% (#78648)

Arthur Moreira de Deus64b1d4719263
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index b5f83dde6cf8..e4768f4bf2e5 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -27224,6 +27224,10 @@
"enum": ["disabled", "optimized"],
"type": "string"
},
+ "mergeFederatedAggregateJoins": {
+ "description": "Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap",
+ "type": "boolean"
+ },
"optimizeJoinedFilters": {
"type": "boolean"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 7865793d3cfe..62e3931d91eb 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -514,6 +514,8 @@ export interface HogQLQueryModifiers {
/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
typeAwareCastSimplification?: boolean
pushDownPredicates?: boolean
+ /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
+ mergeFederatedAggregateJoins?: boolean
/** If these are provided, the query will fail if these skip indexes are not used */
forceClickhouseDataSkippingIndexes?: string[]
inlineCohortCalculation?: 'off' | 'auto' | 'always'
diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.py
index a96f1d1f96dc..d047a1c3d26a 100644
--- a/posthog/clickhouse/client/execute.py
+++ b/posthog/clickhouse/client/execute.py
@@ -572,6 +572,38 @@ def query_with_columns(
return rows
+def _has_comment_marker_outside_strings(sql: str) -> bool:
+ """Whether the SQL contains a `--` or `/*` comment marker outside quoted spans.
+
+ A plain substring check false-positives on markers inside string literals (e.g. an
+ s3() glob like '.../*.csv') and sends comment-free queries through sqlparse, which
+ costs ~100ms on a multi-KB query. Quoted spans ('', "", ``) hide markers; ClickHouse
+ escapes quotes inside them with a backslash or by doubling, both handled below.
+ """
+ i, n = 0, len(sql)
+ while i < n - 1:
+ ch = sql[i]
+ if ch in ("'", '"', "`"):
+ quote = ch
+ i += 1
+ while i < n:
+ if sql[i] == "\\":
+ i += 2
+ continue
+ if sql[i] == quote:
+ if i + 1 < n and sql[i + 1] == quote:
+ i += 2
+ continue
+ break
+ i += 1
+ elif ch == "-" and sql[i + 1] == "-":
+ return True
+ elif ch == "/" and sql[i + 1] == "*":
+ return True
+ i += 1
+ return False
+
+
def _prepare_query(
query: str,
args: QueryArgs,
@@ -614,7 +646,9 @@ def _prepare_query(
# non-templated SQL
rendered_sql = substitute_params(query, args)
- if "--" in rendered_sql or "/*" in rendered_sql:
+ # Substring check first: it rejects the common comment-free case at C speed, so the
+ # per-character scan only runs when a marker exists somewhere in the SQL.
+ if ("--" in rendered_sql or "/*" in rendered_sql) and _has_comment_marker_outside_strings(rendered_sql):
# This can take a very long time with e.g. large funnel queries
formatted_sql = sqlparse.format(rendered_sql, strip_comments=True)
else:
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index e6a0d0f4fc09..b359256d92ab 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -107,8 +107,8 @@ TEAM_ID_FILTER_PATTERNS = {
# Junction tables without team_id; isolation is enforced via an account_id IN system.accounts predicate
"_account_resource_notebooks": "system__accounts.team_id",
"_account_tagged_items": "system__accounts.team_id",
- "_account_custom_property_values": "system__accounts.team_id",
- "_account_custom_property_values_history": "system__accounts.team_id",
+ # The custom property tables declare their real team_id column, so the standard direct
+ # guard applies (and is pushed into the federated read).
# Same shape, scoped through system.support_tickets instead
"_ticket_tagged_items": "system__support_tickets.team_id",
"_ticket_assignments": "system__support_tickets.team_id",
diff --git a/posthog/hogql/database/test/test_postgres_table.py b/posthog/hogql/database/test/test_postgres_table.py
index c577a4004c50..67ef620ed5eb 100644
--- a/posthog/hogql/database/test/test_postgres_table.py
+++ b/posthog/hogql/database/test/test_postgres_table.py
@@ -198,7 +198,7 @@ class TestPostgresTable(BaseTest):
)
self.assertEqual(
self._select("SELECT * FROM postgres_table LIMIT 10"),
- f"SELECT postgres_table.id AS id, postgres_table.team_id AS team_id, postgres_table.name AS name FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS postgres_table WHERE equals(postgres_table.team_id, {self.team.pk}) LIMIT 10",
+ f"SELECT postgres_table.id AS id, postgres_table.team_id AS team_id, postgres_table.name AS name FROM (SELECT * FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) WHERE team_id = {self.team.pk}) AS postgres_table WHERE equals(postgres_table.team_id, {self.team.pk}) LIMIT 10",
)
def test_single_predicate(self):
@@ -271,7 +271,7 @@ class TestPostgresTable(BaseTest):
"LEFT JOIN postgres_table ON other_table.ref_id = postgres_table.id "
"LIMIT 10",
),
- f"SELECT other_table.id AS id, postgres_table.name AS name FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS other_table LEFT JOIN postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table ON and(and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30)))), equals(other_table.ref_id, postgres_table.id)) WHERE equals(other_table.team_id, {self.team.pk}) LIMIT 10",
+ f"SELECT other_table.id AS id, postgres_table.name AS name FROM (SELECT * FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) WHERE team_id = {self.team.pk}) AS other_table LEFT JOIN postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table ON and(and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30)))), equals(other_table.ref_id, postgres_table.id)) WHERE equals(other_table.team_id, {self.team.pk}) LIMIT 10",
)
def test_left_join_multiple_predicates(self):
@@ -302,7 +302,7 @@ class TestPostgresTable(BaseTest):
"LEFT JOIN postgres_table ON other_table.ref_id = postgres_table.id "
"LIMIT 10",
),
- f"SELECT other_table.id AS id FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS other_table LEFT JOIN postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table ON and(and(and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30)))), notEquals(postgres_table.status, %(hogql_val_10)s)), equals(other_table.ref_id, postgres_table.id)) WHERE equals(other_table.team_id, {self.team.pk}) LIMIT 10",
+ f"SELECT other_table.id AS id FROM (SELECT * FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) WHERE team_id = {self.team.pk}) AS other_table LEFT JOIN postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table ON and(and(and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30)))), notEquals(postgres_table.status, %(hogql_val_10)s)), equals(other_table.ref_id, postgres_table.id)) WHERE equals(other_table.team_id, {self.team.pk}) LIMIT 10",
)
def test_inner_join_predicate(self):
@@ -327,7 +327,7 @@ class TestPostgresTable(BaseTest):
"INNER JOIN postgres_table ON other_table.ref_id = postgres_table.id "
"LIMIT 10",
),
- f"SELECT other_table.id AS id, postgres_table.name AS name FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS other_table INNER JOIN postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table ON equals(other_table.ref_id, postgres_table.id) WHERE and(and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30)))), equals(other_table.team_id, {self.team.pk})) LIMIT 10",
+ f"SELECT other_table.id AS id, postgres_table.name AS name FROM (SELECT * FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) WHERE team_id = {self.team.pk}) AS other_table INNER JOIN postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table ON equals(other_table.ref_id, postgres_table.id) WHERE and(and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30)))), equals(other_table.team_id, {self.team.pk})) LIMIT 10",
)
def test_left_join_predicate_with_user_where(self):
@@ -354,7 +354,7 @@ class TestPostgresTable(BaseTest):
"WHERE other_table.ref_id > 100 "
"LIMIT 10",
),
- f"SELECT other_table.id AS id, postgres_table.name AS name FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS other_table LEFT JOIN postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table ON and(and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30)))), equals(other_table.ref_id, postgres_table.id)) WHERE and(equals(other_table.team_id, {self.team.pk}), greater(other_table.ref_id, 100)) LIMIT 10",
+ f"SELECT other_table.id AS id, postgres_table.name AS name FROM (SELECT * FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) WHERE team_id = {self.team.pk}) AS other_table LEFT JOIN postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table ON and(and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30)))), equals(other_table.ref_id, postgres_table.id)) WHERE and(equals(other_table.team_id, {self.team.pk}), greater(other_table.ref_id, 100)) LIMIT 10",
)
def test_lazy_join_with_predicate(self):
@@ -407,7 +407,7 @@ class TestPostgresTable(BaseTest):
)
self.assertEqual(
self._select("SELECT details.name FROM other_table LIMIT 10"),
- f"SELECT other_table__details.name AS name FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) AS other_table LEFT JOIN (SELECT postgres_table.name AS name, postgres_table.id AS other_table__details___id FROM postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table WHERE and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30))))) AS other_table__details ON equals(other_table.ref_id, other_table__details.other_table__details___id) WHERE equals(other_table.team_id, {self.team.pk}) LIMIT 10",
+ f"SELECT other_table__details.name AS name FROM (SELECT * FROM postgresql(%(hogql_val_1_sensitive)s, %(hogql_val_2_sensitive)s, %(hogql_val_0_sensitive)s, %(hogql_val_3_sensitive)s, %(hogql_val_4_sensitive)s) WHERE team_id = {self.team.pk}) AS other_table LEFT JOIN (SELECT postgres_table.name AS name, postgres_table.id AS other_table__details___id FROM postgresql(%(hogql_val_6_sensitive)s, %(hogql_val_7_sensitive)s, %(hogql_val_5_sensitive)s, %(hogql_val_8_sensitive)s, %(hogql_val_9_sensitive)s) AS postgres_table WHERE and(equals(postgres_table.team_id, {self.team.pk}), greaterOrEquals(postgres_table.created_at, minus(today(), toIntervalDay(30))))) AS other_table__details ON equals(other_table.ref_id, other_table__details.other_table__details___id) WHERE equals(other_table.team_id, {self.team.pk}) LIMIT 10",
)
def test_predicate_with_nested_property_access(self):
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.py
index 2f3d8a022be4..eca0f141506e 100644
--- a/posthog/hogql/printer/clickhouse.py
+++ b/posthog/hogql/printer/clickhouse.py
@@ -1002,6 +1002,32 @@ class ClickHousePrinter(BasePrinter):
):
sql = f"(SELECT * FROM {sql})"
+ # ClickHouse doesn't push the outer team_id guard through joins into a postgresql()
+ # read, so a joined federated table gets COPY'd out of Postgres in full. Repeat the
+ # filter adjacent to the table function, where it does get pushed down; the outer
+ # guard stays and column pruning still applies through the SELECT *. Skip tables
+ # that declare predicates: those print in the enclosing select, and the wrap would
+ # block them from being pushed into the federated read alongside the team guard.
+ from posthog.hogql.database.postgres_table import (
+ PostgresTable, # noqa: PLC0415 (keeps persons-DB deps off the printer import path)
+ )
+
+ if (
+ isinstance(table, PostgresTable)
+ # mypy proves this intersection impossible from signatures, but subclasses of
+ # both exist at runtime (customer_analytics _AccountScopedPostgresTable).
+ and not isinstance(table, DANGEROUS_NoTeamIdCheckTable) # type: ignore[unreachable]
+ and "team_id" in table.fields
+ and not table.get_predicates()
+ and self.context.team_id is not None
+ ):
+ # The HogQL `team_id` field may map to a differently named DB column (e.g.
+ # system.teams exposes it as an alias of `id`), so filter the real column, not
+ # the HogQL name. Skip the wrap when the field isn't a plain column.
+ team_id_column = getattr(table.fields["team_id"], "name", None)
+ if team_id_column:
+ sql = f"(SELECT * FROM {sql} WHERE {team_id_column} = {int(self.context.team_id)})"
+
return sql
def _print_select_columns(self, columns):
diff --git a/posthog/hogql/printer/test/test_hogql_access_control.py b/posthog/hogql/printer/test/test_hogql_access_control.py
index 1f59f971cd8c..d45717ebb8f6 100644
--- a/posthog/hogql/printer/test/test_hogql_access_control.py
+++ b/posthog/hogql/printer/test/test_hogql_access_control.py
@@ -321,6 +321,46 @@ class TestAccessControlGuard(BaseTest):
assert f"notIn(toString(system__dashboard_tiles.dashboard_id), %({deny_key})s)" in sql
assert "notIn(toString(system__dashboard_tiles.id)" not in sql
+ def test_account_custom_property_values_guard_filters_account_fk(self):
+ # The hidden EAV tables scope by a direct team guard, so the per-account deny set
+ # must be declared on the table itself (account_id FK) - without it a member denied
+ # an account could read its property values by selecting the hidden table directly.
+ from posthog.hogql.parser import parse_select
+
+ from posthog.constants import AvailableFeature
+
+ from ee.models import AccessControl
+
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ ]
+ self.organization.save()
+
+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save()
+
+ AccessControl.objects.create(team=self.team, resource="account", resource_id="acct-42", access_level="none")
+
+ for table in ("_account_custom_property_values", "_account_custom_property_values_history"):
+ context = HogQLContext(
+ team_id=self.team.pk,
+ team=self.team,
+ user=self.user,
+ enable_select_queries=True,
+ )
+ prepared = prepare_ast_for_printing(
+ parse_select(f"SELECT id FROM system.{table}"),
+ context=context,
+ dialect="clickhouse",
+ )
+ assert prepared is not None
+ sql = print_prepared_ast(prepared, context=context, dialect="clickhouse")
+ deny_keys = [k for k in context.values if k.endswith("_sensitive") and isinstance(context.values[k], list)]
+ assert len(deny_keys) == 1, table
+ assert context.values[deny_keys[0]] == ["acct-42"], table
+ assert f"notIn(toString(system__{table}.account_id), %({deny_keys[0]})s)" in sql, table
+
class TestDeniedTableError(BaseTest):
"""Test that denied tables show a helpful error message."""
diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.py
index 6636ea9ed0a5..06d70bd04a68 100644
--- a/posthog/hogql/printer/utils.py
+++ b/posthog/hogql/printer/utils.py
@@ -265,6 +265,17 @@ def prepare_ast_for_printing(
with context.timings.measure("resolve_lazy_tables"):
resolve_lazy_tables(node, dialect, stack, context, resolver_factory=resolver_factory)
+ # Sibling aggregating LEFT JOINs over federated Postgres tables execute their scans
+ # sequentially; merging them into one UNION ALL join overlaps the per-scan latency.
+ if context.modifiers is not None and context.modifiers.mergeFederatedAggregateJoins:
+ with context.timings.measure("merge_federated_aggregate_joins"):
+ # Deferred: same module-level cycle as clickhouse_property_resolution below.
+ from posthog.hogql.transforms.federated_join_merge import (
+ merge_federated_aggregate_joins, # noqa: PLC0415
+ )
+
+ node = merge_federated_aggregate_joins(node, context, dialect, stack, resolver_factory=resolver_factory)
+
with context.timings.measure("swap_properties"):
node = PropertySwapper(
timezone=context.property_swapper.timezone,
diff --git a/posthog/hogql/transforms/federated_join_merge.py b/posthog/hogql/transforms/federated_join_merge.py
new file mode 100644
index 000000000000..6616eab911fd
--- /dev/null
+++ b/posthog/hogql/transforms/federated_join_merge.py
@@ -0,0 +1,339 @@
+"""Merge sibling aggregating LEFT JOINs over federated Postgres tables into one join.
+
+A select like `accounts LEFT JOIN (agg₁) LEFT JOIN (agg₂) LEFT JOIN (agg₃)`, where each
+right side is a `GROUP BY <key>` subquery over `postgresql(...)` reads joined on the same
+base key, executes its federated scans sequentially, one per join. Rewriting the siblings
+into a single join over `UNION ALL` branches re-grouped by the key lets ClickHouse run all
+the scans inside one pipeline stage, so the per-scan Postgres COPY latencies overlap
+instead of adding up.
+
+The rewrite must reproduce LEFT JOIN default-fill semantics per column, so only three
+column shapes are merged, and anything else makes the whole select ineligible, favoring
+correctness over coverage:
+
+- `count()` columns: padded with NULL in other branches, re-aggregated as
+ `coalesce(max(col), 0)`, so a miss fills 0, matching the original non-nullable default.
+- array columns: padded with `[]`, re-aggregated as `max(col)`: at most one branch holds
+ a non-empty value, and a miss fills `[]`.
+- nullable columns: padded with NULL, re-aggregated as `max(col)` (max skips NULLs), so a
+ miss fills NULL. Non-nullable non-count scalars are rejected: their original join-miss
+ default (`''`/`0`) can't be told apart from a real value after the union.
+"""
+
+from dataclasses import dataclass
+from typing import Literal
+
+from posthog.hogql import ast
+from posthog.hogql.base import _T_AST
+from posthog.hogql.constants import HogQLDialect
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.postgres_table import PostgresTable
+from posthog.hogql.resolver import ResolverFactory, resolve_types
+from posthog.hogql.visitor import TraversingVisitor, clone_expr
+
+MERGED_ALIAS = "__merged_aggregates"
+MERGED_KEY = "__key"
+
+_ARRAY_CALLS = {"groupArray", "arraySort", "arrayDistinct", "groupUniqArray"}
+
+_ColumnKind = Literal["count", "array", "nullable"]
+
+
+@dataclass
+class _Candidate:
+ prev: ast.JoinExpr
+ join: ast.JoinExpr
+ alias: str
+ subquery: ast.SelectQuery
+ key_name: str
+ base_key_chain: tuple[str | int, ...]
+ # (column alias, kind) per non-key select column
+ columns: list[tuple[str, _ColumnKind]]
+
+
+def merge_federated_aggregate_joins(
+ node: _T_AST,
+ context: HogQLContext,
+ dialect: HogQLDialect,
+ stack: list[ast.SelectQuery] | None = None,
+ resolver_factory: ResolverFactory | None = None,
+) -> _T_AST:
+ if dialect != "clickhouse":
+ return node
+
+ finder = _SelectFinder()
+ finder.visit(node)
+ for select in finder.selects:
+ _merge_in_select(select, context, dialect, resolver_factory)
+ return node
+
+
+class _SelectFinder(TraversingVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ self.selects: list[ast.SelectQuery] = []
+
+ def visit_select_query(self, node: ast.SelectQuery):
+ self.selects.append(node)
+ super().visit_select_query(node)
+
+
+def _table_is_federated(join_expr: ast.JoinExpr | None) -> bool:
+ """Every table in the subquery's FROM chain must be a federated Postgres read.
+
+ PostgresTable specifically, not any FunctionCallTable: S3-backed warehouse joins
+ resolve their outer references through type shapes the alias rewriter doesn't
+ handle, and their scans don't serialize the way the postgresql() reads do.
+ """
+ ptr = join_expr
+ while ptr is not None:
+ table_type = getattr(ptr.table, "type", None)
+ while isinstance(table_type, (ast.TableAliasType, ast.ColumnAliasedTableType)):
+ table_type = table_type.table_type
+ if not isinstance(table_type, ast.TableType) or not isinstance(table_type.table, PostgresTable):
+ return False
+ ptr = ptr.next_join
+ return True
+
+
+def _classify_column(expr: ast.Expr) -> _ColumnKind | None:
+ if isinstance(expr, ast.Call):
+ if expr.name == "count":
+ return "count"
+ if expr.name in _ARRAY_CALLS:
+ return "array"
+ expr_type = getattr(expr, "type", None)
+ constant_type = expr_type.return_type if isinstance(expr_type, ast.CallType) else expr_type
+ if isinstance(constant_type, ast.ArrayType):
+ return "array"
+ if isinstance(constant_type, ast.ConstantType) and constant_type.nullable:
+ return "nullable"
+ return None
+
+
+def _candidate_for_join(prev: ast.JoinExpr, join: ast.JoinExpr, base_alias: str) -> _Candidate | None:
+ if join.join_type != "LEFT JOIN" or join.alias is None or not isinstance(join.table, ast.SelectQuery):
+ return None
+ constraint = join.constraint
+ if constraint is None or constraint.constraint_type != "ON":
+ return None
+ compare = constraint.expr
+ if not isinstance(compare, ast.CompareOperation) or compare.op != ast.CompareOperationOp.Eq:
+ return None
+ # The resolver wraps constraint fields in hidden aliases.
+ sides = [side.expr if isinstance(side, ast.Alias) else side for side in (compare.left, compare.right)]
+ if not all(isinstance(side, ast.Field) and len(side.chain) == 2 for side in sides):
+ return None
+ base_side = next((s for s in sides if isinstance(s, ast.Field) and s.chain[0] == base_alias), None)
+ join_side = next((s for s in sides if isinstance(s, ast.Field) and s.chain[0] == join.alias), None)
+ if base_side is None or join_side is None:
+ return None
+ key_name = str(join_side.chain[1])
+
+ subquery = join.table
+ if (
+ subquery.group_by is None
+ or len(subquery.group_by) != 1
+ or subquery.having is not None
+ or subquery.limit is not None
+ or subquery.order_by
+ or subquery.distinct
+ or subquery.settings is not None
+ or subquery.window_exprs
+ or subquery.select_from is None
+ ):
+ return None
+ group_field = subquery.group_by[0]
+ if isinstance(group_field, ast.Alias):
+ group_field = group_field.expr
+ if not isinstance(group_field, ast.Field) or str(group_field.chain[-1]) != key_name:
+ return None
+ if not _table_is_federated(subquery.select_from):
+ return None
+
+ columns: list[tuple[str, _ColumnKind]] = []
+ key_seen = False
+ for col in subquery.select:
+ if not isinstance(col, ast.Alias):
+ return None
+ if col.alias == key_name:
+ key_seen = True
+ continue
+ kind = _classify_column(col.expr)
+ if kind is None:
+ return None
+ columns.append((col.alias, kind))
+ if not key_seen or not columns:
+ return None
+
+ return _Candidate(
+ prev=prev,
+ join=join,
+ alias=join.alias,
+ subquery=subquery,
+ key_name=key_name,
+ base_key_chain=tuple(base_side.chain),
+ columns=columns,
+ )
+
+
+def _pad_expr(kind: str) -> ast.Expr:
+ if kind == "array":
+ return ast.Array(exprs=[])
+ return ast.Constant(value=None)
+
+
+def _merge_in_select(
+ node: ast.SelectQuery,
+ context: HogQLContext,
+ dialect: HogQLDialect,
+ resolver_factory: ResolverFactory | None,
+) -> bool:
+ if node.select_from is None or node.select_from.next_join is None or node.type is None:
+ return False
+ # A pre-existing table under the reserved alias would collide with the merged join
+ # during resolution, so leave such a select untouched.
+ if MERGED_ALIAS in node.type.tables:
+ return False
+ base_alias = node.select_from.alias
+ if base_alias is None and isinstance(node.select_from.table, ast.Field):
+ base_alias = str(node.select_from.table.chain[0])
+ if base_alias is None:
+ return False
+
+ candidates: list[_Candidate] = []
+ prev = node.select_from
+ join = prev.next_join
+ while join is not None:
+ candidate = _candidate_for_join(prev, join, base_alias)
+ if candidate is not None:
+ candidates.append(candidate)
+ prev = join
+ join = join.next_join
+
+ if len(candidates) < 2:
+ return False
+ # All merged joins must share one base key and one key column name, and no column
+ # name may repeat across them, because the merged subquery exposes them side by side.
+ if len({c.base_key_chain for c in candidates}) != 1 or len({c.key_name for c in candidates}) != 1:
+ return False
+ all_columns = [col for c in candidates for col in c.columns]
+ if len({name for name, _ in all_columns}) != len(all_columns):
+ return False
+
+ branches: list[ast.SelectQuery] = []
+ for candidate in candidates:
+ own = {name for name, _ in candidate.columns}
+ select: list[ast.Expr] = [ast.Alias(alias=MERGED_KEY, expr=ast.Field(chain=[candidate.key_name]))]
+ for name, kind in all_columns:
+ expr = ast.Field(chain=[name]) if name in own else _pad_expr(kind)
+ select.append(ast.Alias(alias=name, expr=expr))
+ branches.append(
+ ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(table=clone_expr(candidate.subquery, clear_types=True)),
+ )
+ )
+
+ # Qualify through an alias: a bare `count` column reference inside max() would be
+ # ambiguous with the count() function for both resolvers.
+ outer_select: list[ast.Expr] = [
+ ast.Alias(alias=MERGED_KEY, expr=ast.Field(chain=["__branches", MERGED_KEY])),
+ ]
+ for name, kind in all_columns:
+ merged: ast.Expr = ast.Call(name="max", args=[ast.Field(chain=["__branches", name])])
+ if kind == "count":
+ merged = ast.Call(name="coalesce", args=[merged, ast.Constant(value=0)])
+ outer_select.append(ast.Alias(alias=name, expr=merged))
+ merged_subquery = ast.SelectQuery(
+ select=outer_select,
+ select_from=ast.JoinExpr(
+ alias="__branches",
+ table=ast.SelectSetQuery.create_from_queries(branches, "UNION ALL"),
+ ),
+ group_by=[ast.Field(chain=["__branches", MERGED_KEY])],
+ )
+
+ merged_join = ast.JoinExpr(
+ alias=MERGED_ALIAS,
+ table=merged_subquery,
+ join_type="LEFT JOIN",
+ constraint=ast.JoinConstraint(
+ constraint_type="ON",
+ expr=ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=list(candidates[0].base_key_chain)),
+ right=ast.Field(chain=[MERGED_ALIAS, MERGED_KEY]),
+ ),
+ ),
+ )
+ # Resolve only the new join against the select's scope (the same pattern lazy-table
+ # resolution uses per join). A whole-tree re-resolve is off the table: it would
+ # recreate LazyJoinTypes for sibling lazy joins (e.g. warehouse tables) that
+ # resolve_lazy_tables has already run for and won't expand again.
+ merged_join = resolve_types(merged_join, context, dialect, [node.type], resolver_factory=resolver_factory)
+ if not isinstance(merged_join.type, ast.SelectQueryAliasType):
+ return False
+
+ _splice_merged_join(node.select_from, candidates, merged_join)
+
+ node.type.tables[MERGED_ALIAS] = merged_join.type
+ for candidate in candidates:
+ node.type.tables.pop(candidate.alias, None)
+
+ _AliasRewriter({c.alias for c in candidates}, merged_type=merged_join.type, skip=merged_subquery).visit(node)
+ return True
+
+
+def _splice_merged_join(select_from: ast.JoinExpr, candidates: list[_Candidate], merged_join: ast.JoinExpr) -> None:
+ merged_joins = {id(c.join) for c in candidates}
+ ptr = select_from
+ while ptr.next_join is not None:
+ if id(ptr.next_join) in merged_joins:
+ ptr.next_join = ptr.next_join.next_join
+ else:
+ ptr = ptr.next_join
+ merged_join.next_join = select_from.next_join
+ select_from.next_join = merged_join
+
+
+class _AliasRewriter(TraversingVisitor):
+ """Repoint outer references from the merged joins' aliases to the combined alias."""
+
+ def __init__(self, aliases: set[str], merged_type: ast.SelectQueryAliasType, skip: ast.SelectQuery) -> None:
+ super().__init__()
+ self.aliases = aliases
+ self.merged_type = merged_type
+ self.skip = skip
+
+ def visit_select_query(self, node: ast.SelectQuery):
+ if node is self.skip:
+ return
+ super().visit_select_query(node)
+
+ def _repoint(self, node: ast.Field, column: str) -> None:
+ node.chain = [MERGED_ALIAS, column]
+ node.type = ast.FieldType(name=column, table_type=self.merged_type)
+
+ def visit_field(self, node: ast.Field):
+ # Lazy-table resolution retypes fields without rewriting their chains (e.g.
+ # `accounts.tags.names` typed onto the `accounts__tags` join), so a chain check
+ # misses them, so resolve the owning join through the field's type first. Nested
+ # JSON key accesses arrive as PropertyTypes carrying the materialized column name.
+ field_type = node.type
+ if isinstance(field_type, ast.PropertyType):
+ inner = field_type.field_type
+ table_type = inner.table_type
+ if isinstance(table_type, ast.SelectQueryAliasType) and table_type.alias in self.aliases:
+ materialized = field_type.joined_subquery_field_name or "___".join(
+ [inner.name, *(str(x) for x in field_type.chain)]
+ )
+ self._repoint(node, materialized)
+ return
+ if isinstance(field_type, ast.FieldType):
+ table_type = field_type.table_type
+ if isinstance(table_type, ast.SelectQueryAliasType) and table_type.alias in self.aliases:
+ self._repoint(node, field_type.name)
+ return
+ if len(node.chain) >= 2 and node.chain[0] in self.aliases:
+ self._repoint(node, str(node.chain[1]))
diff --git a/posthog/hogql/transforms/test/test_federated_join_merge.py b/posthog/hogql/transforms/test/test_federated_join_merge.py
new file mode 100644
index 000000000000..92c52d5e4831
--- /dev/null
+++ b/posthog/hogql/transforms/test/test_federated_join_merge.py
@@ -0,0 +1,136 @@
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.schema import HogQLQueryModifiers
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.transforms.federated_join_merge import MERGED_ALIAS
+
+from products.data_tools.backend.models.join import DataWarehouseJoin
+from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable
+
+ACCOUNTS_LAZY_JOINS_QUERY = """
+ select id, accounts.tags.names as tag_names, accounts.notebooks.count as notebook_count
+ from system.accounts as accounts
+"""
+
+EXPLICIT_JOINS_QUERY_TEMPLATE = """
+ select accounts.id, tag_agg.tag_count, note_agg.note_col
+ from system.accounts as accounts
+ left join (
+ select account_id as account_id, count() as tag_count
+ from system._account_tagged_items
+ group by account_id
+ ) as tag_agg on tag_agg.account_id = accounts.id
+ left join (
+ select account_id as account_id, {note_expr} as note_col
+ from system._account_resource_notebooks
+ group by account_id
+ ) as note_agg on note_agg.account_id = accounts.id
+"""
+
+
+class TestFederatedJoinMerge(BaseTest):
+ def _print_select(self, select: str, merge_enabled: bool = True) -> str:
+ printed, _ = prepare_and_print_ast(
+ parse_select(select),
+ HogQLContext(
+ team=self.team,
+ user=self.user,
+ enable_select_queries=True,
+ modifiers=HogQLQueryModifiers(mergeFederatedAggregateJoins=merge_enabled),
+ ),
+ "clickhouse",
+ )
+ return printed
+
+ def test_sibling_aggregating_lazy_joins_merge(self):
+ printed = self._print_select(ACCOUNTS_LAZY_JOINS_QUERY)
+ self.assertIn(MERGED_ALIAS, printed)
+ self.assertIn("UNION ALL", printed)
+
+ def test_explicit_aggregating_joins_merge(self):
+ printed = self._print_select(EXPLICIT_JOINS_QUERY_TEMPLATE.format(note_expr="count()"))
+ self.assertIn(MERGED_ALIAS, printed)
+ self.assertIn("UNION ALL", printed)
+
+ @parameterized.expand(
+ [
+ (
+ "single_aggregating_join",
+ "select id, accounts.notebooks.count as notebook_count from system.accounts as accounts",
+ True,
+ ),
+ ("modifier_off", ACCOUNTS_LAZY_JOINS_QUERY, False),
+ # any(notebook_id) is a non-nullable non-count scalar: its join-miss default
+ # can't be told apart from a real value after the union, so it disqualifies
+ # its join and drops the candidate count below two.
+ (
+ "non_nullable_scalar_aggregate",
+ EXPLICIT_JOINS_QUERY_TEMPLATE.format(note_expr="any(notebook_id)"),
+ True,
+ ),
+ ]
+ )
+ def test_no_merge(self, _name: str, query: str, merge_enabled: bool):
+ printed = self._print_select(query, merge_enabled=merge_enabled)
+ self.assertNotIn(MERGED_ALIAS, printed)
+
+ def test_reserved_alias_already_taken_skips_merge(self):
+ # A user-authored join under the reserved alias must disable the merge for the
+ # select instead of colliding with the transform's generated join.
+ query = f"""
+ select accounts.id, tag_agg.tag_count, note_agg.note_col, {MERGED_ALIAS}.c
+ from system.accounts as accounts
+ left join (
+ select account_id as account_id, count() as tag_count
+ from system._account_tagged_items group by account_id
+ ) as tag_agg on tag_agg.account_id = accounts.id
+ left join (
+ select account_id as account_id, count() as note_col
+ from system._account_resource_notebooks group by account_id
+ ) as note_agg on note_agg.account_id = accounts.id
+ left join (
+ select account_id as account_id, count() as c
+ from system._account_tagged_items group by account_id
+ ) as {MERGED_ALIAS} on {MERGED_ALIAS}.account_id = accounts.id
+ """
+ printed = self._print_select(query)
+ self.assertNotIn("UNION ALL", printed)
+
+ def test_warehouse_join_columns_compile_alongside_aggregating_joins(self):
+ # Merging warehouse (s3) joins breaks compilation ("Can't access field on
+ # LazyJoinType"), so the transform must exclude them. Printing is enough to
+ # catch the regression, and no s3 read happens here.
+ credential = DataWarehouseCredential.objects.create(access_key="key", access_secret="secret", team=self.team)
+ DataWarehouseTable.objects.create(
+ name="account_list",
+ format=DataWarehouseTable.TableFormat.CSVWithNames,
+ team=self.team,
+ credential=credential,
+ url_pattern="http://localhost:19000/bucket/account_list/*.csv",
+ columns={
+ "external_id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "valid": True},
+ "total_mrr": {"hogql": "FloatDatabaseField", "clickhouse": "Nullable(Float64)", "valid": True},
+ },
+ )
+ DataWarehouseJoin.objects.create(
+ team=self.team,
+ source_table_name="system.accounts",
+ source_table_key="external_id",
+ joining_table_name="account_list",
+ joining_table_key="external_id",
+ field_name="account_list",
+ )
+
+ printed = self._print_select(
+ """
+ select id, accounts.tags.names as tag_names, accounts.notebooks.count as notebook_count,
+ accounts.account_list.total_mrr as mrr
+ from system.accounts as accounts
+ """
+ )
+ self.assertIn("account_list", printed)
diff --git a/posthog/schema.py b/posthog/schema.py
index c74f1b32b846..fcb4fda4769c 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -5167,6 +5167,13 @@ class HogQLQueryModifiers(BaseModel):
inlineCohortCalculation: InlineCohortCalculation | None = None
materializationMode: MaterializationMode | None = None
materializedColumnsOptimizationMode: MaterializedColumnsOptimizationMode | None = None
+ mergeFederatedAggregateJoins: bool | None = Field(
+ default=None,
+ description=(
+ "Merge sibling aggregating LEFT JOINs over federated Postgres tables into"
+ " one UNION ALL join, so their scans overlap"
+ ),
+ )
optimizeJoinedFilters: bool | None = None
optimizeProjections: bool | None = None
parserMode: ParserMode | None = Field(
diff --git a/products/customer_analytics/backend/facade/hogql.py b/products/customer_analytics/backend/facade/hogql.py
index 87fceb1ab2c5..d3a87388c557 100644
--- a/products/customer_analytics/backend/facade/hogql.py
+++ b/products/customer_analytics/backend/facade/hogql.py
@@ -90,21 +90,27 @@ account_resource_notebooks: _AccountScopedPostgresTable = _AccountScopedPostgres
)
-account_custom_property_values: _AccountScopedPostgresTable = _AccountScopedPostgresTable(
+account_custom_property_values: PostgresTable = PostgresTable(
name="_account_custom_property_values",
postgres_table_name="customer_analytics_custompropertyvalue",
+ # Per-account deny filters used to arrive via the account-subquery predicate; with the
+ # direct team guard they must be declared explicitly, filtering on the account FK.
+ access_scope="account",
+ access_control_id_field="account_id",
description="Internal federated table (PostgreSQL `customer_analytics_custompropertyvalue`) of custom property values per account; not for direct querying — use `system.accounts.custom_properties`.",
- # Scope through team-filtered accounts (as the other junction tables do) AND prune
- # soft-deleted rows, so superseded `value_*` data can't be read via direct selection
- # of this hidden backing table — matching the `NOT cpv.is_deleted` filter in the lazy join.
+ # Unlike the FK-only junction tables, this table has a real `team_id` column, so the
+ # framework's standard `team_id = X` guard scopes it, and as a plain column comparison it is
+ # pushed down into the federated PostgreSQL read, where the account-subquery predicate
+ # cannot be. Soft-deleted rows stay pruned so superseded `value_*` data can't be read via
+ # direct selection of this hidden backing table, matching the lazy join's filter.
predicates=[
- parse_expr("account_id IN (SELECT id FROM system.accounts)"),
# `NOT is_deleted` (not `is_deleted != true`): the predicate is pushed into the federated
# PostgreSQL query, where comparing a boolean column to an integer literal is a type error.
parse_expr("NOT is_deleted"),
],
fields={
"id": UUIDDatabaseField(name="id", description="Primary key of the custom property value row."),
+ "team_id": IntegerDatabaseField(name="team_id"),
"definition_id": UUIDDatabaseField(
name="definition_id", description="Custom property definition this value is for."
),
@@ -128,12 +134,15 @@ account_custom_property_values: _AccountScopedPostgresTable = _AccountScopedPost
)
-account_custom_property_values_history: _AccountScopedPostgresTable = _AccountScopedPostgresTable(
+account_custom_property_values_history: PostgresTable = PostgresTable(
name="_account_custom_property_values_history",
postgres_table_name="customer_analytics_custompropertyvalue",
+ access_scope="account",
+ access_control_id_field="account_id",
description="Internal federated table (PostgreSQL `customer_analytics_custompropertyvalue`) of every custom property value write per account, superseded rows included; not for direct querying — use `system.accounts.custom_properties_history`.",
fields={
"id": UUIDDatabaseField(name="id", description="Primary key of the custom property value row."),
+ "team_id": IntegerDatabaseField(name="team_id"),
"definition_id": UUIDDatabaseField(
name="definition_id", description="Custom property definition this value is for."
),
diff --git a/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py b/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py
index 850e1208a2be..f41063de3e46 100644
--- a/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/accounts_query_runner.py
@@ -1,6 +1,9 @@
+import posthoganalytics
+
from posthog.schema import AccountsQuery, AccountsQueryResponse, CachedAccountsQueryResponse
from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.errors import BaseHogQLError, ExposedHogQLError
from posthog.hogql.parser import parse_expr, parse_order_expr, parse_select
from posthog.hogql.query import execute_hogql_query
@@ -17,6 +20,13 @@ DEFAULT_COLUMNS = (NAME_COLUMN, "created_at")
DEFAULT_ORDER_BY = "created_at DESC"
+# The query is bound by federated Postgres scans (one per merged lazy-join branch), not
+# CPU; the cluster's effective thread cap keeps those branches from running wide, so ask
+# for enough threads that the scans overlap.
+PERF_QUERY_SETTINGS = HogQLGlobalSettings(max_threads=16)
+
+PERF_FLAG = "customer-analytics-accounts-perf"
+
def _normalize_order_clause(raw: str) -> str:
"""Allow Django-style `-col` shorthand alongside native HogQL `col DESC`."""
@@ -33,6 +43,10 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
+ self._perf_enabled = self._perf_flag_enabled()
+ if self._perf_enabled:
+ self.modifiers.mergeFederatedAggregateJoins = True
+
# Metrics-only callers (just aggregations, no `select`) skip column
# resolution. A combined query carries both `select` and `metrics`.
self._metrics_only = bool(self.query.metrics) and not self.query.select
@@ -59,6 +73,29 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
offset=self.query.offset,
)
+ def _perf_flag_enabled(self) -> bool:
+ # only_evaluate_locally keeps this flag check off the network: it runs on the query
+ # hot path, so an inconclusive local evaluation must mean "off", never an HTTP call.
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ PERF_FLAG,
+ str(self.team.uuid),
+ groups={
+ "organization": str(self.team.organization_id),
+ "project": str(self.team.pk),
+ },
+ group_properties={
+ "organization": {"id": str(self.team.organization_id)},
+ "project": {"id": str(self.team.pk)},
+ },
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ return False
+
def validate_query_runner_access(self, user: User) -> bool:
return UserAccessControl(user=user, team=self.team).assert_access_level_for_resource(
"customer_analytics", "viewer"
@@ -198,6 +235,7 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
user=self.user,
timings=self.timings,
modifiers=self.modifiers,
+ settings=PERF_QUERY_SETTINGS if self._perf_enabled else None,
)
name_index = self.columns.index(NAME_COLUMN)
@@ -243,6 +281,7 @@ class AccountsQueryRunner(AnalyticsQueryRunner[AccountsQueryResponse]):
user=self.user,
timings=self.timings,
modifiers=self.modifiers,
+ settings=PERF_QUERY_SETTINGS if self._perf_enabled else None,
)
def _metric_evaluation_error(self, metrics: list[str], error: Exception) -> ExposedHogQLError:
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
index c35ad91a25a9..e1c9a9d1f3c5 100644
--- a/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_query_runner.py
@@ -7,7 +7,7 @@ from django.utils import timezone
from parameterized import parameterized
-from posthog.schema import AccountsQuery, AccountsQueryResponse
+from posthog.schema import AccountsQuery, AccountsQueryResponse, HogQLQueryModifiers
from posthog.hogql.errors import ExposedHogQLError
@@ -624,3 +624,69 @@ class TestAccountsQueryRunner(ClickhouseTestMixin, NonAtomicBaseTest):
runner = AccountsQueryRunner(query=AccountsQuery(), team=self.team)
self.assertRaises(UserAccessControlError, runner.validate_query_runner_access, self.user)
+
+ def test_multiple_aggregating_joins_preserve_left_join_defaults(self):
+ # Selecting tags + notebooks + a custom property together merges the sibling
+ # federated joins into one UNION ALL join; an account with none of them must
+ # keep the LEFT JOIN defaults (0 notebooks, [] tags, empty property) through
+ # the merged re-aggregation.
+ tag = Tag.objects.create(name="billing", team=self.team)
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ full = create_account(team_id=self.team.id, name="Full")
+ full.tagged_items.create(tag=tag)
+ notebook = Notebook.objects.create(team=self.team, created_by=self.user)
+ ResourceNotebook.objects.create(account=full, notebook=notebook)
+ CustomPropertyValue.objects.unscoped().create(
+ team_id=self.team.id, account=full, definition=definition, value_str="enterprise"
+ )
+ empty = create_account(team_id=self.team.id, name="Empty")
+
+ runner = AccountsQueryRunner(
+ query=AccountsQuery(
+ select=[
+ "id",
+ "accounts.tags.names AS tag_names",
+ "accounts.notebooks.count AS notebook_count",
+ f"accounts.custom_properties.values.`{definition.id}` AS plan",
+ ]
+ ),
+ team=self.team,
+ user=self.user,
+ modifiers=HogQLQueryModifiers(mergeFederatedAggregateJoins=True),
+ )
+ response = runner.calculate()
+ rows = {str(row[runner.columns.index("id")]): row for row in response.results}
+ tags_idx = runner.columns.index("tag_names")
+ count_idx = runner.columns.index("notebook_count")
+ plan_idx = runner.columns.index("plan")
+
+ self.assertEqual(rows[str(full.id)][tags_idx], ["billing"])
+ self.assertEqual(rows[str(full.id)][count_idx], 1)
+ self.assertEqual(rows[str(full.id)][plan_idx], "enterprise")
+ self.assertEqual(rows[str(empty.id)][tags_idx], [])
+ self.assertEqual(rows[str(empty.id)][count_idx], 0)
+ self.assertFalse(rows[str(empty.id)][plan_idx])
+
+ def test_join_merge_requires_modifier(self):
+ # The merge transform must stay behind the modifier: without it the printed
+ # SQL keeps the original per-join shape. The modifier-on run guards against
+ # the query silently becoming ineligible for the merge.
+ from posthog.hogql.query import HogQLQueryExecutor
+
+ query = AccountsQuery(
+ select=["id", "accounts.tags.names AS tag_names", "accounts.notebooks.count AS notebook_count"]
+ )
+
+ def generate_sql(modifiers: HogQLQueryModifiers | None) -> str:
+ runner = AccountsQueryRunner(query=query, team=self.team, user=self.user, modifiers=modifiers)
+ sql, _context = HogQLQueryExecutor(
+ query=runner.to_query(),
+ team=self.team,
+ query_type="AccountsQuery",
+ user=self.user,
+ modifiers=runner.modifiers,
+ ).generate_clickhouse_sql()
+ return sql
+
+ self.assertNotIn("__merged_aggregates", generate_sql(None))
+ self.assertIn("__merged_aggregates", generate_sql(HogQLQueryModifiers(mergeFederatedAggregateJoins=True)))
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 9879c3def10e..efb1a0efb995 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1208,6 +1208,8 @@ export interface HogQLQueryModifiersApi {
inlineCohortCalculation?: InlineCohortCalculationApi | null
materializationMode?: MaterializationModeApi | null
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
+ /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
+ mergeFederatedAggregateJoins?: boolean | null
optimizeJoinedFilters?: boolean | null
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index cde54d9f2530..fe0f1a9037e8 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -495,6 +495,8 @@ export interface HogQLQueryModifiersApi {
inlineCohortCalculation?: InlineCohortCalculationApi | null
materializationMode?: MaterializationModeApi | null
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
+ /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
+ mergeFederatedAggregateJoins?: boolean | null
optimizeJoinedFilters?: boolean | null
optimizeProjections?: boolean | null
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 79766baf0303..30e9673f7979 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -656,6 +656,8 @@ export namespace Schemas {
inlineCohortCalculation?: InlineCohortCalculation | null;
materializationMode?: MaterializationMode | null;
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationMode | null;
+ /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
+ mergeFederatedAggregateJoins?: boolean | null;
optimizeJoinedFilters?: boolean | null;
optimizeProjections?: boolean | null;
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */