: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
chore(devex): adopt the facade wiring-couplings doctrine (#71486)
Julian Bezd02b44c16f22
diff --git a/.claude/rules/product-isolation.md b/.claude/rules/product-isolation.mdindex 8bba42c87320..94585bd50125 100644--- a/.claude/rules/product-isolation.md+++ b/.claude/rules/product-isolation.md@@ -12,6 +12,12 @@ this product is isolated.(`queries.py`, `tasks.py`, `temporal.py`, …) for wiring that core registers ordispatches on. Do not expose internal modules directly, and do not add rawcross-product imports — go through the target product's facade instead.+ Wiring submodules may only re-export classes that implement a core-owned base+ (`QueryRunner`, `MaxTool`, Temporal defns, `@shared_task`) and are defined under the+ product's wiring locations (`backend/hogql_queries/`, `backend/max_tools.py`,+ `backend/temporal/`, `backend/tasks/`); data and error types belong in+ `facade/contracts.py`; Django models never cross the boundary+ (see `products/architecture.md` § Wiring couplings).- **Not isolated:** boundaries are not yet enforced by CI, but prefer using existingfacades when they exist rather than importing internals.diff --git a/products/architecture.md b/products/architecture.mdindex 8d43be1ee7bd..ffa4b1889ef8 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -83,6 +83,36 @@ A product whose views still hold business logic is not soundly skippable even ifThis is also why "no in-process callers, so we don't need a facade" is the wrong test: a product whose only consumers are over HTTP (node services, the generated TS/MCP types) is _not_ facade-optional — there the facade's whole job is sealing its own presentation.The genuine exception is a product with essentially no Django-side logic (a thin shim over an external service): it has nothing to seal, but it is then simply not isolated — no `backend:contract-check`, still paying the full suite — which is an accept-the-cost choice, not "isolated without a facade".+### Wiring couplings++Core sometimes needs behavior from a product, not data: query runners it dispatches on, Temporal workflows it registers, Max tools it offers.+These cross the boundary as classes — allowed only under all three rules:++1. **Approved interface.**+ The class implements a core-owned base from the approved list — today `QueryRunner` (`posthog/hogql_queries/query_runner.py`), `MaxTool` (`ee/hogai/tool.py`), Temporal's `@workflow.defn`/`@activity.defn`, and Celery's `@shared_task`.+ Core code may rely only on the base's interface, never on product-specific members.+ Extending the list is a core PR: define the base and validate at the registration point.+ DRF viewsets are not part of this channel: they live in `presentation/`, register through `routes.py`, and never pass through the facade (facades must not import DRF) — their soundness is governed by the presentation rules above.+2. **Designated location.**+ The implementation lives in the product's wiring location — `backend/hogql_queries/`, `backend/max_tools.py`, `backend/temporal/`, `backend/tasks/` (a flat `backend/tasks.py` also qualifies) — and isolated products keep those locations in their `backend:contract-check` inputs, so any change to a wiring implementation still re-runs the full suite.+3. **Validated registration.**+ Registration points check `issubclass(cls, Base)` and reject anything else.+ Import linters (tach, import-linter) see only the import graph; _what an object is_ can only be checked at runtime, at the door.+ `ee/hogai/registry.py` (MaxTool) is the reference implementation: subclass auto-registration with validation.++Django models never cross, with or without an approved base.+A model cannot be narrowed: whatever interface it presents, the object still carries managers, `save()`/`delete()`, FK descriptors that query other tables on attribute access, and reverse relations added by other apps.+Two core registries are keyed by model class identity and are explicit, sanctioned exceptions: the team-extension registry and the file-system unfiled registry (`FileSystemSyncMixin`).+There the class crosses for registration only, core drives only the registry's mixin methods, and the model's module must stay in the product's contract-check inputs.++A behavioral class that fits no approved interface must not cross at all.+Wrap it in a facade function returning contracts, or register a plain function (see the managed-view provider registry in `products/data_modeling/backend/facade/managed_viewset_hooks.py`).+A product whose facade hands out unapproved behavior is not soundly isolated: it loses `backend:contract-check` and pays the full suite until fixed.++Why shape rules rather than location rules: publicness-by-location without a constrained API shape rots.+Shopify's Packwerk `app/public` folders became a "catch-all drawer" of models, controllers, and jobs for exactly this reason.+The facade stays honest only if what crosses is a frozen dataclass or an implementation of a core-owned interface — nothing else.+# 3. Folder StructureEach product adopts the following structure:@@ -188,7 +218,9 @@ If input and output shapes are identical, reuse the same dataclass.# 5. Facades: The Public Interface-Each product exposes a facade via `backend/facade/api.py`. This is the **only** file other products are allowed to import.+Each product exposes a facade via the `backend/facade/` package — the only place core and other products may import from (tach enforces this).+`api.py` holds the data capabilities: functions that accept and return contracts.+Capability submodules (`queries.py`, `temporal.py`, `max_tools.py`, `tasks.py`, …) exist only to re-export wiring implementations — see [Wiring couplings](#wiring-couplings) — and contain no logic of their own.### Responsibilities@@ -388,6 +420,7 @@ Turbo uses file-based inputs to determine cache validity. The key distinction:- `backend/facade/contracts.py` — frozen dataclasses (enums can live here too)- `backend/facade/enums.py` — optional, for exported enums/constants/shared types when contracts.py grows+- the product's wiring locations (`backend/hogql_queries/`, `backend/max_tools.py`, `backend/temporal/`, `backend/tasks/`) — implementations core registers and drives (see [Wiring couplings](#wiring-couplings))**Implementation inputs** (used by `backend:test`):diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 25a7f0cb21b4..c14f303ffa56 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -37,12 +37,14 @@ from posthog.models.tagged_item import TaggedItemfrom products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplinkfrom products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROLE_FIELDSfrom products.customer_analytics.backend.events import emit_account_tags_added+from products.customer_analytics.backend.facade.contracts import (+ InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,+)from products.customer_analytics.backend.logic import (custom_property_values as _custom_property_values_logic,relationships as _relationships_logic,)from products.customer_analytics.backend.logic.custom_property_definitions import (- InvalidCustomPropertyOptions as InvalidCustomPropertyOptions,apply_option_side_effects,coerce_is_big_number,normalize_options,diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex a53879658068..bbf510dfa4fd 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -22,6 +22,10 @@ from uuid import UUIDfrom pydantic.dataclasses import dataclass+class InvalidCustomPropertyOptions(ValueError):+ """Raised when a select property's options fail validation; the viewset maps it to a 400."""++@dataclass(frozen=True)class AccountAssignment:"""A user assigned to an account role (CSM, account executive, account owner)."""diff --git a/products/customer_analytics/backend/logic/custom_property_definitions.py b/products/customer_analytics/backend/logic/custom_property_definitions.pyindex 01dd0fde3f30..bc36c5c7ca8f 100644--- a/products/customer_analytics/backend/logic/custom_property_definitions.py+++ b/products/customer_analytics/backend/logic/custom_property_definitions.py@@ -6,6 +6,7 @@ from uuid import uuid4from django.db.models import Case, F, QuerySet, TextField, Value, Whenfrom products.customer_analytics.backend.constants import CUSTOM_PROPERTY_OPTION_COLORS+from products.customer_analytics.backend.facade.contracts import InvalidCustomPropertyOptionsfrom products.customer_analytics.backend.models import (DATA_TYPE_BY_DISPLAY_TYPE,CustomPropertyValue,@@ -14,10 +15,6 @@ from products.customer_analytics.backend.models import ()-class InvalidCustomPropertyOptions(ValueError):- """Raised when a select property's options fail validation; the viewset maps it to a 400."""--def coerce_is_big_number(display_type: str, is_big_number: bool) -> bool:"""``is_big_number`` only applies to numeric display types; force it false otherwise.diff --git a/products/customer_analytics/turbo.json b/products/customer_analytics/turbo.jsonindex e16d4eabe6e9..bb57633e21e2 100644--- a/products/customer_analytics/turbo.json+++ b/products/customer_analytics/turbo.json@@ -2,7 +2,15 @@"extends": ["//"],"tasks": {"backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],+ "inputs": [+ "backend/facade/**",+ "backend/presentation/**",+ "backend/routes.py",+ "backend/hogql_queries/**",+ "backend/max_tools.py",+ "backend/models/team_customer_analytics_config.py",+ "backend/tasks/**"+ ],"outputs": [],"cache": true}diff --git a/products/data_modeling/turbo.json b/products/data_modeling/turbo.jsondeleted file mode 100644index e16d4eabe6e9..000000000000--- a/products/data_modeling/turbo.json+++ /dev/null@@ -1,10 +0,0 @@-{- "extends": ["//"],- "tasks": {- "backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],- "outputs": [],- "cache": true- }- }-}diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.pyindex 8078a46a8436..31db7192488c 100644--- a/products/data_warehouse/backend/facade/api.py+++ b/products/data_warehouse/backend/facade/api.py@@ -70,7 +70,7 @@ _LAZY = {"get_redshift_source_location": "redshift_helpers","reconcile_redshift_schemas": "redshift_helpers","reproject_direct_redshift_table": "redshift_helpers",- "HogQLQueryFixerTool": "hogql_fixer_ai",+ "HogQLQueryFixerTool": "max_tools","hide_direct_mysql_table": "direct_mysql","upsert_direct_mysql_table": "direct_mysql","hide_direct_postgres_table": "direct_postgres",diff --git a/products/data_warehouse/backend/hogql_fixer_ai.py b/products/data_warehouse/backend/max_tools.pysimilarity index 100%rename from products/data_warehouse/backend/hogql_fixer_ai.pyrename to products/data_warehouse/backend/max_tools.pydiff --git a/products/data_warehouse/backend/test/test_hogql_fixer_ai.py b/products/data_warehouse/backend/test/test_hogql_fixer_ai.pyindex b65c0f8eb02c..d821c4a23847 100644--- a/products/data_warehouse/backend/test/test_hogql_fixer_ai.py+++ b/products/data_warehouse/backend/test/test_hogql_fixer_ai.py@@ -7,7 +7,7 @@ from posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User-from products.data_warehouse.backend.hogql_fixer_ai import _get_schema_description, _get_system_prompt, _get_user_prompt+from products.data_warehouse.backend.max_tools import _get_schema_description, _get_system_prompt, _get_user_prompt@pytest.mark.django_dbdiff --git a/products/data_warehouse/backend/tests/api/test_fix_hogql.py b/products/data_warehouse/backend/tests/api/test_fix_hogql.pyindex 326ac2b47c94..6ce80538802d 100644--- a/products/data_warehouse/backend/tests/api/test_fix_hogql.py+++ b/products/data_warehouse/backend/tests/api/test_fix_hogql.py@@ -1,13 +1,13 @@from posthog.test.base import APIBaseTestfrom unittest import mock-from products.data_warehouse.backend.hogql_fixer_ai import HogQLQueryFixerTool+from products.data_warehouse.backend.max_tools import HogQLQueryFixerToolclass TestFixHogQL(APIBaseTest):def test_create(self):with (- mock.patch("products.data_warehouse.backend.hogql_fixer_ai.MaxChatOpenAI"),+ mock.patch("products.data_warehouse.backend.max_tools.MaxChatOpenAI"),mock.patch.object(HogQLQueryFixerTool, "_parse_output", return_value="select timestamp from events"),):response = self.client.post(@@ -33,7 +33,7 @@ class TestFixHogQL(APIBaseTest):return wrapperwith (- mock.patch("products.data_warehouse.backend.hogql_fixer_ai.MaxChatOpenAI"),+ mock.patch("products.data_warehouse.backend.max_tools.MaxChatOpenAI"),mock.patch.object(HogQLQueryFixerTool, "_parse_output", return_value="select timestamp from events"),mock.patch.object(HogQLQueryFixerTool, "__init__", capture_tool_init(HogQLQueryFixerTool.__init__)),):diff --git a/products/data_warehouse/turbo.json b/products/data_warehouse/turbo.jsondeleted file mode 100644index e16d4eabe6e9..000000000000--- a/products/data_warehouse/turbo.json+++ /dev/null@@ -1,10 +0,0 @@-{- "extends": ["//"],- "tasks": {- "backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],- "outputs": [],- "cache": true- }- }-}diff --git a/products/demo/backend/facade/contracts.py b/products/demo/backend/facade/contracts.pyindex b51594e430a1..8f7a7a040a43 100644--- a/products/demo/backend/facade/contracts.py+++ b/products/demo/backend/facade/contracts.py@@ -3,7 +3,10 @@The demo facade is behavioral: it exposes the matrix-simulation entry points (the`MatrixManager`, the `HedgeboxMatrix`/`SpikeGPTMatrix` scenarios) and data-generationhelpers, which write into core models and return primitives. The product owns no data-model of its own, so there are no product-owned contracts to define here — the file-exists to mark the product as isolated and is the home for any future cross-boundary-data record.+model of its own, so there are no product-owned contracts to define here, and this file+is only the home for any future cross-boundary data record.++Demo is not isolated: its facade hands out those behavioral classes (`MatrixManager`,+`Matrix`, `HedgeboxMatrix`, `SpikeGPTMatrix`) directly rather than as frozen contracts,+driven across the boundary by `posthog/api/signup.py` and the demo management commands."""diff --git a/products/demo/package.json b/products/demo/package.jsonindex f08610b153e5..0f56201cd6b5 100644--- a/products/demo/package.json+++ b/products/demo/package.json@@ -2,7 +2,6 @@"name": "@posthog/products-demo","scripts": {"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/test -v --tb=short",- "backend:lint": "ruff check --config ../../pyproject.toml backend && ruff format --config ../../pyproject.toml --check backend",- "backend:contract-check": "echo 'Contract files unchanged'"+ "backend:lint": "ruff check --config ../../pyproject.toml backend && ruff format --config ../../pyproject.toml --check backend"}}diff --git a/products/demo/turbo.json b/products/demo/turbo.jsondeleted file mode 100644index 34a16b3d30ce..000000000000--- a/products/demo/turbo.json+++ /dev/null@@ -1,10 +0,0 @@-{- "extends": ["//"],- "tasks": {- "backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**"],- "outputs": [],- "cache": true- }- }-}diff --git a/products/endpoints/turbo.json b/products/endpoints/turbo.jsondeleted file mode 100644index e16d4eabe6e9..000000000000--- a/products/endpoints/turbo.json+++ /dev/null@@ -1,10 +0,0 @@-{- "extends": ["//"],- "tasks": {- "backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],- "outputs": [],- "cache": true- }- }-}diff --git a/products/engineering_analytics/turbo.json b/products/engineering_analytics/turbo.jsonindex e16d4eabe6e9..89467ab134d4 100644--- a/products/engineering_analytics/turbo.json+++ b/products/engineering_analytics/turbo.json@@ -2,7 +2,7 @@"extends": ["//"],"tasks": {"backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],+ "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py", "backend/tasks/**"],"outputs": [],"cache": true}diff --git a/products/error_tracking/backend/facade/tools.py b/products/error_tracking/backend/facade/tools.pyindex 9524f243a6a8..e1b576400741 100644--- a/products/error_tracking/backend/facade/tools.py+++ b/products/error_tracking/backend/facade/tools.py@@ -2,11 +2,11 @@The AI agent presets (``ee/hogai``) register this tool class with the assistant.It crosses the boundary as an object, not data, so it lives in its own facade-submodule. ``search_issues`` imports ``ee.hogai`` itself, so consumers must keep+submodule. ``max_tools`` imports ``ee.hogai`` itself, so consumers must keepimporting this lazily (inside the registration call site) to avoid a circularimport on the ``django.setup()`` path."""-from products.error_tracking.backend.logic.tools.search_issues import SearchErrorTrackingIssuesTool+from products.error_tracking.backend.max_tools import SearchErrorTrackingIssuesTool__all__ = ["SearchErrorTrackingIssuesTool"]diff --git a/products/error_tracking/backend/logic/tools/__init__.py b/products/error_tracking/backend/logic/tools/__init__.pydeleted file mode 100644index 7532ea7db807..000000000000--- a/products/error_tracking/backend/logic/tools/__init__.py+++ /dev/null@@ -1,5 +0,0 @@-from .search_issues import SearchErrorTrackingIssuesTool--__all__ = [- "SearchErrorTrackingIssuesTool",-]diff --git a/products/error_tracking/backend/logic/tools/search_issues.py b/products/error_tracking/backend/logic/tools/search_issues.pydeleted file mode 100644index 136d529a83c5..000000000000--- a/products/error_tracking/backend/logic/tools/search_issues.py+++ /dev/null@@ -1,381 +0,0 @@-import json-from datetime import UTC-from textwrap import dedent-from typing import Literal, cast--from django.utils import timezone--import structlog-from posthoganalytics import capture_exception-from pydantic import BaseModel, Field--from posthog.schema import (- ErrorTrackingIssue,- ErrorTrackingIssueStatus,- ErrorTrackingQuery,- FilterLogicalOperator,- MaxErrorTrackingIssuePreview,- MaxErrorTrackingSearchResponse,- PropertyGroupFilter,- PropertyGroupFilterValue,-)--from ee.hogai.context.insight.query_executor import AssistantQueryExecutor-from ee.hogai.tool import MaxTool-from ee.hogai.tool_errors import MaxToolRetryableError--logger = structlog.get_logger(__name__)---SEARCH_QUERY_EXAMPLES = """-# Examples--## Status filtering-- "Show me active errors" → status: "active"-- "What resolved issues do we have?" → status: "resolved"-- "Show suppressed errors" → status: "suppressed"--## Text search-- "TypeError errors" → searchQuery: "TypeError"-- "Errors mentioning 'undefined'" → searchQuery: "undefined"-- "Find null pointer exceptions" → searchQuery: "null pointer"--## Date range-- "Errors from last 7 days" → dateRange: { date_from: "-7d" }-- "Issues since last week" → dateRange: { date_from: "-7d" }-- "Errors from December" → dateRange: { date_from: "2024-12-01", date_to: "2024-12-31" }--## Ordering-- "Most frequent errors" → orderBy: "occurrences", orderDirection: "DESC"-- "Newest errors first" → orderBy: "first_seen", orderDirection: "DESC"-- "Most recent errors" → orderBy: "last_seen", orderDirection: "DESC"-- "Errors affecting most users" → orderBy: "users", orderDirection: "DESC"--## Combined queries-- "Active TypeError errors from last week" → status: "active", searchQuery: "TypeError", dateRange: { date_from: "-7d" }-- "Top 10 most frequent resolved issues" → status: "resolved", orderBy: "occurrences", limit: 10-"""---class SearchErrorTrackingIssuesArgs(BaseModel):- query: ErrorTrackingQuery = Field(- description=dedent("""- User's question converted into an error tracking query.-- IMPORTANT: When the user asks to "show more" or "next page", you should pass the cursor- from the previous response to continue pagination. Do NOT modify the query parameters.""").strip()- + dedent(f"""-- # Query Structure-- ## status (optional)- Filter by issue status:- - "active": Currently active issues (default if not specified)- - "resolved": Issues marked as resolved- - "pending_release": Issues pending a release- - "suppressed": Suppressed/muted issues- - "archived": Archived issues- - "all": Show all issues regardless of status-- ## searchQuery (optional)- Free text search across:- - Exception type (e.g., "TypeError", "ReferenceError")- - Exception message- - Function names in stack traces- - File paths in stack traces-- ## dateRange (REQUIRED)- Time range for the query:- - date_from: Start date (relative like "-7d", "-30d" or absolute "2024-12-01")- - date_to: End date (null for "until now", or absolute date)-- Common relative formats:- - "-7d" = last 7 days- - "-30d" = last 30 days- - "-24h" = last 24 hours-- Note: All dates in results are displayed in UTC timezone.-- ## orderBy (REQUIRED)- Sort results by:- - "last_seen": When the issue was last seen (most recent activity)- - "first_seen": When the issue first appeared- - "occurrences": Total occurrence count- - "users": Number of affected users- - "sessions": Number of affected sessions- - "revenue": Revenue impact (if configured)-- ## orderDirection (optional)- - "DESC": Descending (default, highest/newest first)- - "ASC": Ascending (lowest/oldest first)-- ## limit (optional)- Number of results to return (1-100, default 50)-- ## filterGroup (optional)- Property filters for advanced filtering. Structure:- {{{{- "type": "AND" | "OR",- "values": [- {{{{- "type": "AND" | "OR",- "values": [- {{{{- "type": "event" | "person" | "session",- "key": "property_name",- "value": "value_or_array",- "operator": "exact" | "icontains" | "is_set" | ...- }}}}- ]- }}}}- ]- }}}}-- Common filter properties:- - event.$browser: Browser type- - event.$os: Operating system- - event.$device_type: Device type (Desktop, Mobile, Tablet)- - event.$current_url: URL where error occurred- - event.$lib: SDK/library used (web, posthog-python, posthog-node, etc.)-- ## filterTestAccounts (optional)- - true: Exclude internal/test accounts- - false: Include all accounts-- ## volumeResolution (REQUIRED)- Resolution for volume chart data. Use 1 for daily buckets.-- {SEARCH_QUERY_EXAMPLES}- """).strip()- )- cursor: str | None = Field(- default=None,- description="Pagination cursor from previous search results. Pass this to get the next page of results.",- )---class SearchErrorTrackingIssuesTool(MaxTool):- name: Literal["search_error_tracking_issues"] = "search_error_tracking_issues"- args_schema: type[BaseModel] = SearchErrorTrackingIssuesArgs- description: str = dedent("""- Search for error tracking issues based on criteria like status, search text, date range, and ordering.-- # When to use this tool:- - User asks to find, search, or list error tracking issues- - User asks about errors, exceptions, or issues in their application- - User wants to filter errors by status, date, frequency, or other criteria- - User asks questions like "show me recent errors" or "what are the most common issues"- - User asks to "show more" or see "next page" of results (use the cursor from previous results)-- # What this tool returns:- A formatted list of matching issues with their name, status, occurrence count, and other key metrics.- If more results are available, a cursor will be provided for pagination.- All timestamps are in UTC timezone.- """).strip()-- def get_required_resource_access(self):- return [("error_tracking", "viewer")]-- async def _arun_impl(- self, query: ErrorTrackingQuery, cursor: str | None = None- ) -> tuple[str, MaxErrorTrackingSearchResponse | None]:- # Ensure reasonable defaults to match dashboard behavior- if query.limit is None or query.limit <= 0:- query.limit = 50 # Match dashboard default- elif query.limit > 100:- query.limit = 100-- # Default to active issues if no status specified- if query.status is None:- query.status = ErrorTrackingIssueStatus.ACTIVE-- # Ensure query parameters match dashboard defaults- query.withAggregations = True- query.withFirstEvent = False- if query.filterTestAccounts is None:- query.filterTestAccounts = False- # Set empty filterGroup if not provided (matches dashboard behavior)- if query.filterGroup is None:- query.filterGroup = PropertyGroupFilter(- type=FilterLogicalOperator.AND_,- values=[PropertyGroupFilterValue(type=FilterLogicalOperator.AND_, values=[])],- )- # Set searchQuery to empty string if None (matches dashboard behavior)- if query.searchQuery is None:- query.searchQuery = ""-- # Apply cursor offset for pagination (default to 0 to match dashboard behavior)- current_offset = 0- if cursor:- try:- current_offset = int(cursor)- except ValueError:- logger.warning("Invalid pagination cursor", cursor=cursor)- query.offset = current_offset-- try:- utc_now = timezone.now().astimezone(UTC)- executor = AssistantQueryExecutor(self._team, utc_now, user=self._user)- query_results = await executor.aexecute_query(query)- except MaxToolRetryableError:- raise- except Exception as e:- capture_exception(e)- logger.exception("Error executing error tracking query", error=str(e))- return f"Error searching for issues: {e}", None-- # Extract results and pagination info from response- # Note: executor returns dict with extra caching fields, so we validate issues individually- raw_results = cast(list[dict], query_results.get("results", []))- results = [ErrorTrackingIssue.model_validate(r) for r in raw_results]- has_more_from_response = cast(bool, query_results.get("hasMore", False))-- # Use has_more from paginator response (based on ClickHouse results before Postgres filtering)- # Fall back to comparing result count vs limit if not available- has_more = has_more_from_response if has_more_from_response else len(results) >= query.limit- next_cursor = str(current_offset + query.limit) if has_more else None-- content = self._format_results(results, has_more)- issue_previews = self._build_issue_previews(results)-- filters = MaxErrorTrackingSearchResponse(- status=query.status,- search_query=query.searchQuery,- date_from=query.dateRange.date_from if query.dateRange else None,- date_to=query.dateRange.date_to if query.dateRange else None,- order_by=query.orderBy,- order_direction=query.orderDirection,- limit=query.limit,- has_more=has_more,- next_cursor=next_cursor,- issues=issue_previews,- )-- return content, filters-- def _build_issue_previews(self, results: list[ErrorTrackingIssue]) -> list[MaxErrorTrackingIssuePreview]:- """Build issue preview objects for frontend display."""- previews = []- for issue in results:- aggregations = issue.aggregations-- previews.append(- MaxErrorTrackingIssuePreview(- id=issue.id or "",- name=issue.name,- description=issue.description or self._extract_exception_message(issue),- status=issue.status or "unknown",- library=issue.library,- first_seen=self._format_date(issue.first_seen) or None,- last_seen=self._format_date(issue.last_seen) or None,- occurrences=int(aggregations.occurrences) if aggregations else 0,- users=int(aggregations.users) if aggregations else 0,- sessions=int(aggregations.sessions) if aggregations else 0,- )- )- return previews-- def _format_results(self, results: list[ErrorTrackingIssue], has_more: bool = False) -> str:- """Format query results as text output."""-- if not results:- return "No issues found matching your criteria."-- total_count = len(results)- if total_count == 1:- content = "Found 1 issue matching your criteria:\n\n"- else:- content = f"Found {total_count} issues matching your criteria:\n\n"-- # Show up to 10 issues in the response- for i, issue in enumerate(results[:10], 1):- content += self._format_issue(i, issue)-- if total_count > 10:- content += f"\n...and {total_count - 10} more issues in this batch"-- if has_more:- content += "\n\nMore issues are available. Ask me to show more if needed."-- return content-- def _format_issue(self, index: int, issue: ErrorTrackingIssue) -> str:- """Format a single issue for display."""- issue_id = issue.id or ""- name = issue.name or "Unnamed issue"- description = issue.description or self._extract_exception_message(issue)- status = issue.status or "unknown"- first_seen = issue.first_seen- last_seen = issue.last_seen-- aggregations = issue.aggregations- if aggregations:- occurrences = int(aggregations.occurrences or 0)- users = int(aggregations.users or 0)- sessions = int(aggregations.sessions or 0)- else:- occurrences = 0- users = 0- sessions = 0-- first_seen_str = self._format_date(first_seen)- last_seen_str = self._format_date(last_seen)-- lines = [f"{index}. {name}"]- if description:- # Truncate long descriptions- desc_display = description[:100] + "..." if len(description) > 100 else description- lines.append(f" {desc_display}")- lines.append(f" ID: {issue_id}")- lines.append(f" Status: {status} | Occurrences: {occurrences:,} | Users: {users:,} | Sessions: {sessions:,}")-- if first_seen_str or last_seen_str:- date_parts = []- if first_seen_str:- date_parts.append(f"First seen: {first_seen_str}")- if last_seen_str:- date_parts.append(f"Last seen: {last_seen_str}")- lines.append(f" {' | '.join(date_parts)}")-- # Empty line between issues for formatting- lines.append("")- return "\n".join(lines)-- def _extract_exception_message(self, issue: ErrorTrackingIssue) -> str | None:- """Extract exception message from first_event properties."""- first_event = issue.first_event- if not first_event:- return None-- properties = first_event.properties- if not properties:- return None-- try:- props = json.loads(properties)- exception_list = props.get("$exception_list", [])- if exception_list and len(exception_list) > 0:- first_exception = exception_list[0]- value = first_exception.get("value")- if value:- return value- except (json.JSONDecodeError, TypeError, KeyError, AttributeError):- pass-- return None-- def _format_date(self, date_value) -> str:- """Format a date value for display in UTC."""- if not date_value:- return ""- from datetime import datetime-- try:- if isinstance(date_value, datetime):- return date_value.strftime("%Y-%m-%d %H:%M UTC")- elif isinstance(date_value, str):- dt = datetime.fromisoformat(date_value.replace("Z", "+00:00"))- return dt.strftime("%Y-%m-%d %H:%M UTC")- except (ValueError, AttributeError):- return str(date_value) if date_value else ""- return str(date_value)diff --git a/products/error_tracking/backend/logic/tools/test/__init__.py b/products/error_tracking/backend/logic/tools/test/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/products/error_tracking/backend/max_tools.py b/products/error_tracking/backend/max_tools.pyindex 3536577fb7c4..07804d87706f 100644--- a/products/error_tracking/backend/max_tools.py+++ b/products/error_tracking/backend/max_tools.py@@ -1,15 +1,33 @@import reimport json-from typing import Optional+from datetime import UTC, datetime+from textwrap import dedent+from typing import Literal, Optional, cast+from django.utils import timezone++import structlogfrom langchain_core.messages import HumanMessage, SystemMessage+from posthoganalytics import capture_exceptionfrom pydantic import BaseModel, Field-from posthog.schema import ErrorTrackingIssueFilteringToolOutput+from posthog.schema import (+ ErrorTrackingIssue,+ ErrorTrackingIssueFilteringToolOutput,+ ErrorTrackingIssueStatus,+ ErrorTrackingQuery,+ FilterLogicalOperator,+ MaxErrorTrackingIssuePreview,+ MaxErrorTrackingSearchResponse,+ PropertyGroupFilter,+ PropertyGroupFilterValue,+)from ee.hogai.chat_agent.schema_generator.parsers import PydanticOutputParserException+from ee.hogai.context.insight.query_executor import AssistantQueryExecutorfrom ee.hogai.llm import MaxChatOpenAIfrom ee.hogai.tool import MaxTool+from ee.hogai.tool_errors import MaxToolRetryableErrorfrom .prompts import (ERROR_TRACKING_FILTER_INITIAL_PROMPT,@@ -18,6 +36,8 @@ from .prompts import (PREFER_FILTERS_PROMPT,)+logger = structlog.get_logger(__name__)+class UpdateIssueQueryArgs(BaseModel):change: str = Field(description="The specific change to be made to issue filters, briefly described.")@@ -107,3 +127,355 @@ class ErrorTrackingIssueFilteringTool(MaxTool):)return ErrorTrackingIssueFilteringToolOutput(**data)+++SEARCH_QUERY_EXAMPLES = """+# Examples++## Status filtering+- "Show me active errors" → status: "active"+- "What resolved issues do we have?" → status: "resolved"+- "Show suppressed errors" → status: "suppressed"++## Text search+- "TypeError errors" → searchQuery: "TypeError"+- "Errors mentioning 'undefined'" → searchQuery: "undefined"+- "Find null pointer exceptions" → searchQuery: "null pointer"++## Date range+- "Errors from last 7 days" → dateRange: { date_from: "-7d" }+- "Issues since last week" → dateRange: { date_from: "-7d" }+- "Errors from December" → dateRange: { date_from: "2024-12-01", date_to: "2024-12-31" }++## Ordering+- "Most frequent errors" → orderBy: "occurrences", orderDirection: "DESC"+- "Newest errors first" → orderBy: "first_seen", orderDirection: "DESC"+- "Most recent errors" → orderBy: "last_seen", orderDirection: "DESC"+- "Errors affecting most users" → orderBy: "users", orderDirection: "DESC"++## Combined queries+- "Active TypeError errors from last week" → status: "active", searchQuery: "TypeError", dateRange: { date_from: "-7d" }+- "Top 10 most frequent resolved issues" → status: "resolved", orderBy: "occurrences", limit: 10+"""+++class SearchErrorTrackingIssuesArgs(BaseModel):+ query: ErrorTrackingQuery = Field(+ description=dedent("""+ User's question converted into an error tracking query.++ IMPORTANT: When the user asks to "show more" or "next page", you should pass the cursor+ from the previous response to continue pagination. Do NOT modify the query parameters.""").strip()+ + dedent(f"""++ # Query Structure++ ## status (optional)+ Filter by issue status:+ - "active": Currently active issues (default if not specified)+ - "resolved": Issues marked as resolved+ - "pending_release": Issues pending a release+ - "suppressed": Suppressed/muted issues+ - "archived": Archived issues+ - "all": Show all issues regardless of status++ ## searchQuery (optional)+ Free text search across:+ - Exception type (e.g., "TypeError", "ReferenceError")+ - Exception message+ - Function names in stack traces+ - File paths in stack traces++ ## dateRange (REQUIRED)+ Time range for the query:+ - date_from: Start date (relative like "-7d", "-30d" or absolute "2024-12-01")+ - date_to: End date (null for "until now", or absolute date)++ Common relative formats:+ - "-7d" = last 7 days+ - "-30d" = last 30 days+ - "-24h" = last 24 hours++ Note: All dates in results are displayed in UTC timezone.++ ## orderBy (REQUIRED)+ Sort results by:+ - "last_seen": When the issue was last seen (most recent activity)+ - "first_seen": When the issue first appeared+ - "occurrences": Total occurrence count+ - "users": Number of affected users+ - "sessions": Number of affected sessions+ - "revenue": Revenue impact (if configured)++ ## orderDirection (optional)+ - "DESC": Descending (default, highest/newest first)+ - "ASC": Ascending (lowest/oldest first)++ ## limit (optional)+ Number of results to return (1-100, default 50)++ ## filterGroup (optional)+ Property filters for advanced filtering. Structure:+ {{{{+ "type": "AND" | "OR",+ "values": [+ {{{{+ "type": "AND" | "OR",+ "values": [+ {{{{+ "type": "event" | "person" | "session",+ "key": "property_name",+ "value": "value_or_array",+ "operator": "exact" | "icontains" | "is_set" | ...+ }}}}+ ]+ }}}}+ ]+ }}}}++ Common filter properties:+ - event.$browser: Browser type+ - event.$os: Operating system+ - event.$device_type: Device type (Desktop, Mobile, Tablet)+ - event.$current_url: URL where error occurred+ - event.$lib: SDK/library used (web, posthog-python, posthog-node, etc.)++ ## filterTestAccounts (optional)+ - true: Exclude internal/test accounts+ - false: Include all accounts++ ## volumeResolution (REQUIRED)+ Resolution for volume chart data. Use 1 for daily buckets.++ {SEARCH_QUERY_EXAMPLES}+ """).strip()+ )+ cursor: str | None = Field(+ default=None,+ description="Pagination cursor from previous search results. Pass this to get the next page of results.",+ )+++class SearchErrorTrackingIssuesTool(MaxTool):+ name: Literal["search_error_tracking_issues"] = "search_error_tracking_issues"+ args_schema: type[BaseModel] = SearchErrorTrackingIssuesArgs+ description: str = dedent("""+ Search for error tracking issues based on criteria like status, search text, date range, and ordering.++ # When to use this tool:+ - User asks to find, search, or list error tracking issues+ - User asks about errors, exceptions, or issues in their application+ - User wants to filter errors by status, date, frequency, or other criteria+ - User asks questions like "show me recent errors" or "what are the most common issues"+ - User asks to "show more" or see "next page" of results (use the cursor from previous results)++ # What this tool returns:+ A formatted list of matching issues with their name, status, occurrence count, and other key metrics.+ If more results are available, a cursor will be provided for pagination.+ All timestamps are in UTC timezone.+ """).strip()++ def get_required_resource_access(self):+ return [("error_tracking", "viewer")]++ async def _arun_impl(+ self, query: ErrorTrackingQuery, cursor: str | None = None+ ) -> tuple[str, MaxErrorTrackingSearchResponse | None]:+ # Ensure reasonable defaults to match dashboard behavior+ if query.limit is None or query.limit <= 0:+ query.limit = 50 # Match dashboard default+ elif query.limit > 100:+ query.limit = 100++ # Default to active issues if no status specified+ if query.status is None:+ query.status = ErrorTrackingIssueStatus.ACTIVE++ # Ensure query parameters match dashboard defaults+ query.withAggregations = True+ query.withFirstEvent = False+ if query.filterTestAccounts is None:+ query.filterTestAccounts = False+ # Set empty filterGroup if not provided (matches dashboard behavior)+ if query.filterGroup is None:+ query.filterGroup = PropertyGroupFilter(+ type=FilterLogicalOperator.AND_,+ values=[PropertyGroupFilterValue(type=FilterLogicalOperator.AND_, values=[])],+ )+ # Set searchQuery to empty string if None (matches dashboard behavior)+ if query.searchQuery is None:+ query.searchQuery = ""++ # Apply cursor offset for pagination (default to 0 to match dashboard behavior)+ current_offset = 0+ if cursor:+ try:+ current_offset = int(cursor)+ except ValueError:+ logger.warning("Invalid pagination cursor", cursor=cursor)+ query.offset = current_offset++ try:+ utc_now = timezone.now().astimezone(UTC)+ executor = AssistantQueryExecutor(self._team, utc_now, user=self._user)+ query_results = await executor.aexecute_query(query)+ except MaxToolRetryableError:+ raise+ except Exception as e:+ capture_exception(e)+ logger.exception("Error executing error tracking query", error=str(e))+ return f"Error searching for issues: {e}", None++ # Extract results and pagination info from response+ # Note: executor returns dict with extra caching fields, so we validate issues individually+ raw_results = cast(list[dict], query_results.get("results", []))+ results = [ErrorTrackingIssue.model_validate(r) for r in raw_results]+ has_more_from_response = cast(bool, query_results.get("hasMore", False))++ # Use has_more from paginator response (based on ClickHouse results before Postgres filtering)+ # Fall back to comparing result count vs limit if not available+ has_more = has_more_from_response if has_more_from_response else len(results) >= query.limit+ next_cursor = str(current_offset + query.limit) if has_more else None++ content = self._format_results(results, has_more)+ issue_previews = self._build_issue_previews(results)++ filters = MaxErrorTrackingSearchResponse(+ status=query.status,+ search_query=query.searchQuery,+ date_from=query.dateRange.date_from if query.dateRange else None,+ date_to=query.dateRange.date_to if query.dateRange else None,+ order_by=query.orderBy,+ order_direction=query.orderDirection,+ limit=query.limit,+ has_more=has_more,+ next_cursor=next_cursor,+ issues=issue_previews,+ )++ return content, filters++ def _build_issue_previews(self, results: list[ErrorTrackingIssue]) -> list[MaxErrorTrackingIssuePreview]:+ """Build issue preview objects for frontend display."""+ previews = []+ for issue in results:+ aggregations = issue.aggregations++ previews.append(+ MaxErrorTrackingIssuePreview(+ id=issue.id or "",+ name=issue.name,+ description=issue.description or self._extract_exception_message(issue),+ status=issue.status or "unknown",+ library=issue.library,+ first_seen=self._format_date(issue.first_seen) or None,+ last_seen=self._format_date(issue.last_seen) or None,+ occurrences=int(aggregations.occurrences) if aggregations else 0,+ users=int(aggregations.users) if aggregations else 0,+ sessions=int(aggregations.sessions) if aggregations else 0,+ )+ )+ return previews++ def _format_results(self, results: list[ErrorTrackingIssue], has_more: bool = False) -> str:+ """Format query results as text output."""++ if not results:+ return "No issues found matching your criteria."++ total_count = len(results)+ if total_count == 1:+ content = "Found 1 issue matching your criteria:\n\n"+ else:+ content = f"Found {total_count} issues matching your criteria:\n\n"++ # Show up to 10 issues in the response+ for i, issue in enumerate(results[:10], 1):+ content += self._format_issue(i, issue)++ if total_count > 10:+ content += f"\n...and {total_count - 10} more issues in this batch"++ if has_more:+ content += "\n\nMore issues are available. Ask me to show more if needed."++ return content++ def _format_issue(self, index: int, issue: ErrorTrackingIssue) -> str:+ """Format a single issue for display."""+ issue_id = issue.id or ""+ name = issue.name or "Unnamed issue"+ description = issue.description or self._extract_exception_message(issue)+ status = issue.status or "unknown"+ first_seen = issue.first_seen+ last_seen = issue.last_seen++ aggregations = issue.aggregations+ if aggregations:+ occurrences = int(aggregations.occurrences or 0)+ users = int(aggregations.users or 0)+ sessions = int(aggregations.sessions or 0)+ else:+ occurrences = 0+ users = 0+ sessions = 0++ first_seen_str = self._format_date(first_seen)+ last_seen_str = self._format_date(last_seen)++ lines = [f"{index}. {name}"]+ if description:+ # Truncate long descriptions+ desc_display = description[:100] + "..." if len(description) > 100 else description+ lines.append(f" {desc_display}")+ lines.append(f" ID: {issue_id}")+ lines.append(f" Status: {status} | Occurrences: {occurrences:,} | Users: {users:,} | Sessions: {sessions:,}")++ if first_seen_str or last_seen_str:+ date_parts = []+ if first_seen_str:+ date_parts.append(f"First seen: {first_seen_str}")+ if last_seen_str:+ date_parts.append(f"Last seen: {last_seen_str}")+ lines.append(f" {' | '.join(date_parts)}")++ # Empty line between issues for formatting+ lines.append("")+ return "\n".join(lines)++ def _extract_exception_message(self, issue: ErrorTrackingIssue) -> str | None:+ """Extract exception message from first_event properties."""+ first_event = issue.first_event+ if not first_event:+ return None++ properties = first_event.properties+ if not properties:+ return None++ try:+ props = json.loads(properties)+ exception_list = props.get("$exception_list", [])+ if exception_list and len(exception_list) > 0:+ first_exception = exception_list[0]+ value = first_exception.get("value")+ if value:+ return value+ except (json.JSONDecodeError, TypeError, KeyError, AttributeError):+ pass++ return None++ def _format_date(self, date_value) -> str:+ """Format a date value for display in UTC."""+ if not date_value:+ return ""+ try:+ if isinstance(date_value, datetime):+ return date_value.strftime("%Y-%m-%d %H:%M UTC")+ elif isinstance(date_value, str):+ dt = datetime.fromisoformat(date_value.replace("Z", "+00:00"))+ return dt.strftime("%Y-%m-%d %H:%M UTC")+ except (ValueError, AttributeError):+ return str(date_value) if date_value else ""+ return str(date_value)diff --git a/products/error_tracking/backend/logic/tools/test/test_search_issues.py b/products/error_tracking/backend/test/test_search_issues.pysimilarity index 99%rename from products/error_tracking/backend/logic/tools/test/test_search_issues.pyrename to products/error_tracking/backend/test/test_search_issues.pyindex 298d422f6329..1e9d9b931afe 100644--- a/products/error_tracking/backend/logic/tools/test/test_search_issues.py+++ b/products/error_tracking/backend/test/test_search_issues.py@@ -22,7 +22,7 @@ from posthog.schema import (MaxErrorTrackingSearchResponse,)-from products.error_tracking.backend.logic.tools.search_issues import SearchErrorTrackingIssuesTool+from products.error_tracking.backend.max_tools import SearchErrorTrackingIssuesToolfrom products.error_tracking.backend.models import (ErrorTrackingIssue,ErrorTrackingIssueFingerprintV2,diff --git a/products/error_tracking/turbo.json b/products/error_tracking/turbo.jsonindex 3e5f4580f6bb..9792401d39d4 100644--- a/products/error_tracking/turbo.json+++ b/products/error_tracking/turbo.json@@ -8,7 +8,11 @@"backend/routes.py","backend/sql.py","backend/embedding.py",- "backend/indexed_embedding.py"+ "backend/indexed_embedding.py",+ "backend/hogql_queries/**",+ "backend/max_tools.py",+ "backend/temporal/**",+ "backend/tasks/**"],"outputs": [],"cache": truediff --git a/products/legal_documents/turbo.json b/products/legal_documents/turbo.jsonindex e16d4eabe6e9..89467ab134d4 100644--- a/products/legal_documents/turbo.json+++ b/products/legal_documents/turbo.json@@ -2,7 +2,7 @@"extends": ["//"],"tasks": {"backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],+ "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py", "backend/tasks/**"],"outputs": [],"cache": true}diff --git a/products/metrics/backend/facade/queries.py b/products/metrics/backend/facade/queries.pyindex 55d772864a5a..de9cdc0de13f 100644--- a/products/metrics/backend/facade/queries.py+++ b/products/metrics/backend/facade/queries.py@@ -6,6 +6,6 @@ lazily at the dispatch site — this module pulls in HogQL machinery that muststay off the `django.setup()` path."""-from products.metrics.backend.metrics_query_runner import MetricsQueryRunner+from products.metrics.backend.hogql_queries.metrics_query_runner import MetricsQueryRunner__all__ = ["MetricsQueryRunner"]diff --git a/products/metrics/backend/metrics_query_runner.py b/products/metrics/backend/hogql_queries/metrics_query_runner.pysimilarity index 100%rename from products/metrics/backend/metrics_query_runner.pyrename to products/metrics/backend/hogql_queries/metrics_query_runner.pydiff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.pyindex 477867d2a8cb..7bba65be9ecd 100644--- a/products/metrics/backend/tests/test_metrics_query_runner.py+++ b/products/metrics/backend/tests/test_metrics_query_runner.py@@ -21,7 +21,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.rbac.user_access_control import UserAccessControlErrorfrom products.metrics.backend.facade.enums import AttributeScope, FilterOp, MetricAggregation, MetricType-from products.metrics.backend.metrics_query_runner import MetricsQueryRunner+from products.metrics.backend.hogql_queries.metrics_query_runner import MetricsQueryRunnerfrom products.metrics.backend.tests._seeder import seed_metricfrom ee.models.rbac.access_control import AccessControldiff --git a/products/metrics/turbo.json b/products/metrics/turbo.jsonindex e16d4eabe6e9..79170fa7526d 100644--- a/products/metrics/turbo.json+++ b/products/metrics/turbo.json@@ -2,7 +2,13 @@"extends": ["//"],"tasks": {"backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],+ "inputs": [+ "backend/facade/**",+ "backend/presentation/**",+ "backend/routes.py",+ "backend/hogql_queries/**",+ "backend/tasks/**"+ ],"outputs": [],"cache": true}diff --git a/products/stamphog/turbo.json b/products/stamphog/turbo.jsonindex e16d4eabe6e9..bd3cdcbaff18 100644--- a/products/stamphog/turbo.json+++ b/products/stamphog/turbo.json@@ -2,7 +2,13 @@"extends": ["//"],"tasks": {"backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],+ "inputs": [+ "backend/facade/**",+ "backend/presentation/**",+ "backend/routes.py",+ "backend/tasks/**",+ "backend/temporal/**"+ ],"outputs": [],"cache": true}diff --git a/products/streamlit_apps/backend/facade/api.py b/products/streamlit_apps/backend/facade/api.pyindex 4b6a7df145c9..c1e3f596fda8 100644--- a/products/streamlit_apps/backend/facade/api.py+++ b/products/streamlit_apps/backend/facade/api.py@@ -15,12 +15,8 @@ from posthog.models.user import Userfrom posthog.storage import object_storagefrom products.streamlit_apps.backend.facade import contracts-from products.streamlit_apps.backend.logic.app_runtime import (- AppRuntimeConcurrencyError,- AppRuntimeError,- AppRuntimeService,- sync_sandbox_status,-)+from products.streamlit_apps.backend.facade.contracts import AppRuntimeConcurrencyError, AppRuntimeError+from products.streamlit_apps.backend.logic.app_runtime import AppRuntimeService, sync_sandbox_statusfrom products.streamlit_apps.backend.logic.bridge import execute_bridge_queryfrom products.streamlit_apps.backend.logic.oauth import (create_streamlit_access_token,diff --git a/products/streamlit_apps/backend/facade/contracts.py b/products/streamlit_apps/backend/facade/contracts.pyindex d179e6e6d726..08d3d90920bd 100644--- a/products/streamlit_apps/backend/facade/contracts.py+++ b/products/streamlit_apps/backend/facade/contracts.py@@ -18,6 +18,16 @@ from uuid import UUIDfrom pydantic.dataclasses import dataclass+class AppRuntimeError(Exception):+ pass+++class AppRuntimeConcurrencyError(AppRuntimeError):+ """Raised when a lifecycle action collides with one already in flight."""++ pass++@dataclass(frozen=True)class StreamlitAppUserInfo:"""Lightweight user info for display purposes. Mirrors core UserBasicSerializer."""diff --git a/products/streamlit_apps/backend/logic/app_runtime.py b/products/streamlit_apps/backend/logic/app_runtime.pyindex 702b52ed721b..f4729ea6fa90 100644--- a/products/streamlit_apps/backend/logic/app_runtime.py+++ b/products/streamlit_apps/backend/logic/app_runtime.py@@ -17,6 +17,7 @@ from posthog.cloud_utils import is_cloudfrom posthog.ph_client import PH_EU_API_KEY, PH_EU_HOST, PH_US_API_KEY, PH_US_HOSTfrom posthog.utils import get_instance_region+from products.streamlit_apps.backend.facade.contracts import AppRuntimeConcurrencyError, AppRuntimeErrorfrom products.streamlit_apps.backend.logic.oauth import create_sandbox_bridge_token, get_streamlit_oauth_appfrom products.streamlit_apps.backend.logic.zip_validator import MAX_UNCOMPRESSED_SIZE, is_safe_zip_pathfrom products.streamlit_apps.backend.models import (@@ -53,16 +54,6 @@ RESTART_COUNT_STABILITY_SECONDS = 5 * 60TTL_TIMEOUT_LAST_ERROR = "Sandbox terminated (TTL timeout)"-class AppRuntimeError(Exception):- pass---class AppRuntimeConcurrencyError(AppRuntimeError):- """Raised when a lifecycle action collides with one already in flight."""-- pass--def _get_sandbox_callback_url() -> str:"""URL that sandboxes use to call back to PostHog (OAuth introspect, bridge queries).diff --git a/products/streamlit_apps/backend/tasks/tasks.py b/products/streamlit_apps/backend/tasks/tasks.pyindex eee2cd64ab5c..4b16074bd634 100644--- a/products/streamlit_apps/backend/tasks/tasks.py+++ b/products/streamlit_apps/backend/tasks/tasks.py@@ -48,7 +48,8 @@ def run_streamlit_app_lifecycle(app_id: str, action: Literal["start", "restart"]"""Celery entry point for both start and restart."""from posthog.storage import object_storage- from products.streamlit_apps.backend.logic.app_runtime import AppRuntimeConcurrencyError, AppRuntimeService+ from products.streamlit_apps.backend.facade.contracts import AppRuntimeConcurrencyError+ from products.streamlit_apps.backend.logic.app_runtime import AppRuntimeServicefrom products.streamlit_apps.backend.models import StreamlitApptry:diff --git a/products/streamlit_apps/turbo.json b/products/streamlit_apps/turbo.jsonindex e16d4eabe6e9..89467ab134d4 100644--- a/products/streamlit_apps/turbo.json+++ b/products/streamlit_apps/turbo.json@@ -2,7 +2,7 @@"extends": ["//"],"tasks": {"backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],+ "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py", "backend/tasks/**"],"outputs": [],"cache": true}diff --git a/products/tasks/turbo.json b/products/tasks/turbo.jsondeleted file mode 100644index e16d4eabe6e9..000000000000--- a/products/tasks/turbo.json+++ /dev/null@@ -1,10 +0,0 @@-{- "extends": ["//"],- "tasks": {- "backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],- "outputs": [],- "cache": true- }- }-}diff --git a/products/visual_review/turbo.json b/products/visual_review/turbo.jsonindex e16d4eabe6e9..89467ab134d4 100644--- a/products/visual_review/turbo.json+++ b/products/visual_review/turbo.json@@ -2,7 +2,7 @@"extends": ["//"],"tasks": {"backend:contract-check": {- "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py"],+ "inputs": ["backend/facade/**", "backend/presentation/**", "backend/routes.py", "backend/tasks/**"],"outputs": [],"cache": true}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_ci_core_coupled_sources.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_ci_core_coupled_sources.pyindex b02994256475..506c4d63a220 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_ci_core_coupled_sources.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_ci_core_coupled_sources.py@@ -131,9 +131,17 @@ def _core_consumed_facade_symbols(tree: ast.AST) -> set[str]:return found-def _contract_covered_sources(root: Path) -> set[str]:- turbo = json.loads((root / "products" / "warehouse_sources" / "turbo.json").read_text())- inputs = turbo["tasks"]["backend:contract-check"]["inputs"]+def _contract_covered_sources(root: Path) -> set[str] | None:+ """Vendor dirs the narrowed contract-check inputs watch, or None when the product has no+ narrowing override — turbo then falls back to watching all of backend/, so every vendor is+ covered and there is nothing to enumerate."""+ turbo_path = root / "products" / "warehouse_sources" / "turbo.json"+ if not turbo_path.exists():+ return None+ turbo = json.loads(turbo_path.read_text())+ inputs = turbo.get("tasks", {}).get("backend:contract-check", {}).get("inputs")+ if not inputs:+ return Nonecovered = {rest.split("/")[0].removesuffix(".py")for entry in inputs@@ -167,6 +175,8 @@ def test_core_facade_coupled_sources_are_covered_by_contract_check():coupled_vendors = {symbol_to_vendor[s] for s in consumed if s in symbol_to_vendor}covered = _contract_covered_sources(root)+ if covered is None:+ returnmissing = coupled_vendors - coveredassert not missing, (f"Core/CorePOE reaches warehouse sources {sorted(missing)} through the facade, but they are "diff --git a/products/warehouse_sources/turbo.json b/products/warehouse_sources/turbo.jsondeleted file mode 100644index 9a5ee6ad0979..000000000000--- a/products/warehouse_sources/turbo.json+++ /dev/null@@ -1,33 +0,0 @@-{- "extends": ["//"],- "tasks": {- "backend:contract-check": {- "inputs": [- "backend/facade/**",- "backend/models/**",- "backend/temporal/data_imports/sources/generated_configs.py",- "backend/temporal/data_imports/sources/common/**",- "backend/temporal/data_imports/sources/google_search_console/**",- "backend/temporal/data_imports/sources/mysql/**",- "backend/temporal/data_imports/sources/postgres/**",- "backend/temporal/data_imports/sources/redshift/**",- "backend/temporal/data_imports/sources/salesforce/**",- "backend/temporal/data_imports/sources/snowflake/**",- "backend/temporal/data_imports/sources/stripe/**",- "!backend/temporal/data_imports/sources/common/rest_source/**",- "!backend/temporal/data_imports/sources/common/test/**",- "!backend/temporal/data_imports/sources/common/sql/tests/**",- "!backend/temporal/data_imports/sources/google_search_console/tests/**",- "!backend/temporal/data_imports/sources/mysql/tests/**",- "!backend/temporal/data_imports/sources/postgres/cdc/tests/**",- "!backend/temporal/data_imports/sources/postgres/test_postgres.py",- "!backend/temporal/data_imports/sources/redshift/tests/**",- "!backend/temporal/data_imports/sources/salesforce/test/**",- "!backend/temporal/data_imports/sources/snowflake/tests/**",- "!backend/temporal/data_imports/sources/stripe/tests/**"- ],- "outputs": [],- "cache": true- }- }-}diff --git a/tools/hogli-commands/hogli_commands/product/ast_helpers.py b/tools/hogli-commands/hogli_commands/product/ast_helpers.pyindex de4ef1842864..3100619353e6 100644--- a/tools/hogli-commands/hogli_commands/product/ast_helpers.py+++ b/tools/hogli-commands/hogli_commands/product/ast_helpers.py@@ -114,9 +114,92 @@ def has_any_function_defs(file_path: Path) -> bool:tree = ast_parse_safe(file_path)if not tree:return False+ return tree_has_top_level_functions(tree)+++def tree_has_top_level_functions(tree: ast.Module) -> bool:+ """True if the module has any top-level function definition (a re-export module has none)."""return any(isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) for node in ast.iter_child_nodes(tree))+def _is_type_checking_guard(node: ast.stmt) -> bool:+ """True for an `if TYPE_CHECKING:` / `if typing.TYPE_CHECKING:` block header."""+ if not isinstance(node, ast.If):+ return False+ test = node.test+ return (isinstance(test, ast.Name) and test.id == "TYPE_CHECKING") or (+ isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING"+ )+++def module_dunder_all(tree: ast.Module) -> set[str] | None:+ """The names in a module-level `__all__` list/tuple of string literals, or None if absent.++ None (no __all__) and an empty set (explicitly empty __all__) are meaningfully different to+ callers, so they aren't collapsed. A non-literal `__all__` (e.g. `sorted(_LAZY)`) reads as+ None — its contents can't be known statically."""+ for node in ast.iter_child_nodes(tree):+ if not isinstance(node, ast.Assign):+ continue+ if not any(isinstance(t, ast.Name) and t.id == "__all__" for t in node.targets):+ continue+ if not isinstance(node.value, (ast.List, ast.Tuple)):+ return None+ return {e.value for e in node.value.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)}+ return None+++def module_level_import_froms(tree: ast.Module) -> list[tuple[int, str | None, list[tuple[str, str | None]]]]:+ """Every module-level `from ... import ...` as (level, module, [(name, asname)]).++ asname is None when no alias is given; `import Foo as Foo` yields ("Foo", "Foo") so callers+ can tell the explicit self-alias re-export idiom apart from a plain import. Skips imports+ nested in functions/classes (not module bindings) and inside `if TYPE_CHECKING:` blocks+ (type-only, nothing crosses at runtime)."""+ results: list[tuple[int, str | None, list[tuple[str, str | None]]]] = []+ for node in ast.iter_child_nodes(tree):+ if _is_type_checking_guard(node):+ continue+ if isinstance(node, ast.ImportFrom):+ results.append((node.level, node.module, [(alias.name, alias.asname) for alias in node.names]))+ return results+++def lazy_reexport_map(tree: ast.Module) -> dict[str, str]:+ """PEP 562 lazy re-export map: {exported name -> dotted source module}.++ Reads module-level dict literals whose values are all string module paths (the+ `_LAZY`/`_MODULES` convention), but only when the module also defines a top-level+ `__getattr__` — the hook that turns such a dict into real re-exports. Returns the+ merged mapping across all qualifying dicts."""+ has_getattr = any(+ isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == "__getattr__"+ for node in ast.iter_child_nodes(tree)+ )+ if not has_getattr:+ return {}+ mapping: dict[str, str] = {}+ for node in ast.iter_child_nodes(tree):+ if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Dict):+ continue+ entries: dict[str, str] = {}+ valid = bool(node.value.keys)+ for key, value in zip(node.value.keys, node.value.values):+ if (+ isinstance(key, ast.Constant)+ and isinstance(key.value, str)+ and isinstance(value, ast.Constant)+ and isinstance(value.value, str)+ ):+ entries[key.value] = value.value+ else:+ valid = False+ break+ if valid:+ mapping.update(entries)+ return mapping++def get_public_function_names(file_path: Path) -> list[str]:"""Return names of public top-level and class-level functions/methods (not nested)."""tree = ast_parse_safe(file_path)diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex e4e1ee67e51a..68d3a7e40e33 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -24,6 +24,7 @@ from .isolation import (has_tach_interface,is_isolated_product,iter_interface_blocks as _iter_interface_blocks,+ location_input_glob,names_from_pattern as _names_from_pattern,pattern_targets_public_surface as _pattern_targets_public_surface,routes_in_turbo_inputs,@@ -361,6 +362,9 @@ def _contract_check_withheld_note(status: IsolationStatus) -> str | None:Surfaced on a passing single-product lint so a reader sees the decision, not justits silent absence. Returns None when there's nothing meaningful to explain."""+ if status.facade_leaks:+ classes = ", ".join(sorted({v.class_name for v in status.facade_leaks}))+ return f"facade hands out non-contract class(es) ({classes}) — not soundly isolated (see § Wiring couplings)"if status.deferred_count > 0 and status.has_legacy_leaks:return f"legacy interface leaks + {status.deferred_count} presentation bypass(es) still open"if status.deferred_count > 0:@@ -399,7 +403,13 @@ class PackageJsonScriptsCheck(ProductCheck):# reward for finishing — it can't be enabled until the wave empties them.status = ctx.isolation_status()needs_contract_check = status.eligible_for_isolated_tests- required = ["backend:test"] + (["backend:contract-check"] if needs_contract_check else [])+ # The wiring gate also withholds the skip script: a facade that still hands out unsanctioned+ # classes can't soundly narrow, so don't nag it to carry 'backend:contract-check' (the script+ # would be inert, and IsolationChainCheck blocks the narrowing that would make it bite). The+ # absence check below still keys on plain eligibility, so the five products that deliberately+ # keep script+broad while un-narrowed aren't told to drop it.+ require_contract_check_script = needs_contract_check and not status.facade_leaks+ required = ["backend:test"] + (["backend:contract-check"] if require_contract_check_script else [])for script in required:if script not in scripts:result.lines.append(f"✗ missing '{script}'")@@ -429,7 +439,12 @@ class PackageJsonScriptsCheck(ProductCheck):)# --- surface the withholding decision (single-product view only; keep the CI sweep quiet) ---- if ctx.detailed and ctx.is_isolated and not needs_contract_check and "backend:contract-check" not in scripts:+ if (+ ctx.detailed+ and ctx.is_isolated+ and not require_contract_check_script+ and "backend:contract-check" not in scripts+ ):note = _contract_check_withheld_note(status)if note:result.lines.append(f"ℹ contract-check skip withheld — {note}")@@ -643,6 +658,7 @@ class IsolationChainCheck(ProductCheck):has_tach = status.has_tach_interfacehas_script = status.has_contract_check_scripthas_narrowed = status.has_narrowed_turbo+ facade_violations = status.facade_leaksresult = CheckResult()@@ -677,6 +693,30 @@ class IsolationChainCheck(ProductCheck):"a real facade should convert models to contracts, not just re-export")+ # The wiring-doctrine gate. Facade class re-exports from a non-garage module gate NARROWING,+ # not the script: while a product is un-narrowed the skip is inert (everything is watched), so+ # a leak there is guidance, not breakage. Once narrowed, the same leak means core can reach an+ # unsanctioned class the suite may not re-test — a hard error. See products/architecture.md+ # § Wiring couplings.+ if facade_violations:+ detail = "; ".join(+ f"{v.class_name} (from {v.source_path}, via facade/{v.facade_module})" for v in facade_violations+ )+ remedies = (+ "move it to a garage (backend/hogql_queries/, backend/max_tools.py, backend/temporal/, "+ "backend/tasks.py) if it implements a core-owned base; move it to facade/contracts.py "+ "if it's a data/error type; or drop the turbo.json narrowing to watch everything"+ )+ if has_narrowed:+ result.issues.append(+ f"facade re-exports class(es) from outside the wiring locations: {detail} — {remedies}"+ )+ elif has_script:+ result.warnings.append(+ f"facade re-exports class(es) from outside the wiring locations: {detail}. The skip is "+ f"inert while un-narrowed, but narrowing is blocked until this is fixed — {remedies}"+ )+# Earned but not turned on: a fully sealed, eligible product that already carries# 'backend:contract-check' (real facade, tach interface, no legacy leaks, presentation# wave emptied). Without a turbo.json narrowing its inputs to facade/presentation, that@@ -684,8 +724,14 @@ class IsolationChainCheck(ProductCheck):# re-runs the full Django suite — the skip is inert. Force the narrowing so READY# products land on ON. Gating on has_script keeps this distinct from# PackageJsonScriptsCheck, which is what nags a still-eligible product to add the script.+ # Suppressed when the facade still hands out unsanctioned classes: narrowing would be+ # rejected by the gate above, so nagging toward it is counterproductive — say what blocks it.needs_turn_on = (- has_script and status.eligible_for_isolated_tests and status.externally_sealed and not has_narrowed+ has_script+ and status.eligible_for_isolated_tests+ and status.externally_sealed+ and not has_narrowed+ and not facade_violations)if needs_turn_on:result.issues.append(@@ -693,8 +739,12 @@ class IsolationChainCheck(ProductCheck):"'backend:contract-check', but turbo.json does not narrow contract-check inputs to ""facade/presentation — the skip is inert (every change still re-runs the full Django "'suite). Add a turbo.json narrowing inputs to ["backend/facade/**", '- '"backend/presentation/**"] to turn the skip on'+ '"backend/presentation/**"] plus any wiring locations the product has '+ "(backend/tasks/**, backend/temporal/**, …) to turn the skip on")+ # When needs_turn_on is suppressed purely because of a facade violation (the other four+ # conjuncts hold), the facade_violations warning above already explains what blocks narrowing,+ # so there's nothing more to say here — the nag is silently withheld, not replaced.# Watching the route registration: routes.py is the product's route-registration entry# point (public API surface, imported by core to assemble the router), but it lives at@@ -726,6 +776,27 @@ class IsolationChainCheck(ProductCheck):f"would skip the Django suite. Add the matching input(s) ({globs}) to keep the skip sound")+ # Watching the wiring garages: a garage the product has must stay in the contract-check+ # inputs, or a change to a query runner / Max tool / Temporal defn / Celery task the facade+ # wires would skip the Django suite. Mirrors routes_unwatched, presence-based.+ if has_narrowed and status.unwatched_garages:+ globs = ", ".join(location_input_glob(g) for g in status.unwatched_garages)+ result.issues.append(+ "turbo.json narrows contract-check inputs but omits the wiring location(s) "+ f"{', '.join(status.unwatched_garages)} — implementations core registers and drives live there, "+ f"so a change to them would skip the Django suite. Add the matching input(s) ({globs})"+ )++ # Watching the carve-out modules: a sanctioned model-registry carve-out crosses the facade by+ # class identity, so its defining module must re-run the suite on change like any wiring.+ if has_narrowed and status.uncovered_carveout_modules:+ globs = ", ".join(location_input_glob(m) for m in status.uncovered_carveout_modules)+ result.issues.append(+ "turbo.json narrows contract-check inputs but omits the carve-out module(s) "+ f"{', '.join(status.uncovered_carveout_modules)} — the class crosses the facade for a core "+ f"registry keyed by class identity, so a change must re-run the suite. Add the matching input(s) ({globs})"+ )+# Guarding against marker abuse: the permanent-interface marker is only legitimate for# modules core depends on outside the import graph (ClickHouse DDL in a frozen migration or# the schema registry). Without this check the marker is mechanically unrestricted — a@@ -752,9 +823,10 @@ class IsolationChainCheck(ProductCheck):# fixed, so it wins; the co-firing mismatch issues still print in the lint output.# An unqualified permanent exposure is a defect in the tach.toml marker itself, so point# there; it takes precedence because it's the most fundamental of these issues.+ turbo_omission = has_narrowed and (status.unwatched_garages or status.uncovered_carveout_modules)if status.unqualified_permanent_exposures:result.file = "tach.toml"- elif needs_turn_on or routes_unwatched:+ elif needs_turn_on or routes_unwatched or turbo_omission:result.file = f"products/{ctx.name}/turbo.json"else:result.file = f"products/{ctx.name}/backend/facade/api.py"diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex a731d71e6e3d..dfaa6f5be586 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -20,6 +20,7 @@ is the reward for finishing, which is why it can't turn on while either seal isfrom __future__ import annotationsimport re+import astimport jsonimport tomllibimport functools@@ -27,7 +28,15 @@ from collections.abc import Iteratorfrom dataclasses import dataclassfrom pathlib import Path-from .ast_helpers import ast_parse_safe, get_imported_module_names, has_any_function_defs+from .ast_helpers import (+ ast_parse_safe,+ get_imported_module_names,+ has_any_function_defs,+ lazy_reexport_map,+ module_dunder_all,+ module_level_import_froms,+ tree_has_top_level_functions,+)from .paths import REPO_ROOT, TACH_TOML, get_tach_block# ---------------------------------------------------------------------------@@ -261,18 +270,28 @@ def contract_check_inputs(product_dir: Path) -> list[str]:# A contract-check input is "on the public surface" when it targets the facade, the presentation# layer, or the routes registration module. Anchored on the path separator so a near-miss like-# backend/facade_legacy/** can't pass; removeprefix (not lstrip, which strips a char set) trims-# only a literal "./" so a "../escape/**" can't be normalized into a surface path.-_FACADE_PRESENTATION_PREFIXES = ("backend/facade/", "backend/presentation/")+# backend/facade_legacy/** can't pass.+_FACADE_PREFIX = "backend/facade/"+_FACADE_PRESENTATION_PREFIXES = (_FACADE_PREFIX, "backend/presentation/")_ROUTES_PREFIXES = ("backend/routes.py", "backend/routes/")+# The wiring locations ("garages"). A garage prefix is either a directory (trailing slash) or a+# single-file module; a class re-exported from one of these is accepted wiring, everything else is+# a leak. See products/architecture.md § Wiring couplings.+GARAGE_PREFIXES: tuple[str, ...] = (+ "backend/hogql_queries/",+ "backend/max_tools.py",+ "backend/temporal/",+ "backend/tasks.py",+ "backend/tasks/",+)-def _input_targets_facade_or_presentation(glob: str) -> bool:- return glob.removeprefix("./").startswith(_FACADE_PRESENTATION_PREFIXES)--def _input_targets_surface(glob: str) -> bool:- return glob.removeprefix("./").startswith(_FACADE_PRESENTATION_PREFIXES + _ROUTES_PREFIXES)+def _glob_targets(glob: str, prefixes: tuple[str, ...]) -> bool:+ """Anchored prefix test for a contract-check input glob. removeprefix (not lstrip, which strips+ a char set) trims only a literal './' so a '../escape/**' can't be normalized into an accepted+ path."""+ return glob.removeprefix("./").startswith(prefixes)def _module_input_prefixes(module: str) -> tuple[str, ...]:@@ -284,26 +303,68 @@ def _module_input_prefixes(module: str) -> tuple[str, ...]:return (f"{path}.py", f"{path}/")-def _input_targets_permanent(glob: str, permanent_modules: frozenset[str]) -> bool:- normalized = glob.removeprefix("./")- return any(normalized.startswith(_module_input_prefixes(m)) for m in permanent_modules)+def location_input_glob(location: str) -> str:+ """A backend-relative location -> the turbo input glob that watches it.++ 'backend/tasks/' -> 'backend/tasks/**'; a single-file location stays itself."""+ return f"{location.rstrip('/')}/**" if location.endswith("/") else location-def has_narrowed_turbo_inputs(product_dir: Path, permanent_modules: frozenset[str] = frozenset()) -> bool:+def has_narrowed_turbo_inputs(+ product_dir: Path,+ permanent_modules: frozenset[str] = frozenset(),+ carveout_modules: frozenset[str] = frozenset(),+) -> bool:"""True only when contract-check inputs are confined to the public surface AND at least onetargets facade/presentation. A broad glob like backend/** alongside a facade entry keeps theskip inert, and a routes-only narrowing isn't a real contract surface — both are rejected.Negated globs ('!...') are excluded from the surface test.- Permanently-exposed modules (permanent_modules) count as extended surface: a product may- list them without forfeiting the narrowing, since core depends on them outside the import- graph and they must re-run the suite on change (see uncovered_permanent_modules)."""+ Permanently-exposed modules, garage wiring locations, and carve-out modules all count as+ extended surface: a product may list them without forfeiting the narrowing, since core depends+ on each outside the plain facade->contracts channel and they must re-run the suite on change+ (see uncovered_permanent_modules, unwatched_garages, and the carve-out coverage check)."""inputs = [i for i in contract_check_inputs(product_dir) if not i.startswith("!")]if not inputs:return False- return all(_input_targets_surface(i) or _input_targets_permanent(i, permanent_modules) for i in inputs) and any(- _input_targets_facade_or_presentation(i) for i in inputs+ permanent_prefixes = tuple(p for m in permanent_modules for p in _module_input_prefixes(m))+ accepted = (+ _FACADE_PRESENTATION_PREFIXES+ + _ROUTES_PREFIXES+ + GARAGE_PREFIXES+ + permanent_prefixes+ + tuple(carveout_modules))+ return all(_glob_targets(i, accepted) for i in inputs) and any(+ _glob_targets(i, _FACADE_PRESENTATION_PREFIXES) for i in inputs+ )+++def _input_covers(input_glob: str, accepted: str) -> bool:+ """A directory location (trailing slash) is covered by any input inside it; a single-file+ location only by an exact input — backend/tasks.py.bak must not count as watching+ backend/tasks.py."""+ if accepted.endswith("/"):+ return input_glob.startswith(accepted)+ return input_glob == accepted+++def _uncovered_locations(product_dir: Path, targets_to_prefixes: dict[str, tuple[str, ...]]) -> set[str]:+ """Targets whose accepted input forms match no narrowed contract-check input.++ Empty when the product has no narrowing override — everything is watched, so nothing is+ uncovered. Shared by the permanent-exposure, garage, and carve-out coverage checks: same+ anchored predicate everywhere, the convention is location-level, no glob simulation."""+ if not targets_to_prefixes:+ return set()+ inputs = [i.removeprefix("./") for i in contract_check_inputs(product_dir) if not i.startswith("!")]+ if not inputs:+ return set()+ return {+ target+ for target, prefixes in targets_to_prefixes.items()+ if not any(_input_covers(i, p) for i in inputs for p in prefixes)+ }def uncovered_permanent_modules(product_dir: Path, permanent_modules: frozenset[str]) -> set[str]:@@ -312,10 +373,7 @@ def uncovered_permanent_modules(product_dir: Path, permanent_modules: frozenset[Each such module is a non-import channel into core; if turbo.json doesn't re-run the suiteon its change, the skip is unsound. IsolationChainCheck turns a non-empty result into ablocking issue, mirroring the routes-watching rule."""- if not permanent_modules:- return set()- inputs = [i.removeprefix("./") for i in contract_check_inputs(product_dir) if not i.startswith("!")]- return {m for m in permanent_modules if not any(i.startswith(_module_input_prefixes(m)) for i in inputs)}+ return _uncovered_locations(product_dir, {m: _module_input_prefixes(m) for m in permanent_modules})# ---------------------------------------------------------------------------@@ -385,11 +443,270 @@ def routes_in_turbo_inputs(product_dir: Path) -> bool:backend/routes/ package. Anchored and negation-aware, so a glob that merely contains 'routes',or a negated exclusion like !backend/routes.py, doesn't falsely count the routes module aswatched (without it, a routes-only change is invisible to the skip and runs no Django suite)."""- return any(- i.removeprefix("./").startswith(_ROUTES_PREFIXES)- for i in contract_check_inputs(product_dir)- if not i.startswith("!")- )+ return any(_glob_targets(i, _ROUTES_PREFIXES) for i in contract_check_inputs(product_dir) if not i.startswith("!"))+++# ---------------------------------------------------------------------------+# Wiring couplings — the facade's class-crossing surface+# ---------------------------------------------------------------------------+#+# A class only crosses the boundary soundly if it implements a core-owned base and lives in a+# wiring location ("garage", GARAGE_PREFIXES above) core keeps in the contract-check inputs. These+# checks catch the two ways that breaks: a facade re-exporting a class from somewhere that ISN'T a+# garage, and a garage that exists but isn't watched. See products/architecture.md § Wiring couplings.+++# Sanctioned model-registry carve-outs, keyed (product, class). These model classes cross the+# facade for a core registry keyed by class identity (team-extension and the file-system unfiled+# registry) — the only classes allowed to cross that aren't wiring implementations. They are never+# flagged, but a narrowed product must still keep the defining module in its contract-check inputs.+# Bar for adding an entry: there must be a core registry keyed by class identity that needs it, AND+# a matching amendment to products/architecture.md § Wiring couplings naming the registry.+CARVE_OUTS: frozenset[tuple[str, str]] = frozenset(+ {+ ("customer_analytics", "TeamCustomerAnalyticsConfig"),+ ("tasks", "Task"),+ }+)+++@dataclass(frozen=True)+class FacadeClassImport:+ """A class a facade module re-exports from a product-internal, non-garage module."""++ facade_module: str # e.g. "queries.py"+ class_name: str # e.g. "MetricsQueryRunner"+ source_path: str # backend-relative, e.g. "backend/metrics_query_runner.py"+++def _product_backend_root(backend_dir: Path) -> str:+ """The product's own backend package as a dotted prefix, e.g. 'products.metrics.backend'."""+ return f"products.{backend_dir.parent.name}.backend"+++def _module_package_parts(source_path: str) -> list[str]:+ """The package a module belongs to, as backend-relative parts, for resolving relative imports.++ 'backend/facade/queries.py' -> ['facade'] (its container); 'backend/logic/matrix/' (a package,+ trailing slash) -> ['logic', 'matrix'] (a package's relative imports are rooted at itself)."""+ trimmed = source_path.removeprefix("backend/")+ if trimmed.endswith("/"):+ return [p for p in trimmed.strip("/").split("/") if p]+ return trimmed.rsplit("/", 1)[0].split("/") if "/" in trimmed else []+++def _resolve_relative(package_parts: list[str], level: int, module: str | None) -> str | None:+ """A relative import from a package -> its module path relative to backend, or None if it climbs+ above backend/ (nothing there is product-internal to this backend). level 1 is the package+ itself, level 2 its parent, etc."""+ climb = level - 1+ if climb > len(package_parts):+ return None+ remaining = package_parts[: len(package_parts) - climb]+ if module:+ remaining = remaining + module.split(".")+ return "/".join(remaining)+++def _resolve_absolute_module(module: str, backend_dir: Path) -> str | None:+ """An absolute import -> its module path relative to backend_dir, or None if it's not this+ product's backend (third-party, core, or another product all return None)."""+ root = _product_backend_root(backend_dir)+ if module == root:+ return ""+ if module.startswith(root + "."):+ return module[len(root) + 1 :].replace(".", "/")+ return None+++def _backend_rel_path(module_rel: str, backend_dir: Path) -> str | None:+ """A module path relative to backend_dir -> a backend-relative on-disk path, or None.++ Resolves to the file that actually holds definitions: 'models' -> 'backend/models.py' if that+ file exists, else 'backend/models/' for a package. The trailing slash on a package lets the+ result be prefix-tested against GARAGE_PREFIXES the same way an input glob is."""+ if module_rel == "":+ return "backend/"+ file_path = backend_dir / f"{module_rel}.py"+ if file_path.is_file():+ return f"backend/{module_rel}.py"+ dir_path = backend_dir / module_rel+ if dir_path.is_dir():+ return f"backend/{module_rel}/"+ return None+++def _source_file(source_path: str, backend_dir: Path) -> Path:+ """The on-disk file for a backend-relative module path (a package resolves to its __init__.py)."""+ if source_path.endswith("/"):+ return backend_dir.parent / source_path.rstrip("/") / "__init__.py"+ return backend_dir.parent / source_path+++def _name_is_class(+ source_path: str,+ name: str,+ backend_dir: Path,+ hops: int = 1,+ cache: dict[Path, ast.Module | None] | None = None,+) -> bool:+ """True if `name` resolves to a class in the module at source_path.++ Follows relative re-exports one hop by default, so a class defined in a submodule and surfaced+ through the package __init__ (the common `from .thing import Thing` shape) still counts. Never+ leaves this product's backend — an absolute or third-party re-export ends the chain.++ `cache` memoizes parses per source file for the duration of one facade traversal, so a+ multi-name import doesn't re-parse the same module once per alias."""+ if cache is None:+ cache = {}+ file_path = _source_file(source_path, backend_dir)+ if file_path not in cache:+ cache[file_path] = ast_parse_safe(file_path)+ tree = cache[file_path]+ if tree is None:+ return False+ if name in {n.name for n in ast.iter_child_nodes(tree) if isinstance(n, ast.ClassDef)}:+ return True+ if hops <= 0:+ return False+ package_parts = _module_package_parts(source_path)+ for level, module, aliases in module_level_import_froms(tree):+ if level == 0:+ continue+ for orig, asname in aliases:+ if (asname or orig) != name:+ continue+ module_rel = _resolve_relative(package_parts, level, module)+ if module_rel is None:+ continue+ nested = _backend_rel_path(module_rel, backend_dir)+ if nested is not None and _name_is_class(nested, orig, backend_dir, hops - 1, cache):+ return True+ return False+++def _resolve_dotted_source(dotted: str, backend_dir: Path) -> str | None:+ """A lazy-map source value ('logic.crud' or 'products.x.backend.logic.crud') -> backend path."""+ module_rel = _resolve_absolute_module(dotted, backend_dir)+ if module_rel is None:+ # Lazy maps commonly store the value relative to the product's backend package.+ module_rel = dotted.replace(".", "/")+ return _backend_rel_path(module_rel, backend_dir)+++def _is_facade_or_garage(source_path: str) -> bool:+ return source_path.startswith((_FACADE_PREFIX, *GARAGE_PREFIXES))+++def _is_test_module(filename: str) -> bool:+ return filename.startswith("test_") or filename.endswith("_test.py")+++def _iter_facade_class_reexports(backend_dir: Path) -> Iterator[FacadeClassImport]:+ """Every product-internal class a facade module hands out, from a non-facade, non-garage module —+ carve-outs included (callers filter). Three shapes are read:++ - a pure re-export module (no top-level function definitions) hands out every class it imports.+ - a data-capability module (api.py and its split-out siblings, which hold functions that+ convert models to contracts) legitimately imports internal classes for its own use, so only+ deliberate re-exports count as handed out: names in its literal `__all__`, plus names+ imported with the explicit self-alias idiom (`from ..x import Foo as Foo` — the shape that+ also suppresses ruff's F401, so it would otherwise be invisible to every lint).+ - a PEP 562 `_LAZY`/`_MODULES` map hands out every class it maps, read regardless of shape.+ """+ facade_dir = backend_dir / "facade"+ if not facade_dir.is_dir():+ return+ parse_cache: dict[Path, ast.Module | None] = {}+ for module_file in sorted(facade_dir.glob("*.py")):+ # contracts/enums are the sanctioned homes for data types; test modules that happen to sit+ # in facade/ are pytest files, not re-export surface. Neither is a wiring re-export.+ if module_file.name in ("contracts.py", "enums.py") or _is_test_module(module_file.name):+ continue+ tree = ast_parse_safe(module_file)+ if tree is None:+ continue+ # A pure re-export module hands out everything it imports; a data-capability module only+ # its deliberate re-exports (__all__ membership or the Foo-as-Foo self-alias).+ is_pure_reexport = not tree_has_top_level_functions(tree)+ allowed = None if is_pure_reexport else module_dunder_all(tree)+ for level, module, aliases in module_level_import_froms(tree):+ module_rel = (+ _resolve_relative(["facade"], level, module)+ if level > 0+ else _resolve_absolute_module(module or "", backend_dir)+ )+ if module_rel is None:+ continue+ source_path = _backend_rel_path(module_rel, backend_dir)+ if source_path is None or _is_facade_or_garage(source_path):+ continue+ for orig, asname in aliases:+ bound = asname or orig+ handed_out = is_pure_reexport or (allowed is not None and bound in allowed) or asname == orig+ if not handed_out:+ continue+ if _name_is_class(source_path, orig, backend_dir, cache=parse_cache):+ yield FacadeClassImport(module_file.name, orig, source_path)+ for name, dotted in lazy_reexport_map(tree).items():+ source_path = _resolve_dotted_source(dotted, backend_dir)+ if source_path is None or _is_facade_or_garage(source_path):+ continue+ if _name_is_class(source_path, name, backend_dir, cache=parse_cache):+ yield FacadeClassImport(module_file.name, name, source_path)+++def _split_facade_reexports(backend_dir: Path, name: str) -> tuple[list[FacadeClassImport], set[str]]:+ """One facade traversal, split into (unsanctioned leaks, carve-out defining modules)."""+ leaks: list[FacadeClassImport] = []+ carveout_modules: set[str] = set()+ for f in _iter_facade_class_reexports(backend_dir):+ if (name, f.class_name) in CARVE_OUTS:+ carveout_modules.add(f.source_path)+ else:+ leaks.append(f)+ return leaks, carveout_modules+++def facade_class_imports(backend_dir: Path, name: str) -> list[FacadeClassImport]:+ """Classes the facade re-exports from a non-garage internal module, minus sanctioned carve-outs.++ Each is a class the facade can hand out that the wiring doctrine doesn't sanction. The remedy is+ always one of three: move it to a garage (if it implements a core-owned base), to+ facade/contracts.py (if it's a data/error type), or drop the turbo.json narrowing.++ Division of labor: deliberate re-exports from a function-bearing facade module must surface via+ __all__ or the Foo-as-Foo self-alias idiom — both counted here — while an imported-and-unused+ leftover is ruff F401's job. The residual hole is therefore only a class that is imported plainly,+ genuinely used inside function bodies, AND separately imported by core anyway — core-side misuse+ this lint doesn't chase."""+ return _split_facade_reexports(backend_dir, name)[0]+++def facade_carveout_modules(backend_dir: Path, name: str) -> set[str]:+ """Backend-relative modules that define the carve-out classes this product's facade re-exports.++ A narrowed product must keep these in its contract-check inputs, exactly like a garage."""+ return _split_facade_reexports(backend_dir, name)[1]+++def unwatched_garages(product_dir: Path) -> set[str]:+ """Garage locations present in the product but missing from its (narrowed) contract-check inputs.++ The accepted prefix keeps the garage's trailing slash, so a directory garage is only covered+ by an input inside it — backend/tasks.py or backend/tasks_extra/** must not count as watching+ backend/tasks/ (same anchoring as _module_input_prefixes)."""+ present = {g for g in GARAGE_PREFIXES if (product_dir / g.rstrip("/")).exists()}+ return _uncovered_locations(product_dir, {g: (g,) for g in present})+++def uncovered_carveout_modules(product_dir: Path, carveout_modules: frozenset[str]) -> set[str]:+ """Carve-out defining modules re-exported by the facade but absent from contract-check inputs.++ A carve-out class crosses the boundary for a class-identity registry, so a change to its+ defining module is a coupling change core must re-test — exactly like a permanent exposure."""+ return _uncovered_locations(product_dir, {m: (m,) for m in carveout_modules})# ---------------------------------------------------------------------------@@ -416,6 +733,14 @@ class IsolationStatus:# schema registry — so they don't qualify as irreducible interfaces and the marker is being# abused to keep an internal (models/logic) walled off. IsolationChainCheck blocks on these.unqualified_permanent_exposures: tuple[str, ...] = ()+ # Classes the facade re-exports from a non-garage, non-carve-out internal module — behavior+ # crossing the boundary that the wiring doctrine doesn't sanction (see facade_class_imports).+ # Blocks narrowing; a warning-only signal while the product is still un-narrowed.+ facade_leaks: tuple[FacadeClassImport, ...] = ()+ # Garage wiring locations present in the product but missing from a narrowed product's inputs,+ # and carve-out modules missing the same way. Both keep the skip sound and block when narrowed.+ unwatched_garages: tuple[str, ...] = ()+ uncovered_carveout_modules: tuple[str, ...] = ()@propertydef deferred_count(self) -> int:@@ -465,6 +790,8 @@ def compute_isolation_status(repo_root = REPO_ROOTmodule_path = f"products.{name}"permanent_modules = frozenset(permanent_interface_modules(tach_content, module_path))+ facade_leaks, carveout_module_set = _split_facade_reexports(backend_dir, name)+ carveout_modules = frozenset(carveout_module_set)return IsolationStatus(name=name,is_isolated=is_isolated,@@ -473,10 +800,13 @@ def compute_isolation_status(has_legacy_leaks=has_legacy_interface_leaks(tach_content, module_path),bypass_entries=tuple(presentation_bypass_entries(name, pyproject_text)),has_contract_check_script=has_contract_check_script(product_dir),- has_narrowed_turbo=has_narrowed_turbo_inputs(product_dir, permanent_modules),+ has_narrowed_turbo=has_narrowed_turbo_inputs(product_dir, permanent_modules, carveout_modules),permanent_exposures=tuple(sorted(permanent_modules)),uncovered_permanent_exposures=tuple(sorted(uncovered_permanent_modules(product_dir, permanent_modules))),unqualified_permanent_exposures=tuple(sorted(unqualified_permanent_modules(module_path, permanent_modules, repo_root=repo_root))),+ facade_leaks=tuple(facade_leaks),+ unwatched_garages=tuple(sorted(unwatched_garages(product_dir))),+ uncovered_carveout_modules=tuple(sorted(uncovered_carveout_modules(product_dir, carveout_modules))),)diff --git a/tools/hogli-commands/hogli_commands/product_structure.yaml b/tools/hogli-commands/hogli_commands/product_structure.yamlindex 0ca453c76843..17f21444bb81 100644--- a/tools/hogli-commands/hogli_commands/product_structure.yaml+++ b/tools/hogli-commands/hogli_commands/product_structure.yaml@@ -66,7 +66,7 @@ root_files:"extends": ["//"],"tasks": {{"backend:contract-check": {{- "inputs": ["backend/facade/**", "backend/presentation/**"],+ "inputs": ["backend/facade/**", "backend/presentation/**", "backend/tasks/**"],"outputs": [],"cache": true}}diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex 7cf8b6324ac9..d358eb855a80 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -26,11 +26,15 @@ from hogli_commands.product.checks import (validate_tach_references,)from hogli_commands.product.isolation import (+ facade_carveout_modules,+ facade_class_imports,has_narrowed_turbo_inputs,permanent_interface_modules,routes_in_turbo_inputs,+ uncovered_carveout_modules,uncovered_permanent_modules,unqualified_permanent_modules,+ unwatched_garages,)# ---------------------------------------------------------------------------@@ -83,6 +87,37 @@ def _make_product()+def _write_facade_product(+ tmp_path: Path,+ *,+ name: str = "my_product",+ facade_files: dict[str, str] | None = None,+ sources: dict[str, str] | None = None,+ turbo_inputs: list[str] | None = None,+) -> tuple[Path, Path]:+ """Build a product with a facade/ package plus arbitrary internal source files.++ `facade_files` are written under backend/facade/; `sources` are backend-relative paths+ (parents created), used both for the modules a facade re-exports from and for making a+ garage directory exist. Returns (product_dir, backend_dir)."""+ product_dir = tmp_path / name+ backend_dir = product_dir / "backend"+ facade = backend_dir / "facade"+ facade.mkdir(parents=True)+ (facade / "contracts.py").write_text("")+ for fname, content in (facade_files or {}).items():+ (facade / fname).write_text(content)+ for rel, content in (sources or {}).items():+ path = backend_dir / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content)+ if turbo_inputs is not None:+ (product_dir / "turbo.json").write_text(+ json.dumps({"tasks": {"backend:contract-check": {"inputs": turbo_inputs}}})+ )+ return product_dir, backend_dir++check = PackageJsonScriptsCheck()@@ -1459,3 +1494,239 @@ def test_presentation_bypass_entries_handles_broken_toml() -> None:from hogli_commands.product.isolation import presentation_bypass_entriesassert presentation_bypass_entries("logs", "not = [valid") == []+++# ---------------------------------------------------------------------------+# Wiring couplings — facade class re-exports and garage coverage+# ---------------------------------------------------------------------------+++class TestFacadeClassImports:+ @pytest.mark.parametrize(+ "facade_files, sources, expected",+ [+ # a pure re-export module hands out every class it imports from a non-garage module+ (+ {"queries.py": "from ..logic import Thing\n__all__ = ['Thing']\n"},+ {"logic.py": "class Thing:\n pass\n"},+ {"Thing"},+ ),+ # a class re-exported from a garage is sanctioned wiring, never flagged+ (+ {"queries.py": "from ..hogql_queries.runner import Runner\n__all__ = ['Runner']\n"},+ {"hogql_queries/runner.py": "class Runner:\n pass\n"},+ set(),+ ),+ # a re-exported function is the designed delegation pattern, never flagged+ (+ {"helpers.py": "from ..logic import do_it\n__all__ = ['do_it']\n"},+ {"logic.py": "def do_it():\n pass\n"},+ set(),+ ),+ # a third-party / core source is not product-internal+ ({"queries.py": "from posthog.models import Team\n__all__ = ['Team']\n"}, {}, set()),+ # a TYPE_CHECKING import is type-only — nothing crosses at runtime+ (+ {+ "queries.py": "from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from ..logic import Thing\n"+ },+ {"logic.py": "class Thing:\n pass\n"},+ set(),+ ),+ # a data-capability module (has functions) without __all__ imports an internal class for+ # its own use, not to hand out+ (+ {"api2.py": "from ..logic import Thing\n\n\ndef build():\n return Thing()\n"},+ {"logic.py": "class Thing:\n pass\n"},+ set(),+ ),+ # ...but the same module hands the class out once it advertises it in __all__+ (+ {+ "api2.py": "from ..logic import Thing\n\n\ndef build():\n return 1\n\n\n__all__ = ['Thing', 'build']\n"+ },+ {"logic.py": "class Thing:\n pass\n"},+ {"Thing"},+ ),+ # ...or re-exports it with the explicit self-alias idiom (which also suppresses F401)+ (+ {"api2.py": "from ..logic import Thing as Thing\n\n\ndef build():\n return 1\n"},+ {"logic.py": "class Thing:\n pass\n"},+ {"Thing"},+ ),+ # a renaming alias is a private import for internal use, not the re-export idiom+ (+ {"api2.py": "from ..logic import Thing as _Thing\n\n\ndef build():\n return _Thing()\n"},+ {"logic.py": "class Thing:\n pass\n"},+ set(),+ ),+ # a PEP 562 lazy map hands out every class it maps+ (+ {+ "api2.py": "_LAZY = {'Thing': 'logic'}\n\n\ndef __getattr__(name):\n import importlib\n\n return getattr(importlib.import_module('x'), name)\n"+ },+ {"logic.py": "class Thing:\n pass\n"},+ {"Thing"},+ ),+ # a class surfaced through a package __init__ still resolves (one re-export hop)+ (+ {"queries.py": "from ..logic import Thing\n__all__ = ['Thing']\n"},+ {"logic/__init__.py": "from .impl import Thing\n", "logic/impl.py": "class Thing:\n pass\n"},+ {"Thing"},+ ),+ ],+ )+ def test_detection(+ self, tmp_path: Path, facade_files: dict[str, str], sources: dict[str, str], expected: set[str]+ ) -> None:+ _, backend = _write_facade_product(tmp_path, facade_files=facade_files, sources=sources)+ assert {f.class_name for f in facade_class_imports(backend, "my_product")} == expected++ def test_carveout_is_not_a_violation_but_is_tracked_for_coverage(self, tmp_path: Path) -> None:+ facade = {+ "team_extension.py": "from ..models.tcac import TeamCustomerAnalyticsConfig\n__all__ = ['TeamCustomerAnalyticsConfig']\n"+ }+ sources = {"models/tcac.py": "class TeamCustomerAnalyticsConfig:\n pass\n"}+ _, backend = _write_facade_product(tmp_path, name="customer_analytics", facade_files=facade, sources=sources)+ assert facade_class_imports(backend, "customer_analytics") == []+ assert facade_carveout_modules(backend, "customer_analytics") == {"backend/models/tcac.py"}++ def test_carveout_class_is_an_ordinary_violation_for_a_product_that_does_not_own_it(self, tmp_path: Path) -> None:+ # the carve-out is keyed (product, class): another product re-exporting the same class name+ # gets no free pass.+ facade = {+ "team_extension.py": "from ..models.tcac import TeamCustomerAnalyticsConfig\n__all__ = ['TeamCustomerAnalyticsConfig']\n"+ }+ sources = {"models/tcac.py": "class TeamCustomerAnalyticsConfig:\n pass\n"}+ _, backend = _write_facade_product(tmp_path, name="unrelated_product", facade_files=facade, sources=sources)+ assert {f.class_name for f in facade_class_imports(backend, "unrelated_product")} == {+ "TeamCustomerAnalyticsConfig"+ }+++class TestUnwatchedGarages:+ @pytest.mark.parametrize(+ "garage_file, turbo_inputs, expected",+ [+ ("tasks/tasks.py", ["backend/facade/**"], {"backend/tasks/"}), # garage present but not watched+ ("tasks/tasks.py", ["backend/facade/**", "backend/tasks/**"], set()), # watched — satisfied+ # un-narrowed: contract-check watches everything, so nothing is "unwatched"+ ("tasks/tasks.py", None, set()),+ # the flat-file garage form is detected and satisfied the same way+ ("tasks.py", ["backend/facade/**"], {"backend/tasks.py"}),+ ("tasks.py", ["backend/facade/**", "backend/tasks.py"], set()),+ # near-miss prefixes must not count as covering the directory garage+ ("tasks/tasks.py", ["backend/facade/**", "backend/tasks.py"], {"backend/tasks/"}),+ ("tasks/tasks.py", ["backend/facade/**", "backend/tasks_extra/**"], {"backend/tasks/"}),+ # a flat-file garage needs an exact input, not a shared prefix+ ("tasks.py", ["backend/facade/**", "backend/tasks.py.bak"], {"backend/tasks.py"}),+ ],+ )+ def test_present_garage_coverage(+ self, tmp_path: Path, garage_file: str, turbo_inputs: list[str] | None, expected: set[str]+ ) -> None:+ product_dir, _ = _write_facade_product(tmp_path, sources={garage_file: ""}, turbo_inputs=turbo_inputs)+ assert unwatched_garages(product_dir) == expected+++class TestNarrowedTurboWiringSurface:+ @pytest.mark.parametrize(+ "inputs, expected",+ [+ (["backend/facade/**", "backend/hogql_queries/**"], True), # a garage dir counts as narrowing surface+ (["backend/facade/**", "backend/max_tools.py"], True), # a single-file garage counts too+ (["backend/facade/**", "backend/tasks.py"], True), # the flat-file tasks garage form+ (["backend/hogql_queries/**"], False), # garage alone isn't a real contract surface+ (["backend/facade/**", "backend/logic/**"], False), # a non-wiring dir breaks the narrowing+ ],+ )+ def test_garage_inputs_count_as_narrowing(self, tmp_path: Path, inputs: list[str], expected: bool) -> None:+ product_dir, _ = _write_facade_product(tmp_path, turbo_inputs=inputs)+ assert has_narrowed_turbo_inputs(product_dir) is expected++ def test_carveout_module_is_accepted_surface_only_when_declared(self, tmp_path: Path) -> None:+ # a carve-out defining module is an odd input (not facade/garage): it only counts as+ # narrowing when the caller passes it as a known carve-out module.+ product_dir, _ = _write_facade_product(tmp_path, turbo_inputs=["backend/facade/**", "backend/models/tcac.py"])+ assert has_narrowed_turbo_inputs(product_dir) is False+ assert has_narrowed_turbo_inputs(product_dir, frozenset(), frozenset({"backend/models/tcac.py"})) is True++ @pytest.mark.parametrize(+ "inputs, expected",+ [+ (["backend/facade/**", "backend/models/tcac.py"], set()), # covered+ (["backend/facade/**"], {"backend/models/tcac.py"}), # missing -> uncovered+ ],+ )+ def test_carveout_module_coverage(self, tmp_path: Path, inputs: list[str], expected: set[str]) -> None:+ product_dir, _ = _write_facade_product(tmp_path, turbo_inputs=inputs)+ assert uncovered_carveout_modules(product_dir, frozenset({"backend/models/tcac.py"})) == expected+++def _add_facade_reexport(ctx: CheckContext) -> None:+ """Give the fixture product a wiring violation: a pure re-export facade module handing out a+ non-garage internal class."""+ (ctx.backend_dir / "facade" / "queries.py").write_text("from ..logic import Thing\n__all__ = ['Thing']\n")+ (ctx.backend_dir / "logic.py").write_text("class Thing:\n pass\n")+++class TestIsolationChainWiringGate:+ def test_narrowed_facade_violation_blocks(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _seal_externally(monkeypatch)+ ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, isolated=True)+ _add_facade_reexport(ctx)+ (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))+ result = chain_check.run(ctx)+ assert any("Thing" in i and "wiring location" in i for i in result.issues)++ def test_unnarrowed_facade_violation_warns_and_suppresses_the_narrowing_nag(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Un-narrowed: the skip is inert, so the leak is a warning, not a block. And the "you're+ # eligible, narrow now" nag must be suppressed — the wiring gate would reject that narrowing.+ _seal_externally(monkeypatch)+ ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, isolated=True)+ _add_facade_reexport(ctx)+ result = chain_check.run(ctx)+ # the leak is a warning that also explains what blocks narrowing...+ assert any("Thing" in w and "narrowing is blocked" in w for w in result.warnings)+ assert not any("Thing" in i for i in result.issues)+ # ...and the "you're eligible, narrow now" nag is suppressed.+ assert not any("inert" in i for i in result.issues)++ def test_narrowed_unwatched_garage_blocks(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _seal_externally(monkeypatch)+ ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, isolated=True)+ (ctx.backend_dir / "tasks").mkdir()+ (ctx.backend_dir / "tasks" / "tasks.py").write_text("")+ (ctx.product_dir / "turbo.json").write_text(json.dumps(_NARROWED_TURBO))+ result = chain_check.run(ctx)+ assert any("backend/tasks/" in i and "wiring location" in i for i in result.issues)+++class TestPackageJsonScriptsWiringWithheld:+ def test_eligible_facade_violation_is_not_nagged_to_add_the_script(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # A demoted product (facade hands out unsanctioned classes) that dropped its script must not+ # be told to add it back — it can't soundly narrow.+ _seal_externally(monkeypatch)+ ctx = _make_product(+ tmp_path,+ scripts={"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"},+ isolated=True,+ )+ _add_facade_reexport(ctx)+ result = check.run(ctx)+ assert not any("contract-check" in i for i in result.issues)++ def test_eligible_facade_violation_keeps_an_existing_script(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # The un-narrowed script+broad products carry a facade violation too; the absence check keys+ # on plain eligibility, so they must not be told to remove the script.+ _seal_externally(monkeypatch)+ ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, isolated=True)+ _add_facade_reexport(ctx)+ result = check.run(ctx)+ assert not any("must not have" in i or "remove 'backend:contract-check'" in i for i in result.issues)