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.

fix(ducklake): pass HogQL access context (#66403)

Alex Lider782c116ee2fb
diff --git a/posthog/ducklake/client.py b/posthog/ducklake/client.py
index bc70eb3660ee..2d558446ce2c 100644
--- a/posthog/ducklake/client.py
+++ b/posthog/ducklake/client.py
@@ -14,6 +14,7 @@ from posthog.ducklake.table_binding import bind_tables_to_ducklake
if TYPE_CHECKING:
from posthog.schema import HogQLQuery
+ from posthog.models import User
from posthog.models.team.team import Team
@@ -72,7 +73,12 @@ def _set_search_path(conn: psycopg.Connection[Any], extra_schemas: list[str] | N
def compile_hogql_to_ducklake_sql(
- team_id: int, query: HogQLQuery, *, team: Team | None = None
+ team_id: int,
+ query: HogQLQuery,
+ *,
+ team: Team | None = None,
+ user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
) -> tuple[str, dict[str, object], str]:
"""Compile a HogQLQuery to DuckDB-dialect SQL for DuckLake.
@@ -95,14 +101,29 @@ def compile_hogql_to_ducklake_sql(
parsed = replace_variables(parsed, list(query.variables.values()), team)
# Build the database up front so warehouse tables can be bound from the ClickHouse
# S3 table function to their DuckLake-materialized tables before printing.
- database = Database.create_for(team_id)
+ database = Database.create_for(
+ team_id,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
bind_tables_to_ducklake(database, team_id)
# Separate context for the DuckDB print — the HogQL round-trip below shouldn't
# contribute to ``postgres_context.values``.
- postgres_context = HogQLContext(team_id=team_id, enable_select_queries=True, database=database)
+ postgres_context = HogQLContext(
+ team_id=team_id,
+ user=user,
+ enable_select_queries=True,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ database=database,
+ )
postgres_sql, _ = prepare_and_print_ast(parsed, postgres_context, dialect="duckdb")
- hogql_context = HogQLContext(team_id=team_id, enable_select_queries=True)
+ hogql_context = HogQLContext(
+ team_id=team_id,
+ user=user,
+ enable_select_queries=True,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
hogql_pretty, _ = prepare_and_print_ast(parsed, hogql_context, dialect="hogql")
return postgres_sql, dict(postgres_context.values), hogql_pretty
@@ -115,6 +136,8 @@ def execute_ducklake_query(
query: HogQLQuery | None = None,
organization_id: str | None = None,
team: Team | None = None,
+ user: User | None = None,
+ bypass_warehouse_access_control: bool = False,
) -> DuckLakeQueryResult:
"""Execute a query against a team's duckgres server.
@@ -123,7 +146,10 @@ def execute_ducklake_query(
Pass organization_id to skip the Team→Organization lookup when org
context is already available from the caller. Pass team to skip the
- Team lookup used for variable substitution.
+ Team lookup used for variable substitution. Pass user so HogQL compilation
+ resolves data warehouse access control the same way as normal query execution.
+ Set bypass_warehouse_access_control only from trusted internal callers that
+ must compile without a user, such as materialization.
"""
if sql and query:
raise ValueError("Provide either sql or query, not both")
@@ -133,7 +159,13 @@ def execute_ducklake_query(
hogql_pretty: str | None = None
values: dict[str, object] = {}
if query:
- sql, values, hogql_pretty = compile_hogql_to_ducklake_sql(team_id, query, team=team)
+ sql, values, hogql_pretty = compile_hogql_to_ducklake_sql(
+ team_id,
+ query,
+ team=team,
+ user=user,
+ bypass_warehouse_access_control=bypass_warehouse_access_control,
+ )
assert sql is not None
diff --git a/posthog/ducklake/test_client.py b/posthog/ducklake/test_client.py
index d697410779a2..43684eab31d3 100644
--- a/posthog/ducklake/test_client.py
+++ b/posthog/ducklake/test_client.py
@@ -121,6 +121,20 @@ class TestDuckLakeModelRedirect:
assert duckgres_data_imports_table_name(schema) in postgres_sql
+class TestDuckgresShadowCompilation:
+ @mock.patch("posthog.ducklake.client.compile_hogql_to_ducklake_sql")
+ def test_materialization_compile_bypasses_warehouse_access_control(self, mock_compile):
+ from posthog.temporal.data_modeling.activities.materialize_view_duckgres import _compile_hogql_to_postgres_sql
+
+ mock_compile.return_value = ("SELECT * FROM source", {}, "SELECT * FROM source")
+
+ _compile_hogql_to_postgres_sql("SELECT * FROM source", 1)
+
+ query = mock_compile.call_args.args[1]
+ assert query.query == "SELECT * FROM source"
+ assert mock_compile.call_args.kwargs == {"bypass_warehouse_access_control": True}
+
+
class TestExecuteDuckLakeQuery:
def test_rejects_both_sql_and_query(self):
with pytest.raises(ValueError, match="not both"):
@@ -172,7 +186,7 @@ class TestExecuteDuckLakeQuery:
query = HogQLQuery(query="SELECT count() FROM events")
result = execute_ducklake_query(1, query=query)
- mock_compile.assert_called_once_with(1, query, team=None)
+ mock_compile.assert_called_once_with(1, query, team=None, user=None, bypass_warehouse_access_control=False)
assert result.sql == "SELECT count(*) FROM events"
assert result.hogql == "SELECT count() FROM events"
assert result.results == [[42]]
diff --git a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
index 42cfcc6239ac..832e8f114858 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
@@ -85,7 +85,13 @@ def _compile_hogql_to_postgres_sql(hogql_query: str, team_id: int) -> tuple[str,
from posthog.ducklake.client import compile_hogql_to_ducklake_sql
- postgres_sql, values, _ = compile_hogql_to_ducklake_sql(team_id, HogQLQuery(query=hogql_query))
+ postgres_sql, values, _ = compile_hogql_to_ducklake_sql(
+ team_id,
+ HogQLQuery(query=hogql_query),
+ # Userless shadow materialization; mirror ClickHouse materialization so the
+ # model query can resolve its warehouse source tables/views.
+ bypass_warehouse_access_control=True,
+ )
return postgres_sql, values
diff --git a/products/endpoints/backend/services/ducklake_shadow.py b/products/endpoints/backend/services/ducklake_shadow.py
index 1b854cc6b850..62bf7a017f5b 100644
--- a/products/endpoints/backend/services/ducklake_shadow.py
+++ b/products/endpoints/backend/services/ducklake_shadow.py
@@ -97,6 +97,8 @@ def run_ducklake_shadow_comparison(
query=hogql_query,
organization_id=str(team.organization_id),
team=team,
+ # Shadow comparisons run off-request after the endpoint query already executed.
+ bypass_warehouse_access_control=True,
)
ducklake_ms = (time.monotonic() - _start) * 1000
ducklake_connect_ms = result.connect_ms
diff --git a/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py b/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py
index e470ab12d5fa..737598ba9220 100644
--- a/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py
+++ b/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py
@@ -148,7 +148,7 @@ class TestShadowComparison(APIBaseTest):
return_value=DuckLakeQueryResult(
columns=["cnt"], types=["20"], results=[[1]], sql="", hogql=None, connect_ms=8.0, query_ms=4.0
),
- ):
+ ) as mock_execute:
ducklake_shadow.run_ducklake_shadow_comparison(
team_id=self.team.pk,
endpoint_id=str(endpoint.id),
@@ -162,6 +162,7 @@ class TestShadowComparison(APIBaseTest):
offset=None,
)
+ assert mock_execute.call_args.kwargs["bypass_warehouse_access_control"] is True
assert len(captured) == 1
assert captured[0]["event"] == ducklake_shadow.SHADOW_EVENT
props = captured[0]["properties"]