:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(endpoints): DuckLake endpoint execution — shadow-only (#65226)
Jovan Sakovic08224c707f6b
diff --git a/posthog/ducklake/client.py b/posthog/ducklake/client.pyindex a364b80b951a..6006b2bf303b 100644--- a/posthog/ducklake/client.py+++ b/posthog/ducklake/client.py@@ -1,5 +1,6 @@from __future__ import annotations+import timefrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any@@ -22,6 +23,9 @@ class DuckLakeQueryResult:results: list[list[Any]]sql: strhogql: str | None = None+ # connect_ms includes control-plane activation of a cold tenant; query_ms is the query alone.+ connect_ms: float | None = None+ query_ms: float | None = None@dataclass@@ -128,19 +132,25 @@ def execute_ducklake_query(assert sql is not Noneconninfo = make_duckgres_conninfo(team_id, organization_id=organization_id)+ _connect_start = time.monotonic()with psycopg.connect(conninfo) as conn:+ connect_ms = (time.monotonic() - _connect_start) * 1000_set_search_path(conn)with conn.cursor() as cur:+ _query_start = time.monotonic()cur.execute(sql, values or None)columns = [desc.name for desc in cur.description] if cur.description else []types = [str(desc.type_code) for desc in cur.description] if cur.description else []rows = cur.fetchall()+ query_ms = (time.monotonic() - _query_start) * 1000return DuckLakeQueryResult(columns=columns,types=types,results=[list(r) for r in rows],sql=sql,hogql=hogql_pretty,+ connect_ms=connect_ms,+ query_ms=query_ms,)diff --git a/products/endpoints/backend/metrics.py b/products/endpoints/backend/metrics.pyindex d049a7e5fa4c..428d09b28032 100644--- a/products/endpoints/backend/metrics.py+++ b/products/endpoints/backend/metrics.py@@ -30,11 +30,6 @@ ENDPOINT_MATERIALIZATION_EVENT_TOTAL = Counter(labelnames=["action", "status"],)-ENDPOINT_DUCKLAKE_FALLBACK_TOTAL = Counter(- "posthog_endpoint_ducklake_fallback_total",- "DuckLake executions that fell back to inline",-)-ENDPOINT_RATE_LIMITED_TOTAL = Counter("posthog_endpoint_rate_limited_total","Rate-limited endpoint requests",diff --git a/products/endpoints/backend/services/ducklake_shadow.py b/products/endpoints/backend/services/ducklake_shadow.pynew file mode 100644index 000000000000..1b854cc6b850--- /dev/null+++ b/products/endpoints/backend/services/ducklake_shadow.py@@ -0,0 +1,141 @@+import time+from typing import Any++from structlog import get_logger++from posthog.schema import EndpointRunRequest, HogQLQuery++from posthog.ducklake.client import execute_ducklake_query+from posthog.ducklake.common import get_duckgres_server_for_organization, is_dev_mode+from posthog.models import Team+from posthog.ph_client import ph_scoped_capture++from products.endpoints.backend.models import Endpoint, EndpointVersion+from products.endpoints.backend.services.strategies import strategy_for++logger = get_logger(__name__)++SHADOW_EVENT = "ducklake_endpoint_exec_shadow"+++def shadow_target_exists(team: Team) -> bool:+ # Local dev points at the dev duckgres config and has no provisioned DuckgresServer row.+ if is_dev_mode():+ return True+ return get_duckgres_server_for_organization(str(team.organization_id)) is not None+++def build_ducklake_hogql_query(+ endpoint: Endpoint,+ version: EndpointVersion,+ team: Team,+ data: EndpointRunRequest,+ *,+ limit: int | None = None,+ offset: int | None = None,+) -> HogQLQuery:+ """Build the HogQL an endpoint would run against DuckLake, matching the inline path's+ variable overrides and pagination so the shadow mirrors what ClickHouse executed."""+ strategy = strategy_for(endpoint, version, team)+ query = strategy.prepare_inline_query(version.query.copy())+ if limit is not None:+ query, _ = strategy.apply_pagination(query, limit, offset or 0)+ plan = strategy.build_inline_plan(query, data)++ hogql_query = HogQLQuery(query=query["query"], variables=query.get("variables"))+ if plan.variables_override and hogql_query.variables:+ for override in plan.variables_override:+ if hogql_query.variables.get(override.variableId):+ hogql_query.variables[override.variableId] = override+ return hogql_query+++def run_ducklake_shadow_comparison(+ *,+ team_id: int,+ endpoint_id: str,+ version_id: str,+ variables: dict[str, Any] | None,+ execution_type: str,+ clickhouse_cached: bool,+ clickhouse_ms: float,+ clickhouse_row_count: int | None,+ limit: int | None,+ offset: int | None,+) -> None:+ """Re-run an endpoint's HogQL against DuckLake and emit a comparison event. Runs in a+ Celery worker off the request path; must never raise into the caller."""+ try:+ team = Team.objects.get(pk=team_id)+ endpoint = Endpoint.objects.get(pk=endpoint_id, team_id=team_id)+ version = EndpointVersion.objects.get(pk=version_id, endpoint=endpoint)+ except (Team.DoesNotExist, Endpoint.DoesNotExist, EndpointVersion.DoesNotExist):+ logger.info(+ "ducklake_shadow_skip_missing_entity",+ team_id=team_id,+ endpoint_id=endpoint_id,+ version_id=version_id,+ )+ return++ if not shadow_target_exists(team):+ logger.info("ducklake_shadow_skip_no_server", team_id=team_id)+ return++ data = EndpointRunRequest(variables=variables)++ ducklake_ms: float | None = None+ ducklake_connect_ms: float | None = None+ ducklake_query_ms: float | None = None+ ducklake_row_count: int | None = None+ ducklake_error: str | None = None+ try:+ hogql_query = build_ducklake_hogql_query(endpoint, version, team, data, limit=limit, offset=offset)+ _start = time.monotonic()+ result = execute_ducklake_query(+ team_id,+ query=hogql_query,+ organization_id=str(team.organization_id),+ team=team,+ )+ ducklake_ms = (time.monotonic() - _start) * 1000+ ducklake_connect_ms = result.connect_ms+ ducklake_query_ms = result.query_ms+ ducklake_row_count = len(result.results)+ except Exception as e:+ ducklake_error = f"{type(e).__name__}: {e}"+ logger.warning(+ "ducklake_shadow_query_failed",+ endpoint_name=endpoint.name,+ team_id=team_id,+ error=ducklake_error,+ )++ row_count_match: bool | None = None+ if ducklake_row_count is not None and clickhouse_row_count is not None:+ row_count_match = ducklake_row_count == clickhouse_row_count++ with ph_scoped_capture() as capture:+ capture(+ distinct_id=str(team.uuid),+ event=SHADOW_EVENT,+ properties={+ "team_id": team_id,+ "organization_id": str(team.organization_id),+ "endpoint_name": endpoint.name,+ "endpoint_version": version.version,+ "query_kind": "hogql",+ "execution_type": execution_type,+ "clickhouse_cached": clickhouse_cached,+ "clickhouse_ms": clickhouse_ms,+ "ducklake_ms": ducklake_ms,+ "ducklake_connect_ms": ducklake_connect_ms,+ "ducklake_query_ms": ducklake_query_ms,+ "clickhouse_row_count": clickhouse_row_count,+ "ducklake_row_count": ducklake_row_count,+ "row_count_match": row_count_match,+ "ducklake_error": ducklake_error,+ "has_variables": bool(variables),+ },+ groups={"organization": str(team.organization_id), "project": str(team_id)},+ )diff --git a/products/endpoints/backend/services/execution.py b/products/endpoints/backend/services/execution.pyindex 55e682381620..59bcf3983a57 100644--- a/products/endpoints/backend/services/execution.py+++ b/products/endpoints/backend/services/execution.py@@ -14,6 +14,7 @@ import uuidfrom datetime import timedeltafrom typing import Literal, Union, cast+from django.conf import settingsfrom django.utils import timezoneimport structlog@@ -51,7 +52,7 @@ from posthog.clickhouse.query_tagging import (is_api_key_access_method,tag_queries,)-from posthog.ducklake.common import get_duckgres_server_for_organization+from posthog.ducklake.common import is_dev_modefrom posthog.errors import ExposedCHQueryErrorfrom posthog.event_usage import get_request_analytics_properties, report_user_actionfrom posthog.exceptions import (@@ -74,7 +75,6 @@ from products.endpoints.backend.logs import build_execution_message, log_endpoinfrom products.endpoints.backend.metrics import (ENDPOINT_CACHE_RESULT_TOTAL,ENDPOINT_CONCURRENCY_REJECTED_TOTAL,- ENDPOINT_DUCKLAKE_FALLBACK_TOTAL,ENDPOINT_EXECUTION_DURATION_SECONDS,ENDPOINT_EXECUTION_TOTAL,ENDPOINT_HOGQL_RESULT_ROWS,@@ -85,6 +85,7 @@ from products.endpoints.backend.metrics import (from products.endpoints.backend.models import Endpoint, EndpointVersionfrom products.endpoints.backend.services.pagination import EndpointPaginationfrom products.endpoints.backend.services.strategies import EndpointQueryStrategy, strategy_for+from products.endpoints.backend.tasks import shadow_compare_ducklake_executionfrom common.hogvm.python.utils import HogVMException@@ -92,7 +93,7 @@ logger = structlog.get_logger(__name__)LAST_EXECUTED_THROTTLE = timedelta(minutes=30)-ExecutionType = Literal["materialized", "materialized_fallback", "inline", "ducklake", "ducklake_fallback"]+ExecutionType = Literal["materialized", "materialized_fallback", "inline"]# Deterministic, customer-caused ClickHouse cost guardrails → stable client `code` + remediation.# Kept out of status="error" so they don't page on-call; surfaced as an actionable 400.@@ -386,38 +387,68 @@ class EndpointExecutionService(PydanticModelMixin):return True- def _should_use_ducklake(self, endpoint: Endpoint, version: EndpointVersion | None) -> bool:- if version is None:- return False- if version.query.get("kind") != "HogQLQuery":+ def _should_shadow_ducklake(self, endpoint: Endpoint, version: EndpointVersion | None) -> bool:+ # Flag is scoped to orgs with a duckgres server; the worker re-checks before querying.+ if version is None or version.query.get("kind") != "HogQLQuery":return False- ff_result = posthoganalytics.feature_enabled(- "endpoints-ducklake-execution",- str(self.team.uuid),- groups={- "organization": str(self.team.organization_id),- "project": str(self.team.id),- },- group_properties={- "organization": {"id": str(self.team.organization_id)},- "project": {"id": str(self.team.id)},- },- only_evaluate_locally=True,- send_feature_flag_events=False,- )- logger.info(- "Ducklake FF evaluation",- endpoint_name=endpoint.name,- ff_result=ff_result,+ # is_dev_mode() is also true under the test suite (USE_LOCAL_SETUP = TEST or ...); never shadow+ # there — it builds a userless HogQL database and runs eagerly under Celery, breaking unrelated runs.+ if is_dev_mode() and not settings.TEST:+ return True++ return bool(+ posthoganalytics.feature_enabled(+ "endpoints-ducklake-shadow-execution",+ str(self.team.uuid),+ groups={+ "organization": str(self.team.organization_id),+ "project": str(self.team.id),+ },+ group_properties={+ "organization": {"id": str(self.team.organization_id)},+ "project": {"id": str(self.team.id)},+ },+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ ))- if not ff_result:- return False- server = get_duckgres_server_for_organization(str(self.team.organization_id))- if server is None:- logger.info("Ducklake skip: no duckgres server", endpoint_name=endpoint.name, team_id=self.team.pk)- return server is not None+ def _maybe_shadow_ducklake(+ self,+ endpoint: Endpoint,+ data: EndpointRunRequest,+ version: EndpointVersion,+ *,+ execution_type: ExecutionType,+ clickhouse_ms: float,+ clickhouse_cached: bool,+ clickhouse_row_count: int | None,+ limit: int | None,+ offset: int | None,+ ) -> None:+ """Fire-and-forget DuckLake shadow for timing comparison; never affects the response."""+ # Only shadow what ClickHouse actually executed: an inline, non-cached run. Cache hits+ # and materialized reads have no comparable DuckLake query and would amplify cost.+ if execution_type != "inline" or clickhouse_cached:+ return+ if not self._should_shadow_ducklake(endpoint, version):+ return+ try:+ shadow_compare_ducklake_execution.delay(+ team_id=self.team.pk,+ endpoint_id=str(endpoint.id),+ version_id=str(version.id),+ variables=data.variables,+ execution_type=execution_type,+ clickhouse_cached=clickhouse_cached,+ clickhouse_ms=clickhouse_ms,+ clickhouse_row_count=clickhouse_row_count,+ limit=limit,+ offset=offset,+ )+ except Exception:+ logger.warning("Failed to dispatch DuckLake shadow comparison", endpoint_name=endpoint.name)# ------------------------------------------------------------------# Top-level entry point@@ -478,7 +509,9 @@ class EndpointExecutionService(PydanticModelMixin):error_label: str | None = None_start_time = time.monotonic()_duration = 0.0+ _ch_query_ms = 0.0+ _ch_query_start = time.monotonic()try:result: Response | None = Noneif use_materialized:@@ -494,20 +527,6 @@ class EndpointExecutionService(PydanticModelMixin):# series drift self-heal on the next materialization run.execution_type = "materialized_fallback"result = None- elif self._should_use_ducklake(endpoint, version_obj):- try:- result = self._execute_ducklake_endpoint(- endpoint, data, version_obj, version_obj.query.copy(), debug=debug- )- execution_type = "ducklake"- except Exception:- logger.warning(- "DuckLake execution failed, falling back to inline",- endpoint_name=endpoint.name,- )- ENDPOINT_DUCKLAKE_FALLBACK_TOTAL.inc()- execution_type = "ducklake_fallback"- result = Noneif result is None:result = self._execute_inline_endpoint(@@ -519,6 +538,8 @@ class EndpointExecutionService(PydanticModelMixin):limit=limit,offset=offset,)+ # Query-only wall-clock, to compare fairly with the DuckLake shadow.+ _ch_query_ms = (time.monotonic() - _ch_query_start) * 1000execution_status = "success"except (ExposedHogQLError, ExposedCHQueryError) as e:execution_status = "user_error"@@ -603,6 +624,18 @@ class EndpointExecutionService(PydanticModelMixin):)self._track_last_executed(endpoint, version_obj)+ self._maybe_shadow_ducklake(+ endpoint,+ data,+ version_obj,+ execution_type=execution_type,+ clickhouse_ms=_ch_query_ms,+ clickhouse_cached=cache_outcome == "hit",+ clickhouse_row_count=result_row_count,+ limit=limit,+ offset=offset,+ )+if isinstance(result.data, dict):result.data["name"] = endpoint.nameresult.data["execution_id"] = execution_id@@ -618,12 +651,10 @@ class EndpointExecutionService(PydanticModelMixin):result_row_count: int | None = Nonetry:if isinstance(result.data, dict):- # DuckLake bypasses the query result cache entirely — don't claim hit/miss for it.- if execution_type != "ducklake":- cache_outcome = "hit" if bool(result.data.get("is_cached")) else "miss"- ENDPOINT_CACHE_RESULT_TOTAL.labels(- execution_type=execution_type, query_kind=query_kind_metric, outcome=cache_outcome- ).inc()+ cache_outcome = "hit" if bool(result.data.get("is_cached")) else "miss"+ ENDPOINT_CACHE_RESULT_TOTAL.labels(+ execution_type=execution_type, query_kind=query_kind_metric, outcome=cache_outcome+ ).inc()results_value = result.data.get("results")if isinstance(results_value, list):@@ -906,60 +937,6 @@ class EndpointExecutionService(PydanticModelMixin):)raise- def _execute_ducklake_endpoint(- self,- endpoint: Endpoint,- data: EndpointRunRequest,- version: EndpointVersion,- query: dict,- debug: bool = False,- ) -> Response:- from posthog.ducklake.client import execute_ducklake_query-- try:- strategy = strategy_for(endpoint, version, self.team)- plan = strategy.build_inline_plan(query, data)-- hogql_query = HogQLQuery(query=query["query"], variables=query.get("variables"))- if plan.variables_override and hogql_query.variables:- for override in plan.variables_override:- if hogql_query.variables.get(override.variableId):- hogql_query.variables[override.variableId] = override-- result = execute_ducklake_query(- self.team.pk,- query=hogql_query,- organization_id=str(self.team.organization_id),- team=self.team,- )- response_data: dict = {- "results": result.results,- "columns": result.columns,- "types": result.types,- "hasMore": False,- "backend": "ducklake",- }- if debug:- response_data["query"] = query.get("query")- response_data["hogql"] = result.hogql- response_data["ducklake_sql"] = result.sql- return Response(response_data, status=status.HTTP_200_OK)- except Exception as e:- logger.exception(- "DuckLake endpoint execution failed",- endpoint_name=endpoint.name,- )- capture_exception(- e,- {- "product": Product.ENDPOINTS,- "team_id": self.team.pk,- "ducklake": True,- "endpoint_name": endpoint.name,- },- )- raise-# ------------------------------------------------------------------# Query service plumbing# ------------------------------------------------------------------diff --git a/products/endpoints/backend/tasks.py b/products/endpoints/backend/tasks.pyindex 456edf183200..de6f4e78ca74 100644--- a/products/endpoints/backend/tasks.py+++ b/products/endpoints/backend/tasks.py@@ -1,4 +1,5 @@from datetime import timedelta+from typing import Anyfrom django.utils import timezone@@ -9,12 +10,41 @@ from posthog.scoping_audit import skip_team_scope_auditfrom products.endpoints.backend.metrics import ENDPOINT_MATERIALIZATION_EVENT_TOTALfrom products.endpoints.backend.models import EndpointVersion+from products.endpoints.backend.services.ducklake_shadow import run_ducklake_shadow_comparisonlogger = get_logger(__name__)STALE_THRESHOLD_DAYS = 30+@shared_task(ignore_result=True)+@skip_team_scope_audit+def shadow_compare_ducklake_execution(+ team_id: int,+ endpoint_id: str,+ version_id: str,+ variables: dict[str, Any] | None,+ execution_type: str,+ clickhouse_cached: bool,+ clickhouse_ms: float,+ clickhouse_row_count: int | None,+ limit: int | None,+ offset: int | None,+) -> None:+ run_ducklake_shadow_comparison(+ team_id=team_id,+ endpoint_id=endpoint_id,+ version_id=version_id,+ variables=variables,+ execution_type=execution_type,+ clickhouse_cached=clickhouse_cached,+ clickhouse_ms=clickhouse_ms,+ clickhouse_row_count=clickhouse_row_count,+ limit=limit,+ offset=offset,+ )++@shared_task(ignore_result=True)@skip_team_scope_auditdef deactivate_stale_materializations() -> None:diff --git a/products/endpoints/backend/tests/test_endpoint_ducklake.py b/products/endpoints/backend/tests/test_endpoint_ducklake.pydeleted file mode 100644index dbd1d679cd93..000000000000--- a/products/endpoints/backend/tests/test_endpoint_ducklake.py+++ /dev/null@@ -1,182 +0,0 @@-import pytest-from posthog.test.base import APIBaseTest-from unittest import mock--from rest_framework import status--from products.endpoints.backend.services.execution import EndpointExecutionService-from products.endpoints.backend.tests.conftest import create_endpoint_with_version--pytestmark = [pytest.mark.django_db]---class TestShouldUseDuckLake(APIBaseTest):- """Test the routing decision for DuckLake vs ClickHouse."""-- def _make_service(self) -> EndpointExecutionService:- return EndpointExecutionService(self.team, mock.MagicMock())-- def test_non_hogql_query_returns_false(self):- endpoint = create_endpoint_with_version(- name="dl-test-insight",- team=self.team,- query={"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]},- created_by=self.user,- )- version = endpoint.get_version()- service = self._make_service()-- assert service._should_use_ducklake(endpoint, version) is False-- def test_none_version_returns_false(self):- endpoint = create_endpoint_with_version(- name="dl-test-none",- team=self.team,- query={"kind": "HogQLQuery", "query": "SELECT count() FROM events"},- created_by=self.user,- )- service = self._make_service()-- assert service._should_use_ducklake(endpoint, None) is False---class TestDuckLakeEndpointExecution(APIBaseTest):- """Integration tests for the full DuckLake execution path via the run() API."""-- def setUp(self):- super().setUp()- self.sync_workflow_patcher = mock.patch(- "products.data_warehouse.backend.data_load.saved_query_service.sync_saved_query_workflow"- )- self.sync_workflow_patcher.start()-- def tearDown(self):- self.sync_workflow_patcher.stop()- super().tearDown()-- @mock.patch("posthog.ducklake.client.execute_ducklake_query")- @mock.patch(- "products.endpoints.backend.services.execution.EndpointExecutionService._should_use_ducklake", return_value=True- )- def test_run_returns_ducklake_result(self, _mock_should, mock_execute):- from posthog.ducklake.client import DuckLakeQueryResult-- mock_execute.return_value = DuckLakeQueryResult(- columns=["event", "cnt"],- types=["25", "20"],- results=[["$pageview", 42], ["$pageleave", 7]],- sql="SELECT event, count(*) as cnt FROM events GROUP BY event",- hogql="SELECT event, count() AS cnt FROM events GROUP BY event",- )-- create_endpoint_with_version(- name="dl-run-test",- team=self.team,- query={"kind": "HogQLQuery", "query": "SELECT event, count() as cnt FROM events GROUP BY event"},- created_by=self.user,- )-- response = self.client.get(f"/api/environments/{self.team.id}/endpoints/dl-run-test/run/")-- assert response.status_code == status.HTTP_200_OK- data = response.json()- assert data["columns"] == ["event", "cnt"]- assert data["results"] == [["$pageview", 42], ["$pageleave", 7]]- assert data["hasMore"] is False- assert data["backend"] == "ducklake"- assert "ducklake_sql" not in data- assert "hogql" not in data- assert "query" not in data- mock_execute.assert_called_once()-- @mock.patch("posthog.ducklake.client.execute_ducklake_query")- @mock.patch(- "products.endpoints.backend.services.execution.EndpointExecutionService._should_use_ducklake", return_value=True- )- def test_run_with_debug_includes_sql_metadata(self, _mock_should, mock_execute):- from posthog.ducklake.client import DuckLakeQueryResult-- mock_execute.return_value = DuckLakeQueryResult(- columns=["cnt"],- types=["20"],- results=[[42]],- sql="SELECT count(*) as cnt FROM events",- hogql="SELECT count() AS cnt FROM events",- )-- create_endpoint_with_version(- name="dl-debug-test",- team=self.team,- query={"kind": "HogQLQuery", "query": "SELECT count() as cnt FROM events"},- created_by=self.user,- )-- response = self.client.post(- f"/api/environments/{self.team.id}/endpoints/dl-debug-test/run/",- data={"debug": True},- content_type="application/json",- )-- assert response.status_code == status.HTTP_200_OK- data = response.json()- assert data["backend"] == "ducklake"- assert data["query"] == "SELECT count() as cnt FROM events"- assert "hogql" in data- assert "ducklake_sql" in data-- @mock.patch("posthog.ducklake.client.execute_ducklake_query")- @mock.patch(- "products.endpoints.backend.services.execution.EndpointExecutionService._should_use_ducklake", return_value=True- )- def test_run_passes_overridden_variables_to_ducklake(self, _mock_should, mock_execute):- from posthog.ducklake.client import DuckLakeQueryResult-- mock_execute.return_value = DuckLakeQueryResult(columns=[], types=[], results=[], sql="", hogql=None)-- create_endpoint_with_version(- name="dl-vars-test",- team=self.team,- query={- "kind": "HogQLQuery",- "query": "SELECT event FROM events WHERE event = {variables.event_name}",- "variables": {- "var-1": {"variableId": "var-1", "code_name": "event_name", "value": "$pageview"},- },- },- created_by=self.user,- )-- response = self.client.post(- f"/api/environments/{self.team.id}/endpoints/dl-vars-test/run/",- data={"variables": {"event_name": "purchase"}},- content_type="application/json",- )-- assert response.status_code == status.HTTP_200_OK- passed_query = mock_execute.call_args.kwargs["query"]- assert passed_query.variables["var-1"].value == "purchase"-- @mock.patch("posthog.ducklake.client.execute_ducklake_query")- @mock.patch(- "products.endpoints.backend.services.execution.EndpointExecutionService._should_use_ducklake", return_value=True- )- def test_run_ducklake_error_falls_back_to_inline(self, _mock_should, mock_execute):- mock_execute.side_effect = Exception("Duckgres connection refused")-- create_endpoint_with_version(- name="dl-error-test",- team=self.team,- query={"kind": "HogQLQuery", "query": "SELECT count() FROM events"},- created_by=self.user,- )-- with mock.patch(- "products.endpoints.backend.services.execution.EndpointExecutionService._execute_inline_endpoint"- ) as mock_inline:- from rest_framework.response import Response-- mock_inline.return_value = Response({"results": [], "columns": [], "hasMore": False}, status=200)- response = self.client.get(f"/api/environments/{self.team.id}/endpoints/dl-error-test/run/")- assert response.status_code == status.HTTP_200_OK- mock_execute.assert_called_once()- mock_inline.assert_called_once()diff --git a/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py b/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.pynew file mode 100644index 000000000000..e470ab12d5fa--- /dev/null+++ b/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py@@ -0,0 +1,323 @@+import pytest+from posthog.test.base import APIBaseTest+from unittest import mock++from rest_framework import status+from rest_framework.response import Response+from rest_framework.test import APIRequestFactory++from posthog.ducklake.client import DuckLakeQueryResult++from products.endpoints.backend.services import ducklake_shadow+from products.endpoints.backend.services.execution import EndpointExecutionService+from products.endpoints.backend.tests.conftest import create_endpoint_with_version++pytestmark = [pytest.mark.django_db]++HOGQL_QUERY = {"kind": "HogQLQuery", "query": "SELECT count() as cnt FROM events"}+TRENDS_QUERY = {"kind": "TrendsQuery", "series": [{"kind": "EventsNode", "event": "$pageview"}]}+++class TestShadowDispatch(APIBaseTest):+ """The dispatch decision in EndpointExecutionService._maybe_shadow_ducklake."""++ def _inline_response(self) -> Response:+ return Response(+ {"results": [[1]], "columns": ["cnt"], "hasMore": False, "is_cached": False},+ status=status.HTTP_200_OK,+ )++ @mock.patch("products.endpoints.backend.services.execution.shadow_compare_ducklake_execution")+ @mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._should_shadow_ducklake",+ return_value=True,+ )+ def test_dispatches_shadow_for_inline_execution(self, _mock_should, mock_task):+ endpoint = create_endpoint_with_version(+ name="shadow-inline", team=self.team, query=HOGQL_QUERY, created_by=self.user+ )+ version = endpoint.get_version()++ with mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._execute_inline_endpoint",+ return_value=self._inline_response(),+ ):+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/shadow-inline/run/")++ assert response.status_code == status.HTTP_200_OK+ mock_task.delay.assert_called_once()+ kwargs = mock_task.delay.call_args.kwargs+ assert kwargs["team_id"] == self.team.pk+ assert kwargs["endpoint_id"] == str(endpoint.id)+ assert kwargs["version_id"] == str(version.id)+ assert kwargs["execution_type"] == "inline"+ assert kwargs["clickhouse_cached"] is False+ assert kwargs["clickhouse_row_count"] == 1+ assert isinstance(kwargs["clickhouse_ms"], float)+ assert kwargs["limit"] is None+ assert kwargs["offset"] is None++ @mock.patch("products.endpoints.backend.services.execution.shadow_compare_ducklake_execution")+ @mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._should_shadow_ducklake",+ return_value=True,+ )+ def test_no_dispatch_on_cache_hit(self, _mock_should, mock_task):+ create_endpoint_with_version(name="shadow-cached", team=self.team, query=HOGQL_QUERY, created_by=self.user)+ cached = Response(+ {"results": [[1]], "columns": ["cnt"], "hasMore": False, "is_cached": True},+ status=status.HTTP_200_OK,+ )++ with mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._execute_inline_endpoint",+ return_value=cached,+ ):+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/shadow-cached/run/")++ assert response.status_code == status.HTTP_200_OK+ mock_task.delay.assert_not_called()++ @mock.patch("products.endpoints.backend.services.execution.shadow_compare_ducklake_execution")+ @mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._should_shadow_ducklake",+ return_value=True,+ )+ def test_dispatch_propagates_pagination(self, _mock_should, mock_task):+ create_endpoint_with_version(name="shadow-paged", team=self.team, query=HOGQL_QUERY, created_by=self.user)++ with mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._execute_inline_endpoint",+ return_value=self._inline_response(),+ ):+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/shadow-paged/run/",+ data={"limit": 5, "offset": 2},+ content_type="application/json",+ )++ assert response.status_code == status.HTTP_200_OK+ kwargs = mock_task.delay.call_args.kwargs+ assert kwargs["limit"] == 5+ assert kwargs["offset"] == 2++ @mock.patch("products.endpoints.backend.services.execution.shadow_compare_ducklake_execution")+ @mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._should_shadow_ducklake",+ return_value=False,+ )+ def test_no_dispatch_when_flag_off(self, _mock_should, mock_task):+ create_endpoint_with_version(name="shadow-off", team=self.team, query=HOGQL_QUERY, created_by=self.user)++ with mock.patch(+ "products.endpoints.backend.services.execution.EndpointExecutionService._execute_inline_endpoint",+ return_value=self._inline_response(),+ ):+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/shadow-off/run/")++ assert response.status_code == status.HTTP_200_OK+ mock_task.delay.assert_not_called()+++class TestShadowComparison(APIBaseTest):+ """The worker-side comparison in run_ducklake_shadow_comparison."""++ def _capture_events(self) -> list[dict]:+ captured: list[dict] = []+ cm = mock.MagicMock()+ cm.__enter__.return_value = lambda **kw: captured.append(kw)+ cm.__exit__.return_value = False+ self._cm_patch = mock.patch.object(ducklake_shadow, "ph_scoped_capture", return_value=cm)+ self._cm_patch.start()+ self.addCleanup(self._cm_patch.stop)+ server_patch = mock.patch.object(+ ducklake_shadow, "get_duckgres_server_for_organization", return_value=mock.MagicMock()+ )+ server_patch.start()+ self.addCleanup(server_patch.stop)+ return captured++ def test_emits_comparison_event_with_both_timings(self):+ endpoint = create_endpoint_with_version(name="cmp-ok", team=self.team, query=HOGQL_QUERY, created_by=self.user)+ version = endpoint.get_version()+ captured = self._capture_events()++ with mock.patch.object(+ ducklake_shadow,+ "execute_ducklake_query",+ return_value=DuckLakeQueryResult(+ columns=["cnt"], types=["20"], results=[[1]], sql="", hogql=None, connect_ms=8.0, query_ms=4.0+ ),+ ):+ ducklake_shadow.run_ducklake_shadow_comparison(+ team_id=self.team.pk,+ endpoint_id=str(endpoint.id),+ version_id=str(version.id),+ variables=None,+ execution_type="inline",+ clickhouse_cached=False,+ clickhouse_ms=12.5,+ clickhouse_row_count=1,+ limit=None,+ offset=None,+ )++ assert len(captured) == 1+ assert captured[0]["event"] == ducklake_shadow.SHADOW_EVENT+ props = captured[0]["properties"]+ assert props["clickhouse_ms"] == 12.5+ assert props["ducklake_ms"] is not None+ assert props["ducklake_connect_ms"] == 8.0+ assert props["ducklake_query_ms"] == 4.0+ assert props["clickhouse_row_count"] == 1+ assert props["ducklake_row_count"] == 1+ assert props["row_count_match"] is True+ assert props["ducklake_error"] is None+ assert props["execution_type"] == "inline"++ def test_emits_event_with_error_when_ducklake_fails(self):+ endpoint = create_endpoint_with_version(name="cmp-err", team=self.team, query=HOGQL_QUERY, created_by=self.user)+ version = endpoint.get_version()+ captured = self._capture_events()++ with mock.patch.object(+ ducklake_shadow, "execute_ducklake_query", side_effect=Exception("duckgres connection refused")+ ):+ ducklake_shadow.run_ducklake_shadow_comparison(+ team_id=self.team.pk,+ endpoint_id=str(endpoint.id),+ version_id=str(version.id),+ variables=None,+ execution_type="inline",+ clickhouse_cached=False,+ clickhouse_ms=12.5,+ clickhouse_row_count=1,+ limit=None,+ offset=None,+ )++ assert len(captured) == 1+ props = captured[0]["properties"]+ assert props["ducklake_ms"] is None+ assert props["ducklake_row_count"] is None+ assert props["row_count_match"] is None+ assert "duckgres connection refused" in props["ducklake_error"]++ def test_missing_entity_is_noop(self):+ captured = self._capture_events()++ ducklake_shadow.run_ducklake_shadow_comparison(+ team_id=self.team.pk,+ endpoint_id="00000000-0000-0000-0000-000000000000",+ version_id="00000000-0000-0000-0000-000000000000",+ variables=None,+ execution_type="inline",+ clickhouse_cached=False,+ clickhouse_ms=12.5,+ clickhouse_row_count=1,+ limit=None,+ offset=None,+ )++ assert captured == []++ def test_no_duckgres_server_is_noop_in_prod(self):+ endpoint = create_endpoint_with_version(+ name="cmp-noserver", team=self.team, query=HOGQL_QUERY, created_by=self.user+ )+ version = endpoint.get_version()+ captured = self._capture_events()++ with (+ mock.patch.object(ducklake_shadow, "is_dev_mode", return_value=False),+ mock.patch.object(ducklake_shadow, "get_duckgres_server_for_organization", return_value=None),+ ):+ ducklake_shadow.run_ducklake_shadow_comparison(+ team_id=self.team.pk,+ endpoint_id=str(endpoint.id),+ version_id=str(version.id),+ variables=None,+ execution_type="inline",+ clickhouse_cached=False,+ clickhouse_ms=12.5,+ clickhouse_row_count=1,+ limit=None,+ offset=None,+ )++ assert captured == []++ def test_dev_mode_shadows_without_provisioned_server(self):+ endpoint = create_endpoint_with_version(name="cmp-dev", team=self.team, query=HOGQL_QUERY, created_by=self.user)+ version = endpoint.get_version()+ captured = self._capture_events()++ with (+ mock.patch.object(ducklake_shadow, "is_dev_mode", return_value=True),+ mock.patch.object(ducklake_shadow, "get_duckgres_server_for_organization", return_value=None),+ mock.patch.object(+ ducklake_shadow,+ "execute_ducklake_query",+ return_value=DuckLakeQueryResult(columns=["cnt"], types=["20"], results=[[1]], sql="", hogql=None),+ ),+ ):+ ducklake_shadow.run_ducklake_shadow_comparison(+ team_id=self.team.pk,+ endpoint_id=str(endpoint.id),+ version_id=str(version.id),+ variables=None,+ execution_type="inline",+ clickhouse_cached=False,+ clickhouse_ms=12.5,+ clickhouse_row_count=1,+ limit=None,+ offset=None,+ )++ assert len(captured) == 1+++class TestShouldShadowDucklake(APIBaseTest):+ """The real gating in EndpointExecutionService._should_shadow_ducklake (unmocked)."""++ def _service(self) -> EndpointExecutionService:+ request = APIRequestFactory().get("/")+ return EndpointExecutionService(team=self.team, request=request)++ def test_does_not_shadow_during_test_suite(self):+ # is_dev_mode() is True under the test suite (USE_LOCAL_SETUP = TEST or ...), but the shadow+ # must not fire during tests: it builds a userless HogQL database and runs eagerly under Celery,+ # which trips access-control assertions on unrelated runs (e.g. PSAK system-table gating).+ endpoint = create_endpoint_with_version(+ name="should-shadow-test", team=self.team, query=HOGQL_QUERY, created_by=self.user+ )+ assert self._service()._should_shadow_ducklake(endpoint, endpoint.get_version()) is False++ @mock.patch("products.endpoints.backend.services.execution.is_dev_mode", return_value=True)+ def test_shadows_in_local_dev(self, _mock_dev):+ endpoint = create_endpoint_with_version(+ name="should-shadow-dev", team=self.team, query=HOGQL_QUERY, created_by=self.user+ )+ with self.settings(TEST=False):+ assert self._service()._should_shadow_ducklake(endpoint, endpoint.get_version()) is True++ @mock.patch("products.endpoints.backend.services.execution.is_dev_mode", return_value=True)+ def test_no_shadow_for_non_hogql_query(self, _mock_dev):+ endpoint = create_endpoint_with_version(+ name="should-shadow-trends", team=self.team, query=TRENDS_QUERY, created_by=self.user+ )+ with self.settings(TEST=False):+ assert self._service()._should_shadow_ducklake(endpoint, endpoint.get_version()) is False++ @mock.patch("products.endpoints.backend.services.execution.is_dev_mode", return_value=False)+ @mock.patch("products.endpoints.backend.services.execution.posthoganalytics.feature_enabled")+ def test_shadows_in_prod_when_flag_enabled(self, mock_flag, _mock_dev):+ endpoint = create_endpoint_with_version(+ name="should-shadow-flag", team=self.team, query=HOGQL_QUERY, created_by=self.user+ )+ version = endpoint.get_version()+ with self.settings(TEST=False):+ mock_flag.return_value = True+ assert self._service()._should_shadow_ducklake(endpoint, version) is True+ mock_flag.return_value = False+ assert self._service()._should_shadow_ducklake(endpoint, version) is Falsediff --git a/products/endpoints/backend/tests/test_endpoint_logs.py b/products/endpoints/backend/tests/test_endpoint_logs.pyindex 4880e9eb322b..c789620e0953 100644--- a/products/endpoints/backend/tests/test_endpoint_logs.py+++ b/products/endpoints/backend/tests/test_endpoint_logs.py@@ -40,8 +40,8 @@ class TestBuildExecutionMessage(SimpleTestCase):),("success_partial_tokens_omitted",- {"succeeded": True, "execution_type": "ducklake", "version": 1},- "Endpoint executed · path=ducklake version=1",+ {"succeeded": True, "execution_type": "inline", "version": 1},+ "Endpoint executed · path=inline version=1",),])