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(endpoints): isolate product behind facade and canonical layout (#67558)

Jovan Sakovic9f96a6d7ddbe
diff --git a/posthog/demo/products/hedgebox/matrix.py b/posthog/demo/products/hedgebox/matrix.py
index 196edb026595..54c863a37e15 100644
--- a/posthog/demo/products/hedgebox/matrix.py
+++ b/posthog/demo/products/hedgebox/matrix.py
@@ -61,7 +61,7 @@ from products.cohorts.backend.models.cohort import Cohort
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.data_tools.backend.models.join import DataWarehouseJoin
-from products.endpoints.backend.models import Endpoint, EndpointVersion
+from products.endpoints.backend.facade.models import Endpoint, EndpointVersion
from products.error_tracking.backend.models import (
ErrorTrackingIssue,
ErrorTrackingIssueFingerprintV2,
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 9372c0a49613..3105c2666ab9 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -38,7 +38,7 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
from products.early_access_features.backend.models import EarlyAccessFeature
-from products.endpoints.backend.models import Endpoint, EndpointVersion
+from products.endpoints.backend.facade.models import Endpoint, EndpointVersion
from products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingSymbolSet
from products.experiments.backend.models.experiment import Experiment
from products.exports.backend.models.exported_asset import ExportedAsset
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 27ad81bab4e8..ca6e5eaa6b55 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -81,7 +81,7 @@ from products.conversations.backend.tasks import (
)
from products.data_modeling.backend.facade.tasks import cleanup_expired_test_saved_queries
from products.data_warehouse.backend.facade.tasks import send_external_data_failure_digest_catchup
-from products.endpoints.backend.tasks import deactivate_stale_materializations
+from products.endpoints.backend.facade.tasks import deactivate_stale_materializations
from products.feature_flags.backend.tasks import (
cleanup_stale_flag_definitions_expiry_tracking_task,
cleanup_stale_flags_expiry_tracking_task,
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.py
index 1545e5172a2d..40a958444860 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view.py
@@ -33,7 +33,7 @@ from posthog.temporal.common.logger import get_logger
from products.data_modeling.backend.facade.modeling import bounded_resolver_factory_for_view
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery, Node, NodeType
from products.data_warehouse.backend.facade.api import ensure_bucket_exists, get_s3_client
-from products.endpoints.backend.services.materialization import prepare_executable_query
+from products.endpoints.backend.facade.temporal import prepare_executable_query
LOGGER = get_logger(__name__)
diff --git a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
index 6e8b81a65b77..a5b0746c6ebb 100644
--- a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
+++ b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py
@@ -20,7 +20,7 @@ from products.data_modeling.backend.facade.models import (
Node,
NodeType,
)
-from products.endpoints.backend.services.materialization import prepare_executable_query
+from products.endpoints.backend.facade.temporal import prepare_executable_query
LOGGER = get_logger(__name__)
diff --git a/posthog/temporal/data_modeling/run_workflow.py b/posthog/temporal/data_modeling/run_workflow.py
index 7a277f5206c5..fbf9d494f653 100644
--- a/posthog/temporal/data_modeling/run_workflow.py
+++ b/posthog/temporal/data_modeling/run_workflow.py
@@ -73,8 +73,10 @@ from products.data_warehouse.backend.facade.api import (
ensure_bucket_exists,
get_s3_client,
)
-from products.endpoints.backend.rate_limit import update_materialization_ready_for_saved_query
-from products.endpoints.backend.services.materialization import prepare_executable_query
+from products.endpoints.backend.facade.temporal import (
+ prepare_executable_query,
+ update_materialization_ready_for_saved_query,
+)
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
from products.warehouse_sources.backend.facade.temporal import prepare_s3_files_for_querying
diff --git a/products/endpoints/backend/services/__init__.py b/products/endpoints/backend/facade/__init__.py
similarity index 100%
rename from products/endpoints/backend/services/__init__.py
rename to products/endpoints/backend/facade/__init__.py
diff --git a/products/endpoints/backend/facade/api.py b/products/endpoints/backend/facade/api.py
new file mode 100644
index 000000000000..f33c598261f8
--- /dev/null
+++ b/products/endpoints/backend/facade/api.py
@@ -0,0 +1,74 @@
+"""
+Facade API for endpoints.
+
+This is the ONLY module (with its facade siblings) other apps are allowed
+to import.
+
+Responsibilities:
+- Call internal logic and models
+- Convert Django models to contracts before returning
+- Remain thin and stable
+
+Do NOT:
+- Implement business logic here
+- Import DRF, serializers, or HTTP concerns
+- Return ORM instances or QuerySets
+
+Wiring that core registers crosses the boundary through the dedicated
+submodules instead: ``facade.tasks`` (celery beat), ``facade.temporal``
+(data-modeling workflow hooks), ``facade.models`` (model-class consumers).
+"""
+
+from products.endpoints.backend.models import Endpoint, EndpointVersion
+
+from . import contracts
+
+
+def _to_endpoint_info(endpoint: Endpoint) -> contracts.EndpointInfo:
+ return contracts.EndpointInfo(
+ id=endpoint.id,
+ team_id=endpoint.team_id,
+ name=endpoint.name,
+ is_active=endpoint.is_active,
+ current_version=endpoint.current_version,
+ derived_from_insight=endpoint.derived_from_insight,
+ created_at=endpoint.created_at,
+ updated_at=endpoint.updated_at,
+ last_executed_at=endpoint.last_executed_at,
+ )
+
+
+def _to_version_info(version: EndpointVersion) -> contracts.EndpointVersionInfo:
+ return contracts.EndpointVersionInfo(
+ id=version.id,
+ endpoint_id=version.endpoint_id,
+ version=version.version,
+ query=version.query,
+ description=version.description,
+ data_freshness_seconds=version.data_freshness_seconds,
+ is_active=version.is_active,
+ is_materialized=version.is_materialized,
+ created_at=version.created_at,
+ last_executed_at=version.last_executed_at,
+ )
+
+
+def list_endpoints(team_id: int) -> list[contracts.EndpointInfo]:
+ endpoints = Endpoint.objects.filter(team_id=team_id, deleted=False).order_by("name")
+ return [_to_endpoint_info(e) for e in endpoints]
+
+
+def get_endpoint(team_id: int, name: str) -> contracts.EndpointInfo | None:
+ endpoint = Endpoint.objects.filter(team_id=team_id, name=name, deleted=False).first()
+ return _to_endpoint_info(endpoint) if endpoint is not None else None
+
+
+def get_endpoint_version(team_id: int, name: str, version: int | None = None) -> contracts.EndpointVersionInfo | None:
+ """Get a specific version's snapshot, or the current version when ``version`` is None."""
+ endpoint = Endpoint.objects.filter(team_id=team_id, name=name, deleted=False).first()
+ if endpoint is None:
+ return None
+ try:
+ return _to_version_info(endpoint.get_version(version))
+ except EndpointVersion.DoesNotExist:
+ return None
diff --git a/products/endpoints/backend/facade/contracts.py b/products/endpoints/backend/facade/contracts.py
new file mode 100644
index 000000000000..e14c0e933363
--- /dev/null
+++ b/products/endpoints/backend/facade/contracts.py
@@ -0,0 +1,46 @@
+"""
+Contract types for endpoints.
+
+Stable, framework-free frozen dataclasses that define what this product
+exposes to the rest of the codebase. No Django imports.
+
+Pydantic dataclasses (not stdlib) so structural mistakes from mappers or
+internal callers surface at the facade boundary with a ValidationError
+instead of producing a malformed payload downstream.
+"""
+
+from datetime import datetime
+from uuid import UUID
+
+from pydantic.dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class EndpointInfo:
+ """An endpoint (team-scoped, name-addressed). Version-specific data lives on EndpointVersionInfo."""
+
+ id: UUID
+ team_id: int
+ name: str
+ is_active: bool
+ current_version: int
+ derived_from_insight: str | None
+ created_at: datetime
+ updated_at: datetime
+ last_executed_at: datetime | None
+
+
+@dataclass(frozen=True)
+class EndpointVersionInfo:
+ """An immutable query snapshot for one endpoint version."""
+
+ id: UUID
+ endpoint_id: UUID
+ version: int
+ query: dict
+ description: str
+ data_freshness_seconds: int
+ is_active: bool
+ is_materialized: bool
+ created_at: datetime
+ last_executed_at: datetime | None
diff --git a/products/endpoints/backend/facade/models.py b/products/endpoints/backend/facade/models.py
new file mode 100644
index 000000000000..678c92daff63
--- /dev/null
+++ b/products/endpoints/backend/facade/models.py
@@ -0,0 +1,12 @@
+"""
+Model-class wiring for endpoints.
+
+Light re-exports of the model classes cross-product object-consumers need
+(demo-data generation, HogQL system-table test fixtures). Prefer the
+contract-returning functions in ``facade.api`` for data access; import from
+here only when the consumer genuinely needs the model class itself.
+"""
+
+from products.endpoints.backend.models import Endpoint, EndpointVersion
+
+__all__ = ["Endpoint", "EndpointVersion"]
diff --git a/products/endpoints/backend/facade/tasks.py b/products/endpoints/backend/facade/tasks.py
new file mode 100644
index 000000000000..dff5688d4e2c
--- /dev/null
+++ b/products/endpoints/backend/facade/tasks.py
@@ -0,0 +1,10 @@
+"""
+Celery-task wiring for endpoints.
+
+Re-exports the beat-scheduled cleanup task (name-pinned) that core's
+scheduler registers.
+"""
+
+from products.endpoints.backend.tasks import deactivate_stale_materializations
+
+__all__ = ["deactivate_stale_materializations"]
diff --git a/products/endpoints/backend/facade/temporal.py b/products/endpoints/backend/facade/temporal.py
new file mode 100644
index 000000000000..43cf91ceeceb
--- /dev/null
+++ b/products/endpoints/backend/facade/temporal.py
@@ -0,0 +1,14 @@
+"""
+Temporal wiring for endpoints.
+
+Re-exports the hooks the data-modeling Temporal workflow calls around
+endpoint-backed saved queries: rebuilding the executable HogQL before each
+materialization run, and updating the materialization-readiness cache on
+completion/failure. Heavy imports (HogQL) ride along, same as the direct
+imports they replace — keep this module off config-only import paths.
+"""
+
+from products.endpoints.backend.logic.materialization import prepare_executable_query
+from products.endpoints.backend.rate_limit import update_materialization_ready_for_saved_query
+
+__all__ = ["prepare_executable_query", "update_materialization_ready_for_saved_query"]
diff --git a/products/endpoints/backend/logic/__init__.py b/products/endpoints/backend/logic/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/endpoints/backend/services/activity.py b/products/endpoints/backend/logic/activity.py
similarity index 100%
rename from products/endpoints/backend/services/activity.py
rename to products/endpoints/backend/logic/activity.py
diff --git a/products/endpoints/backend/services/crud.py b/products/endpoints/backend/logic/crud.py
similarity index 98%
rename from products/endpoints/backend/services/crud.py
rename to products/endpoints/backend/logic/crud.py
index b21e82a6e97b..24e1907022fe 100644
--- a/products/endpoints/backend/services/crud.py
+++ b/products/endpoints/backend/logic/crud.py
@@ -29,11 +29,11 @@ from posthog.types import InsightQueryNode
from products.data_modeling.backend.facade.api import delete_node_from_dag
from products.data_warehouse.backend.facade.api import trigger_saved_query_schedule
from products.endpoints.backend.constants import DEFAULT_DATA_FRESHNESS_SECONDS
+from products.endpoints.backend.logic.activity import EndpointContext
+from products.endpoints.backend.logic.materialization import EndpointMaterializationService
+from products.endpoints.backend.logic.validation import validate_bucket_overrides
from products.endpoints.backend.models import Endpoint, EndpointVersion
from products.endpoints.backend.rate_limit import clear_endpoint_materialization_cache
-from products.endpoints.backend.services.activity import EndpointContext
-from products.endpoints.backend.services.materialization import EndpointMaterializationService
-from products.endpoints.backend.services.validation import validate_bucket_overrides
logger = structlog.get_logger(__name__)
diff --git a/products/endpoints/backend/services/ducklake_shadow.py b/products/endpoints/backend/logic/ducklake_shadow.py
similarity index 98%
rename from products/endpoints/backend/services/ducklake_shadow.py
rename to products/endpoints/backend/logic/ducklake_shadow.py
index 62bf7a017f5b..f6dffc65adf1 100644
--- a/products/endpoints/backend/services/ducklake_shadow.py
+++ b/products/endpoints/backend/logic/ducklake_shadow.py
@@ -10,8 +10,8 @@ from posthog.ducklake.common import get_duckgres_server_for_organization, is_dev
from posthog.models import Team
from posthog.ph_client import ph_scoped_capture
+from products.endpoints.backend.logic.strategies import strategy_for
from products.endpoints.backend.models import Endpoint, EndpointVersion
-from products.endpoints.backend.services.strategies import strategy_for
logger = get_logger(__name__)
diff --git a/products/endpoints/backend/services/execution.py b/products/endpoints/backend/logic/execution.py
similarity index 99%
rename from products/endpoints/backend/services/execution.py
rename to products/endpoints/backend/logic/execution.py
index 4714c7dc3c3e..878d799a937f 100644
--- a/products/endpoints/backend/services/execution.py
+++ b/products/endpoints/backend/logic/execution.py
@@ -71,6 +71,8 @@ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.data_warehouse.backend.facade.api import trigger_saved_query_schedule
from products.endpoints.backend.exceptions import EndpointAtCapacity, EndpointQueryTooExpensive
from products.endpoints.backend.insight_transformers import MaterializedSeriesMismatchError
+from products.endpoints.backend.logic.pagination import EndpointPagination
+from products.endpoints.backend.logic.strategies import EndpointQueryStrategy, strategy_for
from products.endpoints.backend.logs import build_execution_message, log_endpoint_execution
from products.endpoints.backend.metrics import (
ENDPOINT_CACHE_RESULT_TOTAL,
@@ -83,8 +85,6 @@ from products.endpoints.backend.metrics import (
query_kind_label,
)
from products.endpoints.backend.models import Endpoint, EndpointVersion
-from products.endpoints.backend.services.pagination import EndpointPagination
-from products.endpoints.backend.services.strategies import EndpointQueryStrategy, strategy_for
from products.endpoints.backend.tasks import shadow_compare_ducklake_execution
from common.hogvm.python.utils import HogVMException
diff --git a/products/endpoints/backend/services/materialization.py b/products/endpoints/backend/logic/materialization.py
similarity index 99%
rename from products/endpoints/backend/services/materialization.py
rename to products/endpoints/backend/logic/materialization.py
index 1a362b8531e1..5219e1c5d635 100644
--- a/products/endpoints/backend/services/materialization.py
+++ b/products/endpoints/backend/logic/materialization.py
@@ -29,6 +29,8 @@ from posthog.models.activity_logging.activity_log import Detail, log_activity
from products.data_modeling.backend.facade.api import delete_node_from_dag, sync_saved_query_to_dag
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.endpoints.backend.constants import DATA_FRESHNESS_BUCKETS
+from products.endpoints.backend.logic.activity import EndpointContext
+from products.endpoints.backend.logic.strategies import apply_where_filter, strategy_for
from products.endpoints.backend.materialization_transforms import (
MaterializationNotSupportedError,
_extract_aggregate_name,
@@ -41,8 +43,6 @@ from products.endpoints.backend.materialization_transforms import (
from products.endpoints.backend.metrics import ENDPOINT_MATERIALIZATION_EVENT_TOTAL
from products.endpoints.backend.models import Endpoint, EndpointVersion
from products.endpoints.backend.rate_limit import clear_endpoint_materialization_cache
-from products.endpoints.backend.services.activity import EndpointContext
-from products.endpoints.backend.services.strategies import apply_where_filter, strategy_for
from products.warehouse_sources.backend.facade.models import sync_frequency_to_sync_frequency_interval
logger = structlog.get_logger(__name__)
diff --git a/products/endpoints/backend/services/pagination.py b/products/endpoints/backend/logic/pagination.py
similarity index 100%
rename from products/endpoints/backend/services/pagination.py
rename to products/endpoints/backend/logic/pagination.py
diff --git a/products/endpoints/backend/services/strategies.py b/products/endpoints/backend/logic/strategies.py
similarity index 99%
rename from products/endpoints/backend/services/strategies.py
rename to products/endpoints/backend/logic/strategies.py
index 1a578419b7c3..435afc77f640 100644
--- a/products/endpoints/backend/services/strategies.py
+++ b/products/endpoints/backend/logic/strategies.py
@@ -37,6 +37,7 @@ from posthog.hogql_queries.insights.utils.breakdowns import BREAKDOWN_NULL_STRIN
from posthog.models.team import Team
from products.endpoints.backend.insight_transformers import transform_materialized_insight_response
+from products.endpoints.backend.logic.pagination import EndpointPagination
from products.endpoints.backend.materialization_transforms import (
ENDPOINT_BREAKDOWN_LIMIT,
MaterializableVariable,
@@ -45,7 +46,6 @@ from products.endpoints.backend.materialization_transforms import (
transform_select_for_materialized_table,
)
from products.endpoints.backend.models import Endpoint, EndpointVersion
-from products.endpoints.backend.services.pagination import EndpointPagination
if TYPE_CHECKING:
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
diff --git a/products/endpoints/backend/services/validation.py b/products/endpoints/backend/logic/validation.py
similarity index 100%
rename from products/endpoints/backend/services/validation.py
rename to products/endpoints/backend/logic/validation.py
diff --git a/products/endpoints/backend/openapi.py b/products/endpoints/backend/openapi.py
index 32adc16eb383..f302c13d809e 100644
--- a/products/endpoints/backend/openapi.py
+++ b/products/endpoints/backend/openapi.py
@@ -2,8 +2,8 @@ from django.conf import settings
from rest_framework.request import Request
+from products.endpoints.backend.logic.strategies import InsightEndpointStrategy
from products.endpoints.backend.models import Endpoint, EndpointVersion
-from products.endpoints.backend.services.strategies import InsightEndpointStrategy
from products.product_analytics.backend.models.insight_variable import InsightVariable
INSIGHT_VARIABLE_TYPE_TO_OPENAPI: dict[str, dict] = {
diff --git a/products/endpoints/backend/presentation/__init__.py b/products/endpoints/backend/presentation/__init__.py
new file mode 100644
index 000000000000..28feeaab1366
--- /dev/null
+++ b/products/endpoints/backend/presentation/__init__.py
@@ -0,0 +1 @@
+"""HTTP presentation layer of the endpoints product (DRF viewsets and serializers)."""
diff --git a/products/endpoints/backend/serializers.py b/products/endpoints/backend/presentation/serializers.py
similarity index 100%
rename from products/endpoints/backend/serializers.py
rename to products/endpoints/backend/presentation/serializers.py
diff --git a/products/endpoints/backend/presentation/views/__init__.py b/products/endpoints/backend/presentation/views/__init__.py
new file mode 100644
index 000000000000..359ebb6fa9f9
--- /dev/null
+++ b/products/endpoints/backend/presentation/views/__init__.py
@@ -0,0 +1,3 @@
+"""DRF viewsets for endpoints — submodule paths (`backend.presentation.views.*`) are part
+of the shared tach interface for isolated products.
+"""
diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/presentation/views/api.py
similarity index 97%
rename from products/endpoints/backend/api.py
rename to products/endpoints/backend/presentation/views/api.py
index 36cd8b311f0a..b01e196ec6a7 100644
--- a/products/endpoints/backend/api.py
+++ b/products/endpoints/backend/presentation/views/api.py
@@ -1,13 +1,13 @@
"""HTTP layer for the Endpoints product.
The viewset is intentionally thin: authentication/permissions, request parsing,
-and response serialization. Business logic lives in ``backend/services``:
+and response serialization. Business logic lives in ``backend/logic``:
-- ``services.crud``: create/update/destroy orchestration + activity logging
-- ``services.execution``: the /run path (materialized / inline / DuckLake)
-- ``services.materialization``: enable/disable/preview materialization
-- ``services.strategies``: HogQL vs insight query behavior
-- ``services.validation``: request payload validation
+- ``logic.crud``: create/update/destroy orchestration + activity logging
+- ``logic.execution``: the /run path (materialized / inline / DuckLake)
+- ``logic.materialization``: enable/disable/preview materialization
+- ``logic.strategies``: HogQL vs insight query behavior
+- ``logic.validation``: request payload validation
"""
import re
@@ -54,32 +54,29 @@ from posthog.rbac.user_access_control import access_level_satisfied_for_resource
from posthog.schema_migrations.upgrade import upgrade
from products.endpoints.backend.constants import ENDPOINT_NAME_REGEX
+from products.endpoints.backend.logic.crud import EndpointCrudService
+from products.endpoints.backend.logic.execution import EndpointExecutionService
+from products.endpoints.backend.logic.materialization import EndpointMaterializationService, build_materialization_info
+from products.endpoints.backend.logic.validation import (
+ validate_bucket_overrides,
+ validate_endpoint_request,
+ validate_update_request,
+)
from products.endpoints.backend.logs import ENDPOINTS_LOG_SOURCE
from products.endpoints.backend.models import Endpoint, EndpointVersion
from products.endpoints.backend.openapi import generate_openapi_spec
-from products.endpoints.backend.rate_limit import (
- EndpointBurstThrottle,
- EndpointProjectSecretApiKeyTeamBurstThrottle,
- EndpointProjectSecretApiKeyTeamSustainedThrottle,
- EndpointSustainedThrottle,
-)
-from products.endpoints.backend.serializers import (
+from products.endpoints.backend.presentation.serializers import (
EndpointMaterializationSerializer,
EndpointRequestSerializer,
EndpointResponseSerializer,
EndpointRunResponseSerializer,
EndpointVersionResponseSerializer,
)
-from products.endpoints.backend.services.crud import EndpointCrudService
-from products.endpoints.backend.services.execution import EndpointExecutionService
-from products.endpoints.backend.services.materialization import (
- EndpointMaterializationService,
- build_materialization_info,
-)
-from products.endpoints.backend.services.validation import (
- validate_bucket_overrides,
- validate_endpoint_request,
- validate_update_request,
+from products.endpoints.backend.rate_limit import (
+ EndpointBurstThrottle,
+ EndpointProjectSecretApiKeyTeamBurstThrottle,
+ EndpointProjectSecretApiKeyTeamSustainedThrottle,
+ EndpointSustainedThrottle,
)
diff --git a/products/endpoints/backend/routes.py b/products/endpoints/backend/routes.py
index 842f908775b4..428889907963 100644
--- a/products/endpoints/backend/routes.py
+++ b/products/endpoints/backend/routes.py
@@ -1,6 +1,6 @@
from posthog.api.routing import RouterRegistry
-from products.endpoints.backend.api import EndpointViewSet
+from products.endpoints.backend.presentation.views.api import EndpointViewSet
def register_routes(routers: RouterRegistry) -> None:
diff --git a/products/endpoints/backend/tasks/__init__.py b/products/endpoints/backend/tasks/__init__.py
new file mode 100644
index 000000000000..ba5b688474d6
--- /dev/null
+++ b/products/endpoints/backend/tasks/__init__.py
@@ -0,0 +1,4 @@
+from products.endpoints.backend.tasks.tasks import ( # noqa: F401
+ deactivate_stale_materializations,
+ shadow_compare_ducklake_execution,
+)
diff --git a/products/endpoints/backend/tasks.py b/products/endpoints/backend/tasks/tasks.py
similarity index 92%
rename from products/endpoints/backend/tasks.py
rename to products/endpoints/backend/tasks/tasks.py
index cf01bea46f76..3a6b2cf7d611 100644
--- a/products/endpoints/backend/tasks.py
+++ b/products/endpoints/backend/tasks/tasks.py
@@ -9,16 +9,20 @@ from structlog import get_logger
from posthog.celery_queues import CeleryQueue
from posthog.scoping_audit import skip_team_scope_audit
+from products.endpoints.backend.logic.ducklake_shadow import run_ducklake_shadow_comparison
from products.endpoints.backend.metrics import ENDPOINT_MATERIALIZATION_EVENT_TOTAL
from products.endpoints.backend.models import EndpointVersion
-from products.endpoints.backend.services.ducklake_shadow import run_ducklake_shadow_comparison
logger = get_logger(__name__)
STALE_THRESHOLD_DAYS = 30
-@shared_task(ignore_result=True, queue=CeleryQueue.LONG_RUNNING.value)
+@shared_task(
+ ignore_result=True,
+ queue=CeleryQueue.LONG_RUNNING.value,
+ name="products.endpoints.backend.tasks.shadow_compare_ducklake_execution",
+)
@skip_team_scope_audit
def shadow_compare_ducklake_execution(
team_id: int,
@@ -46,7 +50,7 @@ def shadow_compare_ducklake_execution(
)
-@shared_task(ignore_result=True)
+@shared_task(ignore_result=True, name="products.endpoints.backend.tasks.deactivate_stale_materializations")
@skip_team_scope_audit
def deactivate_stale_materializations() -> None:
"""
diff --git a/products/endpoints/backend/tests/test_deactivate_stale_materializations.py b/products/endpoints/backend/tests/test_deactivate_stale_materializations.py
index 9e238f7770f0..e620cd52ade3 100644
--- a/products/endpoints/backend/tests/test_deactivate_stale_materializations.py
+++ b/products/endpoints/backend/tests/test_deactivate_stale_materializations.py
@@ -8,7 +8,7 @@ from django.utils import timezone
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.endpoints.backend.models import Endpoint, EndpointVersion
-from products.endpoints.backend.tasks import (
+from products.endpoints.backend.tasks.tasks import (
STALE_THRESHOLD_DAYS,
_deactivate_version_materialization,
deactivate_stale_materializations,
@@ -207,7 +207,7 @@ class TestDeactivateStaleMaterializationsTask(BaseTest):
def test_no_endpoints_found(self):
# No materialized endpoints exist
- with mock.patch("products.endpoints.backend.tasks.logger") as mock_logger:
+ with mock.patch("products.endpoints.backend.tasks.tasks.logger") as mock_logger:
deactivate_stale_materializations()
mock_logger.info.assert_called_with("deactivate_stale_materializations_no_candidates")
diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.py
index f3dfc49bfe86..769301b9ff5a 100644
--- a/products/endpoints/backend/tests/test_endpoint.py
+++ b/products/endpoints/backend/tests/test_endpoint.py
@@ -1473,7 +1473,7 @@ class TestMaterializationPreview(ClickhouseTestMixin, APIBaseTest):
assert version.bucket_overrides == {"timestamp": "week"}
# Change bucket_overrides — should trigger an immediate refresh
- with mock.patch("products.endpoints.backend.services.crud.trigger_saved_query_schedule") as mock_trigger:
+ with mock.patch("products.endpoints.backend.logic.crud.trigger_saved_query_schedule") as mock_trigger:
response = self.client.patch(
f"/api/environments/{self.team.id}/endpoints/trigger-bucket/",
{"bucket_overrides": {"timestamp": "hour"}},
diff --git a/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py b/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py
index 737598ba9220..9171d6322135 100644
--- a/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py
+++ b/products/endpoints/backend/tests/test_endpoint_ducklake_shadow.py
@@ -8,8 +8,8 @@ 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.logic import ducklake_shadow
+from products.endpoints.backend.logic.execution import EndpointExecutionService
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
pytestmark = [pytest.mark.django_db]
@@ -27,9 +27,9 @@ class TestShadowDispatch(APIBaseTest):
status=status.HTTP_200_OK,
)
- @mock.patch("products.endpoints.backend.services.execution.shadow_compare_ducklake_execution")
+ @mock.patch("products.endpoints.backend.logic.execution.shadow_compare_ducklake_execution")
@mock.patch(
- "products.endpoints.backend.services.execution.EndpointExecutionService._should_shadow_ducklake",
+ "products.endpoints.backend.logic.execution.EndpointExecutionService._should_shadow_ducklake",
return_value=True,
)
def test_dispatches_shadow_for_inline_execution(self, _mock_should, mock_task):
@@ -39,7 +39,7 @@ class TestShadowDispatch(APIBaseTest):
version = endpoint.get_version()
with mock.patch(
- "products.endpoints.backend.services.execution.EndpointExecutionService._execute_inline_endpoint",
+ "products.endpoints.backend.logic.execution.EndpointExecutionService._execute_inline_endpoint",
return_value=self._inline_response(),
):
response = self.client.get(f"/api/environments/{self.team.id}/endpoints/shadow-inline/run/")
@@ -57,9 +57,9 @@ class TestShadowDispatch(APIBaseTest):
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.logic.execution.shadow_compare_ducklake_execution")
@mock.patch(
- "products.endpoints.backend.services.execution.EndpointExecutionService._should_shadow_ducklake",
+ "products.endpoints.backend.logic.execution.EndpointExecutionService._should_shadow_ducklake",
return_value=True,
)
def test_no_dispatch_on_cache_hit(self, _mock_should, mock_task):
@@ -70,7 +70,7 @@ class TestShadowDispatch(APIBaseTest):
)
with mock.patch(
- "products.endpoints.backend.services.execution.EndpointExecutionService._execute_inline_endpoint",
+ "products.endpoints.backend.logic.execution.EndpointExecutionService._execute_inline_endpoint",
return_value=cached,
):
response = self.client.get(f"/api/environments/{self.team.id}/endpoints/shadow-cached/run/")
@@ -78,16 +78,16 @@ class TestShadowDispatch(APIBaseTest):
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.logic.execution.shadow_compare_ducklake_execution")
@mock.patch(
- "products.endpoints.backend.services.execution.EndpointExecutionService._should_shadow_ducklake",
+ "products.endpoints.backend.logic.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",
+ "products.endpoints.backend.logic.execution.EndpointExecutionService._execute_inline_endpoint",
return_value=self._inline_response(),
):
response = self.client.post(
@@ -101,16 +101,16 @@ class TestShadowDispatch(APIBaseTest):
assert kwargs["limit"] == 5
assert kwargs["offset"] == 2
- @mock.patch("products.endpoints.backend.services.execution.shadow_compare_ducklake_execution")
+ @mock.patch("products.endpoints.backend.logic.execution.shadow_compare_ducklake_execution")
@mock.patch(
- "products.endpoints.backend.services.execution.EndpointExecutionService._should_shadow_ducklake",
+ "products.endpoints.backend.logic.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",
+ "products.endpoints.backend.logic.execution.EndpointExecutionService._execute_inline_endpoint",
return_value=self._inline_response(),
):
response = self.client.get(f"/api/environments/{self.team.id}/endpoints/shadow-off/run/")
@@ -294,7 +294,7 @@ class TestShouldShadowDucklake(APIBaseTest):
)
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)
+ @mock.patch("products.endpoints.backend.logic.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
@@ -302,7 +302,7 @@ class TestShouldShadowDucklake(APIBaseTest):
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)
+ @mock.patch("products.endpoints.backend.logic.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
@@ -310,8 +310,8 @@ class TestShouldShadowDucklake(APIBaseTest):
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")
+ @mock.patch("products.endpoints.backend.logic.execution.is_dev_mode", return_value=False)
+ @mock.patch("products.endpoints.backend.logic.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
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index 03d2ee5c7e52..38a2b77faeb4 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -16,7 +16,7 @@ from posthog.hogql.errors import ExposedHogQLError
from posthog.errors import CHQueryErrorNoCommonType
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
-from products.endpoints.backend.services.execution import EndpointExecutionService
+from products.endpoints.backend.logic.execution import EndpointExecutionService
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
from products.product_analytics.backend.models.insight_variable import InsightVariable
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -172,9 +172,9 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
)
with (
- mock.patch("products.endpoints.backend.services.execution.process_query_model", side_effect=error),
- mock.patch("products.endpoints.backend.services.execution.capture_exception"),
- mock.patch("products.endpoints.backend.services.execution._emit_endpoint_failure_signal"),
+ mock.patch("products.endpoints.backend.logic.execution.process_query_model", side_effect=error),
+ mock.patch("products.endpoints.backend.logic.execution.capture_exception"),
+ mock.patch("products.endpoints.backend.logic.execution._emit_endpoint_failure_signal"),
):
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
@@ -1795,7 +1795,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
# BREAKDOWN SENTINEL CLEANUP
# =========================================================================
- @mock.patch("products.endpoints.backend.services.execution.process_query_model")
+ @mock.patch("products.endpoints.backend.logic.execution.process_query_model")
def test_inline_insight_sentinel_null_cleaned_from_breakdown_value(self, mock_process):
mock_process.return_value = {
"results": [
@@ -1822,7 +1822,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(results[0]["breakdown_value"], ["Chrome", None])
self.assertIsNone(results[1]["breakdown_value"])
- @mock.patch("products.endpoints.backend.services.execution.process_query_model")
+ @mock.patch("products.endpoints.backend.logic.execution.process_query_model")
def test_inline_insight_sentinel_cleaned_from_label(self, mock_process):
mock_process.return_value = {
"results": [
@@ -1851,7 +1851,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
results = response.json()["results"]
self.assertEqual(results[0]["label"], "Chrome::null")
- @mock.patch("products.endpoints.backend.services.execution.process_query_model")
+ @mock.patch("products.endpoints.backend.logic.execution.process_query_model")
def test_hogql_result_sentinel_cleaned_from_breakdown_column(self, mock_process):
mock_process.return_value = {
"results": [
@@ -1906,7 +1906,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
# Patch the limit to a low value so the 30 distinct breakdown values exceed it
with (
mock.patch("products.endpoints.backend.materialization_transforms.ENDPOINT_BREAKDOWN_LIMIT", 5),
- mock.patch("products.endpoints.backend.services.strategies.capture_exception") as mock_capture,
+ mock.patch("products.endpoints.backend.logic.strategies.capture_exception") as mock_capture,
):
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",
@@ -2230,7 +2230,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
def test_disable_materialization_no_op_does_not_increment_counter(self):
from prometheus_client import REGISTRY
- from products.endpoints.backend.services.materialization import EndpointMaterializationService
+ from products.endpoints.backend.logic.materialization import EndpointMaterializationService
endpoint = self._make_simple_hogql_endpoint("metric_disable_no_op")
labels = {"action": "disable", "status": "success"}
@@ -2248,8 +2248,8 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
boom = RuntimeError("synthetic failure")
with (
- mock.patch("products.endpoints.backend.services.execution.process_query_model", side_effect=boom),
- mock.patch("products.endpoints.backend.services.execution._emit_endpoint_failure_signal") as mock_emit,
+ mock.patch("products.endpoints.backend.logic.execution.process_query_model", side_effect=boom),
+ mock.patch("products.endpoints.backend.logic.execution._emit_endpoint_failure_signal") as mock_emit,
):
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",
@@ -2267,7 +2267,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
def test_emit_failure_signal_swallows_errors(self):
"""Signal emission must never mask the original exception."""
- from products.endpoints.backend.services.execution import _emit_endpoint_failure_signal
+ from products.endpoints.backend.logic.execution import _emit_endpoint_failure_signal
endpoint = self._make_simple_hogql_endpoint("failure_signal_swallow")
@@ -2391,7 +2391,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
def test_series_mismatch_falls_back_to_inline(self):
"""Series drift triggers re-materialization AND serves the request inline."""
from products.endpoints.backend.insight_transformers import MaterializedSeriesMismatchError
- from products.endpoints.backend.services.strategies import InsightEndpointStrategy
+ from products.endpoints.backend.logic.strategies import InsightEndpointStrategy
endpoint = self._make_fresh_materialized_endpoint(
"mismatch-fallback",
@@ -2414,7 +2414,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
"transform_materialized_response",
side_effect=MaterializedSeriesMismatchError("series drift"),
),
- mock.patch("products.endpoints.backend.services.execution.trigger_saved_query_schedule") as mock_trigger,
+ mock.patch("products.endpoints.backend.logic.execution.trigger_saved_query_schedule") as mock_trigger,
):
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
@@ -2427,7 +2427,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
def test_emit_failure_signal_reaches_workflow_boundary(self):
"""The failure-signal plumbing must make it to the Temporal boundary when the
org/source gates allow it — anything raising before that is a plumbing bug."""
- from products.endpoints.backend.services.execution import _emit_endpoint_failure_signal
+ from products.endpoints.backend.logic.execution import _emit_endpoint_failure_signal
from products.signals.backend.models import SignalSourceConfig
self.organization.is_ai_data_processing_approved = True
diff --git a/products/endpoints/backend/tests/test_endpoint_logs.py b/products/endpoints/backend/tests/test_endpoint_logs.py
index c789620e0953..e4f41ab68924 100644
--- a/products/endpoints/backend/tests/test_endpoint_logs.py
+++ b/products/endpoints/backend/tests/test_endpoint_logs.py
@@ -76,7 +76,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):
def test_successful_run_emits_info_log(self):
endpoint = self._create_hogql_endpoint("logs_ok", "SELECT 1")
- with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:
+ with mock.patch("products.endpoints.backend.logic.execution.log_endpoint_execution") as mock_log:
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
)
@@ -95,7 +95,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):
def test_failed_run_emits_error_log(self):
endpoint = self._create_hogql_endpoint("logs_fail", "SELECT nonexistent_column_xyz FROM events")
- with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:
+ with mock.patch("products.endpoints.backend.logic.execution.log_endpoint_execution") as mock_log:
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
)
@@ -111,7 +111,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):
def test_successful_run_returns_execution_id_matching_log(self):
endpoint = self._create_hogql_endpoint("logs_exec_id", "SELECT 1")
- with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:
+ with mock.patch("products.endpoints.backend.logic.execution.log_endpoint_execution") as mock_log:
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", {}, format="json"
)
@@ -125,7 +125,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):
def test_invalid_refresh_mode_emits_error_log_and_clean_message(self):
endpoint = self._create_hogql_endpoint("logs_bad_refresh", "SELECT 1")
- with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:
+ with mock.patch("products.endpoints.backend.logic.execution.log_endpoint_execution") as mock_log:
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",
{"refresh": "hey"},
@@ -161,7 +161,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):
# must still surface in the logs.
endpoint = self._create_hogql_endpoint(f"logs_reject_{_name}", "SELECT 1")
- with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:
+ with mock.patch("products.endpoints.backend.logic.execution.log_endpoint_execution") as mock_log:
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/", body, format="json"
)
@@ -178,7 +178,7 @@ class TestEndpointExecutionLogs(ClickhouseTestMixin, APIBaseTest):
# non-materialized endpoint — this failure must still surface in the logs.
endpoint = self._create_hogql_endpoint("logs_bad_validate", "SELECT 1")
- with mock.patch("products.endpoints.backend.services.execution.log_endpoint_execution") as mock_log:
+ with mock.patch("products.endpoints.backend.logic.execution.log_endpoint_execution") as mock_log:
response = self.client.post(
f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",
{"refresh": "direct"},
diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.py
index 62fa0f5978c3..9cae326eb7e2 100644
--- a/products/endpoints/backend/tests/test_endpoint_materialization.py
+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py
@@ -26,14 +26,14 @@ from posthog.sync import database_sync_to_async
from products.data_modeling.backend.facade.modeling import DataWarehouseModelPath
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.data_warehouse.backend.facade.api import get_saved_query_schedule
-from products.endpoints.backend.materialization_transforms import build_endpoint_hogql
-from products.endpoints.backend.models import EndpointVersion
-from products.endpoints.backend.services.execution import EndpointExecutionService
-from products.endpoints.backend.services.materialization import (
+from products.endpoints.backend.logic.execution import EndpointExecutionService
+from products.endpoints.backend.logic.materialization import (
EndpointMaterializationService,
OrphanedEndpointSavedQueryError,
prepare_executable_query,
)
+from products.endpoints.backend.materialization_transforms import build_endpoint_hogql
+from products.endpoints.backend.models import EndpointVersion
from products.endpoints.backend.tests.conftest import create_endpoint_with_version
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -655,7 +655,7 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
saved_query.save()
with mock.patch(
- "products.endpoints.backend.services.execution.EndpointExecutionService._execute_query_and_respond"
+ "products.endpoints.backend.logic.execution.EndpointExecutionService._execute_query_and_respond"
) as mock_execute:
old_cache_time = timezone.now() - timedelta(minutes=30)
old_cached_response = Response(
@@ -700,7 +700,7 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):
new_saved_query.save()
with mock.patch(
- "products.endpoints.backend.services.execution.EndpointExecutionService._execute_query_and_respond"
+ "products.endpoints.backend.logic.execution.EndpointExecutionService._execute_query_and_respond"
) as mock_execute:
new_cache_time = timezone.now() - timedelta(minutes=5)
new_cached_response = Response(
diff --git a/products/endpoints/backend/tests/test_endpoint_query_tagging.py b/products/endpoints/backend/tests/test_endpoint_query_tagging.py
index 8858edca849e..893d8392f3c8 100644
--- a/products/endpoints/backend/tests/test_endpoint_query_tagging.py
+++ b/products/endpoints/backend/tests/test_endpoint_query_tagging.py
@@ -43,7 +43,7 @@ class TestEndpointQueryTagging(ClickhouseTestMixin, APIBaseTest):
)
def test_run_via_session_auth_tags_endpoint_playground(self):
- with mock.patch("products.endpoints.backend.services.execution.tag_queries", wraps=tag_queries) as spy:
+ with mock.patch("products.endpoints.backend.logic.execution.tag_queries", wraps=tag_queries) as spy:
response = self.client.post(self.run_url, {}, format="json")
assert response.status_code == status.HTTP_200_OK, response.json()
call = _find_endpoint_feature_call(spy)
@@ -52,7 +52,7 @@ class TestEndpointQueryTagging(ClickhouseTestMixin, APIBaseTest):
def test_run_via_personal_api_key_tags_endpoint_execution(self):
self.client.logout()
- with mock.patch("products.endpoints.backend.services.execution.tag_queries", wraps=tag_queries) as spy:
+ with mock.patch("products.endpoints.backend.logic.execution.tag_queries", wraps=tag_queries) as spy:
response = self.client.post(
self.run_url,
{},
diff --git a/products/endpoints/backend/tests/test_facade.py b/products/endpoints/backend/tests/test_facade.py
new file mode 100644
index 000000000000..562f1c880cb1
--- /dev/null
+++ b/products/endpoints/backend/tests/test_facade.py
@@ -0,0 +1,61 @@
+from posthog.test.base import BaseTest
+
+from posthog.models.team import Team
+
+from products.endpoints.backend.facade import api as facade
+from products.endpoints.backend.tests.conftest import create_endpoint_with_version
+
+SAMPLE_QUERY = {"kind": "HogQLQuery", "query": "SELECT count(1) FROM query_log"}
+
+
+class TestEndpointsFacade(BaseTest):
+ def test_endpoint_reads_are_team_scoped_and_exclude_deleted(self):
+ endpoint = create_endpoint_with_version("live_endpoint", self.team, SAMPLE_QUERY, self.user)
+ deleted = create_endpoint_with_version("deleted_endpoint", self.team, SAMPLE_QUERY, self.user)
+ deleted.soft_delete()
+ other_team = Team.objects.create(organization=self.organization)
+ create_endpoint_with_version("other_team_endpoint", other_team, SAMPLE_QUERY, self.user)
+
+ listed = facade.list_endpoints(self.team.id)
+ assert [e.name for e in listed] == ["live_endpoint"]
+ assert facade.get_endpoint(self.team.id, "deleted_endpoint") is None
+ assert facade.get_endpoint(other_team.id, "live_endpoint") is None
+
+ info = facade.get_endpoint(self.team.id, "live_endpoint")
+ assert info is not None
+ assert info.id == endpoint.id
+ assert info.team_id == self.team.id
+ assert info.is_active is True
+ assert info.current_version == 1
+
+ def test_get_endpoint_version_resolves_current_and_specific(self):
+ endpoint = create_endpoint_with_version("versioned", self.team, SAMPLE_QUERY, self.user)
+ new_query = {"kind": "HogQLQuery", "query": "SELECT 2"}
+ endpoint.create_new_version(new_query, self.user)
+
+ current = facade.get_endpoint_version(self.team.id, "versioned")
+ assert current is not None
+ assert current.version == 2
+ assert current.query == new_query
+ assert current.endpoint_id == endpoint.id
+ assert current.is_materialized is False
+
+ v1 = facade.get_endpoint_version(self.team.id, "versioned", version=1)
+ assert v1 is not None
+ assert v1.query == SAMPLE_QUERY
+
+ assert facade.get_endpoint_version(self.team.id, "versioned", version=99) is None
+ assert facade.get_endpoint_version(self.team.id, "missing") is None
+
+ def test_wiring_reexports_resolve(self):
+ from products.endpoints.backend.facade import (
+ models as facade_models,
+ tasks as facade_tasks,
+ temporal,
+ )
+
+ assert callable(facade_tasks.deactivate_stale_materializations)
+ assert callable(temporal.prepare_executable_query)
+ assert callable(temporal.update_materialization_ready_for_saved_query)
+ assert facade_models.Endpoint is not None
+ assert facade_models.EndpointVersion is not None
diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.py
index b34fedf95601..2a69444c355c 100644
--- a/products/endpoints/backend/tests/test_insight_response_parity.py
+++ b/products/endpoints/backend/tests/test_insight_response_parity.py
@@ -148,7 +148,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
)
with mock.patch(
- "products.endpoints.backend.services.execution.process_query_model",
+ "products.endpoints.backend.logic.execution.process_query_model",
return_value=flat_response,
):
mat_resp = self._run_endpoint(endpoint)
@@ -205,7 +205,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
)
with mock.patch(
- "products.endpoints.backend.services.execution.process_query_model",
+ "products.endpoints.backend.logic.execution.process_query_model",
return_value=flat_response,
):
mat_resp = self._run_endpoint(endpoint, variables={"$browser": "Chrome"})
@@ -360,7 +360,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
)
with mock.patch(
- "products.endpoints.backend.services.execution.process_query_model",
+ "products.endpoints.backend.logic.execution.process_query_model",
return_value=flat_response,
):
mat_resp = self._run_endpoint(endpoint)
@@ -430,7 +430,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
)
with mock.patch(
- "products.endpoints.backend.services.execution.process_query_model",
+ "products.endpoints.backend.logic.execution.process_query_model",
return_value=flat_response,
):
mat_resp = self._run_endpoint(endpoint)
@@ -494,7 +494,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
)
with mock.patch(
- "products.endpoints.backend.services.execution.process_query_model",
+ "products.endpoints.backend.logic.execution.process_query_model",
return_value=flat_response,
):
mat_resp = self._run_endpoint(endpoint)
@@ -549,7 +549,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
)
with mock.patch(
- "products.endpoints.backend.services.execution.process_query_model",
+ "products.endpoints.backend.logic.execution.process_query_model",
return_value=flat_response,
):
mat_resp = self._run_endpoint(endpoint)
@@ -650,7 +650,7 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):
)
with mock.patch(
- "products.endpoints.backend.services.execution.process_query_model",
+ "products.endpoints.backend.logic.execution.process_query_model",
return_value=flat_response,
):
mat_resp = self._run_endpoint(endpoint)
diff --git a/products/endpoints/backend/tests/test_variable_materialization.py b/products/endpoints/backend/tests/test_variable_materialization.py
index d1db7abd4724..d840914ded0d 100644
--- a/products/endpoints/backend/tests/test_variable_materialization.py
+++ b/products/endpoints/backend/tests/test_variable_materialization.py
@@ -1891,7 +1891,7 @@ class TestMaterializedReadPath(APIBaseTest):
def _build_read_query(self, query_str: str, variables_meta: dict, variable_values: dict) -> str:
"""Simulate the materialized read path: analyze variables, then build a SELECT with filters."""
- from products.endpoints.backend.services.strategies import apply_where_filter
+ from products.endpoints.backend.logic.strategies import apply_where_filter
hogql_query = {"kind": "HogQLQuery", "query": query_str, "variables": variables_meta}
_, _, var_infos = analyze_variables_for_materialization(hogql_query)
diff --git a/products/endpoints/tsconfig.json b/products/endpoints/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/endpoints/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/pyproject.toml b/pyproject.toml
index 170af7083d29..efdd9953923e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -564,6 +564,19 @@ ignore_imports = [
"products.logs.backend.presentation.views.api -> products.exports.backend.models.exported_asset",
"products.logs.backend.presentation.views.alerts_api -> products.cdp.backend.api.hog_function",
"products.logs.backend.presentation.views.alerts_api -> products.cdp.backend.models.hog_functions.hog_function",
+ # TODO: endpoints presentation wave — the structural move landed EndpointViewSet under
+ # presentation/views/ but it still reaches in-product internals (models, logic services,
+ # throttles, openapi generation) directly. Thin it to parse -> facade -> serialize and
+ # delete each entry. backend:contract-check stays off until this list is empty.
+ "products.endpoints.backend.presentation.views.api -> products.endpoints.backend.constants",
+ "products.endpoints.backend.presentation.views.api -> products.endpoints.backend.logs",
+ "products.endpoints.backend.presentation.views.api -> products.endpoints.backend.models",
+ "products.endpoints.backend.presentation.views.api -> products.endpoints.backend.openapi",
+ "products.endpoints.backend.presentation.views.api -> products.endpoints.backend.rate_limit",
+ "products.endpoints.backend.presentation.views.api -> products.endpoints.backend.logic.crud",
+ "products.endpoints.backend.presentation.views.api -> products.endpoints.backend.logic.execution",
+ "products.endpoints.backend.presentation.views.api -> products.endpoints.backend.logic.materialization",
+ "products.endpoints.backend.presentation.views.api -> products.endpoints.backend.logic.validation",
# TODO: notebooks presentation wave — the moved NotebookViewSet still reaches in-product
# internals (collab, kernel runtime, query validation, models) and the tasks sandbox
# directly. Thin it to parse -> facade -> serialize and delete each entry.
diff --git a/tach.toml b/tach.toml
index c3d09a5ce6a4..34ab1a4ba52a 100644
--- a/tach.toml
+++ b/tach.toml
@@ -720,7 +720,7 @@ expose = [
"backend\\.routes.*",
]
from = [
- "products\\.(customer_analytics|data_modeling|data_warehouse|error_tracking|experiments|mcp_analytics|mcp_store|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review|warehouse_sources)",
+ "products\\.(customer_analytics|data_modeling|data_warehouse|endpoints|error_tracking|experiments|mcp_analytics|mcp_store|metrics|notebooks|notifications|streamlit_apps|tasks|tracing|user_interviews|visual_review|warehouse_sources)",
]
# TODO: Experiments-specific temporary interface