Skip to content

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

chore(error-tracking): seal external boundary and enable contract-check (#65456)

Hugues Pouillotc5f763e280d5
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.md
index 1ae0321d161e..efcf5ed7b010 100644
--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md
+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md
@@ -284,6 +284,39 @@ in `facade/api.py` with the viewset deferred.
string-reference section surfaces the latter). tach/import-linter
only police the import channel; a mechanical check for these
non-import channels is a known gap, noted and deferred.
+ - **Permanent-interface exception (irreducible import coupling).** Some
+ import coupling genuinely cannot be drained: ClickHouse DDL modules
+ (`backend.sql`, `backend.embedding`, …) are imported by core's
+ `posthog/clickhouse/schema.py` registry, `conftest.py`, and **frozen**
+ ClickHouse migrations that hardcode the import path forever. You cannot
+ reroute a frozen migration or move the module. For this, mark the
+ tach `[[interfaces]]` block that exposes those modules with a
+ `# isolation:permanent-interface` comment on the line(s) directly above
+ it. The marker tells `hogli product:lint` the block is a declared,
+ irreducible exposure — **not** a legacy leak — so it stops withholding
+ `backend:contract-check`. Soundness is preserved by pairing it with
+ turbo.json: every permanently-exposed module **must** appear in the
+ contract-check `inputs` (e.g. `backend/sql.py`), so a change to it still
+ re-runs the full suite. `IsolationChainCheck` enforces that pairing and
+ fails if a marked module is missing from the inputs. Use this only for
+ coupling that is both non-behavioral-over-HTTP and impossible to reroute
+ (frozen-migration / schema-registry DDL) — not as an escape hatch for
+ model/logic imports you simply haven't migrated yet. That restriction is
+ structural, not stylistic: the marker is only sound when every
+ frozen-pinned module contains **only DDL**. `error_tracking` is the worked
+ example (`sql` / `embedding` / `indexed_embedding` are pure-DDL modules).
+ `cohorts` matches too — migration 0010 pins
+ `products.cohorts.backend.models.sql`, a DDL-only submodule, so the marker
+ applies to exactly that submodule (not `backend.models.*`).
+ `event_definitions` does **not**: migration 0120 pins
+ `products.event_definitions.backend.models.property_definition`, a module
+ that defines the `PropertyDefinition` model class alongside its DDL
+ constant, so marking it permanent would expose model access — precisely
+ the escape hatch this exception forbids. Products with that shape need the
+ DDL extracted into a dedicated module first, with the frozen import path
+ preserved by a re-export shim in the original module; the shim's residual
+ exposure (the frozen migration still imports the model module) must be
+ documented honestly in the block comment, not papered over by the marker.
- Verify with `tach check --dependencies --interfaces`, `lint-imports`
(import-linter contract for presentation → facade), and `hogli product:lint <name>`.
- Use `hogli product:maturity <name>` for a detailed breakdown of remaining
diff --git a/ee/hogai/context/error_tracking/test/test_context.py b/ee/hogai/context/error_tracking/test/test_context.py
index 2f3c911e97bc..e79a6df60fbd 100644
--- a/ee/hogai/context/error_tracking/test/test_context.py
+++ b/ee/hogai/context/error_tracking/test/test_context.py
@@ -2,14 +2,19 @@ from freezegun import freeze_time
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events
from unittest.mock import patch
+from django.apps import apps
from django.utils.timezone import now
from dateutil.relativedelta import relativedelta
-from products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingIssueFingerprintV2
-
from ee.hogai.context.error_tracking.context import ErrorTrackingIssueContext
+# Test-fixture setup only — the code under test (ErrorTrackingIssueContext) reads issues through
+# the facade. Issues have no create-contract (they come from ingestion), so the test seeds the row
+# directly; apps.get_model avoids an import edge into error_tracking internals that tach would flag.
+ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")
+ErrorTrackingIssueFingerprintV2 = apps.get_model("error_tracking", "ErrorTrackingIssueFingerprintV2")
+
@freeze_time("2025-01-15T12:00:00Z")
class TestErrorTrackingIssueContext(ClickhouseTestMixin, APIBaseTest):
diff --git a/ee/hogai/eval/sandboxed/error_tracking/seeders.py b/ee/hogai/eval/sandboxed/error_tracking/seeders.py
index cd8d95b507cf..d889a92add63 100644
--- a/ee/hogai/eval/sandboxed/error_tracking/seeders.py
+++ b/ee/hogai/eval/sandboxed/error_tracking/seeders.py
@@ -28,9 +28,11 @@ import json
import uuid
import logging
from datetime import UTC, datetime, timedelta
-from typing import Any, Protocol
+from typing import TYPE_CHECKING, Any, Protocol
from zoneinfo import ZoneInfo
+from django.apps import apps
+
from posthog.clickhouse.client import sync_execute
from posthog.models import Team
from posthog.models.event.sql import INSERT_EVENT_SQL
@@ -39,9 +41,14 @@ from posthog.models.person.sql import INSERT_PERSON_DISTINCT_ID2, INSERT_PERSON_
from posthog.models.utils import uuid7
from posthog.session_recordings.queries.test.session_replay_sql import INSERT_SINGLE_SESSION_REPLAY
-from products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingIssueFingerprintV2
from products.error_tracking.backend.sql import INSERT_ERROR_TRACKING_FINGERPRINT_ISSUE_STATE
+if TYPE_CHECKING:
+ from products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingIssueFingerprintV2
+else:
+ ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")
+ ErrorTrackingIssueFingerprintV2 = apps.get_model("error_tracking", "ErrorTrackingIssueFingerprintV2")
+
logger = logging.getLogger(__name__)
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.py
index 224cbfb4172b..32e199bf3d3d 100644
--- a/posthog/admin/admins/organization_admin.py
+++ b/posthog/admin/admins/organization_admin.py
@@ -1,6 +1,7 @@
from datetime import UTC, timedelta
from django import forms
+from django.apps import apps
from django.conf import settings
from django.contrib import admin, messages
from django.core.management import call_command
@@ -9,7 +10,6 @@ from django.template.loader import render_to_string
from django.urls import path, reverse
from django.utils import timezone
from django.utils.html import format_html
-from django.utils.module_loading import import_string
from django.utils.safestring import mark_safe
from posthog.admin.inline_registry import extra_inlines_for
@@ -23,22 +23,14 @@ from posthog.models.organization import Organization
from posthog.person_db_router import PERSONS_DB_MODELS
# Registry of default-db models to count for bulk-delete report.
-# Format: (model_import_path, filter_field, display_name)
+# Format: (app_label.ModelName, filter_field, display_name)
# This mirrors delete_bulky_postgres_data() in posthog/models/team/util.py
# When bulk-delete changes, update this list accordingly.
# Note: BatchExport requires special handling (see below)
BULK_DELETE_MODEL_REGISTRY: tuple[tuple[str, str, str], ...] = (
- ("products.early_access_features.backend.models.EarlyAccessFeature", "team_id", "Early Access Features"),
- (
- "products.error_tracking.backend.models.ErrorTrackingIssueFingerprintV2",
- "team_id",
- "Error Tracking Fingerprints",
- ),
- (
- "products.product_analytics.backend.models.insight_caching_state.InsightCachingState",
- "team_id",
- "Insight Caching States",
- ),
+ ("early_access_features.EarlyAccessFeature", "team_id", "Early Access Features"),
+ ("error_tracking.ErrorTrackingIssueFingerprintV2", "team_id", "Error Tracking Fingerprints"),
+ ("product_analytics.InsightCachingState", "team_id", "Insight Caching States"),
)
# Subset of persons-db models that are part of the bulk-delete path.
@@ -64,9 +56,9 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:
return []
results = []
- for model_path, filter_field, display_name in BULK_DELETE_MODEL_REGISTRY:
+ for model_label, filter_field, display_name in BULK_DELETE_MODEL_REGISTRY:
try:
- model_class = import_string(model_path)
+ model_class = apps.get_model(model_label)
# nosemgrep: orm-field-injection -- filter_field from hardcoded BULK_DELETE_MODEL_REGISTRY, not user input
count = model_class.objects.filter(**{f"{filter_field}__in": team_ids}).count()
results.append(
@@ -81,7 +73,7 @@ def get_model_counts_for_organization(organization: Organization) -> list[dict]:
{
"name": display_name,
"count": f"Error: {e}",
- "model": model_path,
+ "model": model_label,
}
)
diff --git a/posthog/api/test/test_personal_api_keys.py b/posthog/api/test/test_personal_api_keys.py
index 5d5f7d9a14da..7d29e50a8662 100644
--- a/posthog/api/test/test_personal_api_keys.py
+++ b/posthog/api/test/test_personal_api_keys.py
@@ -3,6 +3,7 @@ from datetime import timedelta
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.apps import apps
from django.utils import timezone
from parameterized import parameterized
@@ -18,9 +19,10 @@ from posthog.models.personal_api_key import LEGACY_PERSONAL_API_KEY_SALT, Person
from posthog.models.team.team import Team
from posthog.models.utils import SHA256_HASH_PREFIX, generate_random_token_personal, hash_key_value
-from products.error_tracking.backend.models import ErrorTrackingIssue
from products.product_analytics.backend.models.insight import Insight
+ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")
+
class TestPersonalAPIKeysAPI(APIBaseTest):
def test_create_personal_api_key(self):
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 0b42439a1a8a..2dafb6d6bb0d 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -39,7 +39,6 @@ from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
from products.early_access_features.backend.models import EarlyAccessFeature
from products.endpoints.backend.facade.models import Endpoint, EndpointVersion
-from products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingSymbolSet
from products.experiments.backend.models.experiment import Experiment
from products.exports.backend.models.exported_asset import ExportedAsset
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -60,10 +59,28 @@ if TYPE_CHECKING:
from products.customer_analytics.backend.models.account import Account
from products.customer_analytics.backend.models.custom_property_definition import CustomPropertyDefinition
from products.customer_analytics.backend.models.custom_property_value import CustomPropertyValue
+ from products.error_tracking.backend.models import (
+ ErrorTrackingAssignmentRule,
+ ErrorTrackingBypassRule,
+ ErrorTrackingIssue,
+ ErrorTrackingIssueAssignment,
+ ErrorTrackingIssueFingerprintV2,
+ ErrorTrackingRelease,
+ ErrorTrackingSuppressionRule,
+ ErrorTrackingSymbolSet,
+ )
else:
Account = apps.get_model("customer_analytics", "Account")
CustomPropertyDefinition = apps.get_model("customer_analytics", "CustomPropertyDefinition")
CustomPropertyValue = apps.get_model("customer_analytics", "CustomPropertyValue")
+ ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")
+ ErrorTrackingSymbolSet = apps.get_model("error_tracking", "ErrorTrackingSymbolSet")
+ ErrorTrackingIssueAssignment = apps.get_model("error_tracking", "ErrorTrackingIssueAssignment")
+ ErrorTrackingIssueFingerprintV2 = apps.get_model("error_tracking", "ErrorTrackingIssueFingerprintV2")
+ ErrorTrackingAssignmentRule = apps.get_model("error_tracking", "ErrorTrackingAssignmentRule")
+ ErrorTrackingBypassRule = apps.get_model("error_tracking", "ErrorTrackingBypassRule")
+ ErrorTrackingSuppressionRule = apps.get_model("error_tracking", "ErrorTrackingSuppressionRule")
+ ErrorTrackingRelease = apps.get_model("error_tracking", "ErrorTrackingRelease")
# Only directly-queryable tables are team-scoped via a WHERE clause. Namespace nodes such as
# `information_schema` carry no `table` of their own (just child catalog tables computed per-query),
@@ -295,46 +312,34 @@ def _create_error_tracking_issue(team: Team, label: str) -> ErrorTrackingIssue:
def _create_error_tracking_issue_assignment(team: Team, label: str):
- from products.error_tracking.backend.models import ErrorTrackingIssueAssignment
-
issue = ErrorTrackingIssue.objects.create(team=team, name=f"assigned_issue_{label}", status="active")
return ErrorTrackingIssueAssignment.objects.create(team=team, issue=issue)
def _create_error_tracking_issue_fingerprint(team: Team, label: str):
- from products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2
-
issue = ErrorTrackingIssue.objects.create(team=team, name=f"fp_issue_{label}", status="active")
return ErrorTrackingIssueFingerprintV2.objects.create(team=team, issue=issue, fingerprint=f"fp_{label}")
def _create_error_tracking_assignment_rule(team: Team, label: str):
- from products.error_tracking.backend.models import ErrorTrackingAssignmentRule
-
return ErrorTrackingAssignmentRule.objects.create(
team=team, filters={"type": "AND", "values": []}, bytecode=[], order_key=0
)
def _create_error_tracking_bypass_rule(team: Team, label: str):
- from products.error_tracking.backend.models import ErrorTrackingBypassRule
-
return ErrorTrackingBypassRule.objects.create(
team=team, filters={"type": "AND", "values": []}, bytecode=[], order_key=0
)
def _create_error_tracking_suppression_rule(team: Team, label: str):
- from products.error_tracking.backend.models import ErrorTrackingSuppressionRule
-
return ErrorTrackingSuppressionRule.objects.create(
team=team, filters={"type": "AND", "values": []}, bytecode=[], order_key=0, sampling_rate=1.0
)
def _create_error_tracking_release(team: Team, label: str):
- from products.error_tracking.backend.models import ErrorTrackingRelease
-
return ErrorTrackingRelease.objects.create(
team=team, hash_id=f"hash_{label}", version=f"v_{label}", project=f"proj_{label}"
)
diff --git a/posthog/management/commands/fingerprint_embeddings_backfill.py b/posthog/management/commands/fingerprint_embeddings_backfill.py
index cfb84b756f5a..25d53da2617f 100644
--- a/posthog/management/commands/fingerprint_embeddings_backfill.py
+++ b/posthog/management/commands/fingerprint_embeddings_backfill.py
@@ -1,7 +1,9 @@
import json
import logging
from datetime import timedelta
+from typing import TYPE_CHECKING
+from django.apps import apps
from django.core.management.base import BaseCommand
import structlog
@@ -10,7 +12,10 @@ from posthog.clickhouse.client.execute import sync_execute
from posthog.kafka_client.routing import producer_scope
from posthog.kafka_client.topics import KAFKA_ERROR_TRACKING_ISSUE_FINGERPRINT_EMBEDDINGS
-from products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2
+if TYPE_CHECKING:
+ from products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2
+else:
+ ErrorTrackingIssueFingerprintV2 = apps.get_model("error_tracking", "ErrorTrackingIssueFingerprintV2")
logger = structlog.get_logger(__name__)
logger.setLevel(logging.INFO)
diff --git a/posthog/management/commands/sync_exceptions_to_clickhouse.py b/posthog/management/commands/sync_exceptions_to_clickhouse.py
index 14c8ff8fc229..2634cddf8d3f 100644
--- a/posthog/management/commands/sync_exceptions_to_clickhouse.py
+++ b/posthog/management/commands/sync_exceptions_to_clickhouse.py
@@ -1,5 +1,7 @@
import logging
+from typing import TYPE_CHECKING
+from django.apps import apps
from django.core.management.base import BaseCommand
import structlog
@@ -7,10 +9,12 @@ import structlog
from posthog.clickhouse.client.execute import sync_execute
from posthog.kafka_client.routing import flush_all_producers
-from products.error_tracking.backend.models import (
- ErrorTrackingIssueFingerprintV2,
- override_error_tracking_issue_fingerprint,
-)
+from products.error_tracking.backend.facade import override_error_tracking_issue_fingerprint
+
+if TYPE_CHECKING:
+ from products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2
+else:
+ ErrorTrackingIssueFingerprintV2 = apps.get_model("error_tracking", "ErrorTrackingIssueFingerprintV2")
logger = structlog.get_logger(__name__)
logger.setLevel(logging.INFO)
diff --git a/posthog/models/product_intent/product_intent.py b/posthog/models/product_intent/product_intent.py
index d49b2a542c0c..e9dbd764ddf0 100644
--- a/posthog/models/product_intent/product_intent.py
+++ b/posthog/models/product_intent/product_intent.py
@@ -20,7 +20,6 @@ from posthog.session_recordings.models.session_recording_event import SessionRec
from posthog.utils import get_instance_realm, get_safe_cache, safe_cache_delete, safe_cache_set
from products.dashboards.backend.models.dashboard import Dashboard
-from products.error_tracking.backend.models import ErrorTrackingIssue
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -120,7 +119,11 @@ class ProductIntent(UUIDTModel, RootTeamMixin):
def has_activated_error_tracking(self) -> bool:
# the team has resolved any issues
- return ErrorTrackingIssue.objects.filter(team=self.team, status=ErrorTrackingIssue.Status.RESOLVED).exists()
+ # Local import: this module loads during django.setup() (via posthog.models), and the
+ # error_tracking facade pulls in posthog.event_usage -> posthog.models (circular).
+ from products.error_tracking.backend import facade as error_tracking # noqa: PLC0415
+
+ return error_tracking.has_resolved_issues(self.team_id)
def has_activated_surveys(self) -> bool:
return Survey.objects.filter(team__project_id=self.team.project_id, start_date__isnull=False).exists()
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.py
index 8db919b8f99c..045605fd424c 100644
--- a/posthog/models/remote_config.py
+++ b/posthog/models/remote_config.py
@@ -25,7 +25,6 @@ from posthog.storage.hypercache import HyperCache, HyperCacheStoreMissing
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.models.plugin import PluginConfig
-from products.error_tracking.backend.models import ErrorTrackingSuppressionRule
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_tours.backend.models import ProductTour
from products.surveys.backend.models import Survey
@@ -211,7 +210,7 @@ class RemoteConfig(UUIDTModel):
from posthog.models.team import Team
from posthog.plugins.site import get_decide_site_apps
- from products.error_tracking.backend.remote_config import build_error_tracking_config
+ from products.error_tracking.backend.facade import build_error_tracking_config
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.surveys.backend.api.survey import get_surveys_opt_in, get_surveys_response
@@ -580,8 +579,8 @@ def product_tour_deleted(sender, instance, **kwargs):
transaction.on_commit(_on_commit)
-@receiver(post_save, sender=ErrorTrackingSuppressionRule)
-def error_tracking_suppression_rule_saved(sender, instance: "ErrorTrackingSuppressionRule", created, **kwargs):
+@receiver(post_save, sender="error_tracking.ErrorTrackingSuppressionRule")
+def error_tracking_suppression_rule_saved(sender, instance, created, **kwargs):
transaction.on_commit(lambda: _update_team_remote_config(instance.team_id))
diff --git a/posthog/models/team/util.py b/posthog/models/team/util.py
index f153e3733289..18744373deb7 100644
--- a/posthog/models/team/util.py
+++ b/posthog/models/team/util.py
@@ -2,6 +2,8 @@ import time
from datetime import timedelta
from typing import Any
+from django.apps import apps
+
import structlog
from posthog.cache_utils import cache_for
@@ -57,16 +59,17 @@ def _delete_misc_small_tables_for_teams(team_ids: list[int]) -> None:
from products.data_modeling.backend.facade.models import Edge, Node
from products.early_access_features.backend.models import EarlyAccessFeature
- from products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2
from products.product_analytics.backend.models.insight_caching_state import InsightCachingState
+ error_tracking_fingerprint = apps.get_model("error_tracking", "ErrorTrackingIssueFingerprintV2")
+
# Data modeling Edge/Node must be deleted before the Team row: Team cascades to
# DataWarehouseSavedQuery, which has PROTECT on delete.
_raw_delete_batch(Edge.objects.filter(team_id__in=team_ids))
_raw_delete_batch(Node.objects.filter(team_id__in=team_ids))
_raw_delete_batch(FileSystemViewLog.objects.filter(team_id__in=team_ids))
_raw_delete_batch(EarlyAccessFeature.objects.filter(team_id__in=team_ids))
- _raw_delete_batch(ErrorTrackingIssueFingerprintV2.objects.filter(team_id__in=team_ids))
+ _raw_delete_batch(error_tracking_fingerprint.objects.filter(team_id__in=team_ids))
# FeatureFlagHashKeyOverride references Person, so it must go before persons are deleted.
_delete_hash_key_overrides_for_teams(team_ids)
_raw_delete_batch(InsightCachingState.objects.filter(team_id__in=team_ids))
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index 2469f38ed3c2..6ed1d020b5ec 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -22,6 +22,7 @@ from posthog.test.base import (
)
from unittest.mock import MagicMock, Mock, patch
+from django.apps import apps
from django.test import TestCase
from django.utils.timezone import now
@@ -77,7 +78,6 @@ from products.batch_exports.backend.models.batch_export import (
from products.cdp.backend.models.plugin import Plugin, PluginConfig
from products.dashboards.backend.models.dashboard import Dashboard
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
-from products.error_tracking.backend.models import ErrorTrackingIssue
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.warehouse_sources.backend.facade.models import (
DataWarehouseTable,
@@ -91,6 +91,8 @@ from ee.api.test.base import LicensedTestMixin
from ee.clickhouse.materialized_columns.columns import materialize
from ee.models.license import License
+ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")
+
logger = structlog.get_logger(__name__)
diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.py
index bdfed1872b10..4cc7a182ccbe 100644
--- a/posthog/test/test_permissions.py
+++ b/posthog/test/test_permissions.py
@@ -4,6 +4,7 @@ from datetime import timedelta
from posthog.test.base import BaseTest
from unittest.mock import Mock, PropertyMock, patch
+from django.apps import apps
from django.test import SimpleTestCase
from django.utils import timezone
@@ -18,14 +19,14 @@ from posthog.models.organization import OrganizationMembership
from posthog.permissions import AccessControlPermission, PostHogFeatureFlagPermission
from posthog.rbac.user_access_control import UserAccessControl
-from products.error_tracking.backend.models import ErrorTrackingIssue
-
try:
from ee.models.rbac.access_control import AccessControl
from ee.models.rbac.role import Role, RoleMembership
except ImportError:
pass
+ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")
+
class TestAccessControlPermission(BaseTest):
"""
diff --git a/products/demo/backend/logic/products/hedgebox/matrix.py b/products/demo/backend/logic/products/hedgebox/matrix.py
index de2150b9bf4f..276456638e52 100644
--- a/products/demo/backend/logic/products/hedgebox/matrix.py
+++ b/products/demo/backend/logic/products/hedgebox/matrix.py
@@ -7,6 +7,7 @@ from io import StringIO
from typing import TYPE_CHECKING, Any, Optional, TypedDict, cast
from urllib.parse import urlparse, urlunparse
+from django.apps import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import IntegrityError
@@ -62,12 +63,7 @@ from products.demo.backend.logic.matrix.matrix import Cluster, Matrix
from products.demo.backend.logic.matrix.models import SimEvent
from products.demo.backend.logic.matrix.randomization import Industry
from products.endpoints.backend.facade.models import Endpoint, EndpointVersion
-from products.error_tracking.backend.models import (
- ErrorTrackingIssue,
- ErrorTrackingIssueFingerprintV2,
- ErrorTrackingStackFrame,
- sync_issues_to_clickhouse,
-)
+from products.error_tracking.backend.facade import sync_issues_to_clickhouse
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.event_definitions.backend.models.property_definition import PropertyType
from products.event_definitions.backend.models.schema import (
@@ -109,6 +105,10 @@ if TYPE_CHECKING:
from posthog.models.team import Team
from posthog.models.user import User
+ErrorTrackingIssue = apps.get_model("error_tracking", "ErrorTrackingIssue")
+ErrorTrackingIssueFingerprintV2 = apps.get_model("error_tracking", "ErrorTrackingIssueFingerprintV2")
+ErrorTrackingStackFrame = apps.get_model("error_tracking", "ErrorTrackingStackFrame")
+
@dataclass
class HedgeboxCompany:
diff --git a/products/error_tracking/backend/facade/__init__.py b/products/error_tracking/backend/facade/__init__.py
index 6fc78f3730e2..0776128a3261 100644
--- a/products/error_tracking/backend/facade/__init__.py
+++ b/products/error_tracking/backend/facade/__init__.py
@@ -5,6 +5,7 @@ from .api import (
ReleaseHashInUseError,
auto_select_project_for_user,
batch_get_stack_frames,
+ build_error_tracking_config,
build_ingestion_failures_url,
count_issues_created_since,
create_assignment_rule,
@@ -41,6 +42,7 @@ from .api import (
get_symbol_set_counts_by_team,
get_top_issues_for_team,
has_filter_values,
+ has_resolved_issues,
is_supported_external_issue_provider,
issue_exists,
list_assignment_rules,
@@ -52,9 +54,11 @@ from .api import (
list_spike_events,
list_stack_frames,
list_suppression_rules,
+ override_error_tracking_issue_fingerprint,
reorder_assignment_rules,
reorder_grouping_rules,
reorder_suppression_rules,
+ sync_issues_to_clickhouse,
update_assignment_rule,
update_grouping_rule,
update_release,
@@ -69,6 +73,7 @@ __all__ = [
"ReleaseHashInUseError",
"auto_select_project_for_user",
"batch_get_stack_frames",
+ "build_error_tracking_config",
"build_ingestion_failures_url",
"contracts",
"count_issues_created_since",
@@ -106,6 +111,7 @@ __all__ = [
"get_symbol_set_counts_by_team",
"get_top_issues_for_team",
"has_filter_values",
+ "has_resolved_issues",
"is_supported_external_issue_provider",
"issue_exists",
"list_assignment_rules",
@@ -117,9 +123,11 @@ __all__ = [
"list_spike_events",
"list_stack_frames",
"list_suppression_rules",
+ "override_error_tracking_issue_fingerprint",
"reorder_assignment_rules",
"reorder_grouping_rules",
"reorder_suppression_rules",
+ "sync_issues_to_clickhouse",
"update_assignment_rule",
"update_grouping_rule",
"update_release",
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index e1f074c3cccd..c044cdc0249c 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -12,7 +12,13 @@ import posthoganalytics
from posthog.event_usage import groups
from .. import logic, weekly_digest
-from ..models import resolve_fingerprints_for_issues
+from ..models import (
+ ErrorTrackingIssue,
+ override_error_tracking_issue_fingerprint as override_error_tracking_issue_fingerprint,
+ resolve_fingerprints_for_issues,
+ sync_issues_to_clickhouse as sync_issues_to_clickhouse,
+)
+from ..remote_config import build_error_tracking_config as build_error_tracking_config
from . import contracts
IssueNotFoundError = logic.ErrorTrackingIssueNotFoundError
@@ -626,3 +632,7 @@ def get_source_maps_recommendation_for_team(team: Any) -> dict[str, Any] | None:
def build_ingestion_failures_url(team_id: int) -> str:
return weekly_digest.build_ingestion_failures_url(team_id)
+
+
+def has_resolved_issues(team_id: int) -> bool:
+ return ErrorTrackingIssue.objects.filter(team_id=team_id, status=ErrorTrackingIssue.Status.RESOLVED).exists()
diff --git a/products/error_tracking/package.json b/products/error_tracking/package.json
index 1e8cc74cd2fc..40ac2c68d526 100644
--- a/products/error_tracking/package.json
+++ b/products/error_tracking/package.json
@@ -1,7 +1,8 @@
{
"name": "@posthog/products-error-tracking",
"scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
},
"dependencies": {
"kea": "catalog:",
diff --git a/products/error_tracking/turbo.json b/products/error_tracking/turbo.json
new file mode 100644
index 000000000000..3e5f4580f6bb
--- /dev/null
+++ b/products/error_tracking/turbo.json
@@ -0,0 +1,17 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/routes.py",
+ "backend/sql.py",
+ "backend/embedding.py",
+ "backend/indexed_embedding.py"
+ ],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/products/reminders/backend/constants.py b/products/reminders/backend/constants.py
index 0a01dd18f4e8..8ec2bf89789a 100644
--- a/products/reminders/backend/constants.py
+++ b/products/reminders/backend/constants.py
@@ -1,9 +1,9 @@
+from django.apps import apps
from django.db import models
from posthog.session_recordings.models.session_recording import SessionRecording
from products.dashboards.backend.models.dashboard import Dashboard
-from products.error_tracking.backend.models import ErrorTrackingIssue
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.notebooks.backend.models import Notebook
@@ -21,7 +21,7 @@ RESOURCE_MODELS: dict[str, tuple[type[models.Model], str, str]] = {
"survey": (Survey, "pk", "surveys"),
"notebook": (Notebook, "short_id", "notebooks"),
"replay": (SessionRecording, "session_id", "replay"),
- "error_tracking": (ErrorTrackingIssue, "pk", "error_tracking"),
+ "error_tracking": (apps.get_model("error_tracking", "ErrorTrackingIssue"), "pk", "error_tracking"),
}
RESOURCE_TYPES: tuple[str, ...] = tuple(RESOURCE_MODELS.keys())
diff --git a/tach.toml b/tach.toml
index cd3c20b7a022..3f738015f6f6 100644
--- a/tach.toml
+++ b/tach.toml
@@ -844,18 +844,20 @@ from = [
"products.legal_documents",
]
-# error_tracking exposes its ClickHouse DDL (sql / embedding / indexed_embedding) to
-# core's ClickHouse schema + frozen migrations, and its models / remote_config to core
-# model-class consumers (product_intent, remote_config, team deletion) and test fixtures.
-# The frozen-migration coupling cannot be rerouted, so this block is permanent rather than
-# shrinking to zero — which is why backend:contract-check stays off for this product.
+# isolation:permanent-interface
+# error_tracking exposes its ClickHouse DDL (sql / embedding / indexed_embedding) to core's
+# ClickHouse schema registry, conftest, the embedding worker, the hogql document_embeddings
+# system table, and frozen ClickHouse migrations. That coupling is outside the import-reroute
+# path — frozen migrations hardcode these import paths and the schema registry owns table DDL —
+# so it can never route through the facade. The marker above declares it permanent rather than a
+# legacy leak, so it does not hold the external seal open. turbo.json keeps these three modules
+# in the contract-check inputs so any change to them still re-runs the Django suite
+# (IsolationChainCheck enforces that). All other core coupling now goes through backend.facade.
[[interfaces]]
expose = [
"backend\\.embedding.*",
"backend\\.indexed_embedding.*",
- "backend\\.models.*",
- "backend\\.remote_config.*",
"backend\\.sql.*",
]
from = [
diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.py
index 2041d116c8eb..c46065631d91 100644
--- a/tools/hogli-commands/hogli_commands/product/checks.py
+++ b/tools/hogli-commands/hogli_commands/product/checks.py
@@ -712,6 +712,20 @@ class IsolationChainCheck(ProductCheck):
f'routes-only change would skip the Django suite. Add "{routes_glob}" to the contract-check inputs'
)
+ # Watching the permanent-interface exposures: a marked [[interfaces]] block lets core
+ # depend on these modules outside the import graph (ClickHouse DDL in the schema registry
+ # and frozen migrations). That coupling can't be sealed, so the skip stays sound only if a
+ # change to those modules still re-runs the suite — they must be in the contract-check
+ # inputs. Mirrors routes_unwatched.
+ if has_narrowed and status.uncovered_permanent_exposures:
+ globs = ", ".join(f"{m.replace('.', '/')}.py" for m in status.uncovered_permanent_exposures)
+ result.issues.append(
+ "turbo.json narrows contract-check inputs but omits the permanently-exposed module(s) "
+ f"{', '.join(status.uncovered_permanent_exposures)} — core depends on them outside the import "
+ "graph (ClickHouse DDL in the schema registry and frozen migrations), so a change to them "
+ f"would skip the Django suite. Add the matching input(s) ({globs}) to keep the skip sound"
+ )
+
# Note: a product that has the contract-check script *and* deferred
# presentation-wave ignore_imports entries is hard-blocked by
# PackageJsonScriptsCheck — the skip can't be enabled until the wave empties them.
diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.py
index 5e65077d9f30..94638222af51 100644
--- a/tools/hogli-commands/hogli_commands/product/isolation.py
+++ b/tools/hogli-commands/hogli_commands/product/isolation.py
@@ -34,8 +34,36 @@ from .paths import REPO_ROOT, TACH_TOML, get_tach_block
# ---------------------------------------------------------------------------
-def iter_interface_blocks(tach_content: str) -> Iterator[tuple[list[str], list[str]]]:
- """Yield (expose_patterns, from_patterns) for every [[interfaces]] block."""
+# A tach [[interfaces]] block carrying this marker in the comment lines directly above it
+# exposes internals that core depends on *permanently* and outside the import-reroute path —
+# ClickHouse DDL consumed by core's schema registry and frozen migrations, which can never be
+# routed through the facade. Such a block is NOT a legacy leak: the modules stay walled off
+# from every importer except the declared consumers, and turbo.json must re-run the Django
+# suite on any change to them (enforced by IsolationChainCheck) so the skip stays sound.
+PERMANENT_INTERFACE_MARKER = "isolation:permanent-interface"
+
+
+def _block_is_permanent(tach_content: str, header_start: int) -> bool:
+ """True if the [[interfaces]] header at header_start is preceded by the permanent marker.
+
+ Scans the comment lines immediately above the header (blank lines allowed between the
+ comment and the header), stopping at the first line of TOML content — which, between two
+ blocks, is always the previous block's body, so a marker can't leak across block boundaries.
+ """
+ for line in reversed(tach_content[:header_start].splitlines()):
+ stripped = line.strip()
+ if not stripped:
+ continue
+ if stripped.startswith("#"):
+ if PERMANENT_INTERFACE_MARKER in stripped:
+ return True
+ continue
+ break
+ return False
+
+
+def _iter_interface_blocks_raw(tach_content: str) -> Iterator[tuple[list[str], list[str], bool]]:
+ """Yield (expose_patterns, from_patterns, is_permanent) for every [[interfaces]] block."""
for match in re.finditer(r"\[\[interfaces\]\]\s*\n(.*?)(?=\[\[|\Z)", tach_content, re.DOTALL):
block = match.group(1)
expose_match = re.search(r"expose\s*=\s*\[(.*?)\]", block, re.DOTALL)
@@ -44,6 +72,12 @@ def iter_interface_blocks(tach_content: str) -> Iterator[tuple[list[str], list[s
continue
expose_patterns = re.findall(r'"(.*?)"', expose_match.group(1))
from_patterns = re.findall(r'"(.*?)"', from_match.group(1))
+ yield expose_patterns, from_patterns, _block_is_permanent(tach_content, match.start())
+
+
+def iter_interface_blocks(tach_content: str) -> Iterator[tuple[list[str], list[str]]]:
+ """Yield (expose_patterns, from_patterns) for every [[interfaces]] block."""
+ for expose_patterns, from_patterns, _permanent in _iter_interface_blocks_raw(tach_content):
yield expose_patterns, from_patterns
@@ -136,8 +170,14 @@ def has_legacy_interface_leaks(tach_content: str, module_path: str) -> bool:
Detected structurally: an [[interfaces]] block whose `from` is exactly this
module and whose `expose` includes any non-facade/non-presentation pattern.
+
+ A block carrying the PERMANENT_INTERFACE_MARKER is exempt — its exposure is a
+ declared, irreducible non-import coupling (see permanent_interface_modules), not
+ a leak to be drained.
"""
- for expose_patterns, from_patterns in iter_interface_blocks(tach_content):
+ for expose_patterns, from_patterns, is_permanent in _iter_interface_blocks_raw(tach_content):
+ if is_permanent:
+ continue
normalized_from = [p.replace("\\", "") for p in from_patterns]
if normalized_from != [module_path]:
continue
@@ -146,6 +186,32 @@ def has_legacy_interface_leaks(tach_content: str, module_path: str) -> bool:
return False
+def _normalize_exposed_module(pattern: str) -> str:
+ """'backend\\.sql.*' -> 'backend.sql'; 'backend\\.embedding.*' -> 'backend.embedding'."""
+ normalized = pattern.replace("\\", "")
+ return normalized[:-2] if normalized.endswith(".*") else normalized
+
+
+def permanent_interface_modules(tach_content: str, module_path: str) -> set[str]:
+ """Module roots a product permanently exposes to core via a marked [[interfaces]] block.
+
+ These are non-import-behavioral couplings — ClickHouse DDL imported by core's schema
+ registry and frozen migrations — that cannot be rerouted through the facade. The marker
+ keeps the external seal honest rather than leaving the block to read as a temporary leak:
+ the modules stay walled off for every importer except the declared consumers, and the
+ returned set is what turbo.json must keep in its contract-check inputs so a change to them
+ still re-runs the Django suite (enforced by IsolationChainCheck).
+ """
+ modules: set[str] = set()
+ for expose_patterns, from_patterns, is_permanent in _iter_interface_blocks_raw(tach_content):
+ if not is_permanent:
+ continue
+ if [p.replace("\\", "") for p in from_patterns] != [module_path]:
+ continue
+ modules.update(_normalize_exposed_module(p) for p in expose_patterns if not pattern_targets_public_surface(p))
+ return modules
+
+
def presentation_bypass_entries(name: str, pyproject_text: str | None = None) -> list[str]:
"""import-linter ignore_imports entries that still let this product's presentation
reach its own internals directly — the deferred presentation-wave worklist.
@@ -208,19 +274,49 @@ def _input_targets_surface(glob: str) -> bool:
return glob.removeprefix("./").startswith(_FACADE_PRESENTATION_PREFIXES + _ROUTES_PREFIXES)
-def has_narrowed_turbo_inputs(product_dir: Path) -> bool:
+def _module_input_prefixes(module: str) -> tuple[str, ...]:
+ """A permanently-exposed module's accepted contract-check input forms.
+
+ 'backend.sql' -> ('backend/sql.py', 'backend/sql/') so either a single-file module or a
+ package satisfies coverage."""
+ path = module.replace(".", "/")
+ 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 has_narrowed_turbo_inputs(product_dir: Path, permanent_modules: frozenset[str] = frozenset()) -> bool:
"""True only when contract-check inputs are confined to the public surface AND at least one
targets facade/presentation. A broad glob like backend/** alongside a facade entry keeps the
skip inert, and a routes-only narrowing isn't a real contract surface — both are rejected.
- Negated globs ('!...') are excluded from the surface test."""
+ 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)."""
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) for i in inputs) and any(
+ 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
)
+def uncovered_permanent_modules(product_dir: Path, permanent_modules: frozenset[str]) -> set[str]:
+ """Permanently-exposed modules with no matching contract-check input glob.
+
+ Each such module is a non-import channel into core; if turbo.json doesn't re-run the suite
+ on its change, the skip is unsound. IsolationChainCheck turns a non-empty result into a
+ blocking 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)}
+
+
def routes_in_turbo_inputs(product_dir: Path) -> bool:
"""True if contract-check inputs watch the routes module specifically — backend/routes.py or a
backend/routes/ package. Anchored and negation-aware, so a glob that merely contains 'routes',
@@ -248,6 +344,11 @@ class IsolationStatus:
bypass_entries: tuple[str, ...] # presentation -> internals deferrals still open (the worklist)
has_contract_check_script: bool
has_narrowed_turbo: bool
+ # Module roots permanently exposed to core outside the import-reroute path (declared via the
+ # permanent-interface marker in tach.toml). They are not leaks, but turbo.json must keep them
+ # in its contract-check inputs — uncovered_permanent_exposures lists any that don't.
+ permanent_exposures: tuple[str, ...] = ()
+ uncovered_permanent_exposures: tuple[str, ...] = ()
@property
def deferred_count(self) -> int:
@@ -293,6 +394,7 @@ def compute_isolation_status(
if tach_content is None:
tach_content = TACH_TOML.read_text() if TACH_TOML.exists() else ""
module_path = f"products.{name}"
+ permanent_modules = frozenset(permanent_interface_modules(tach_content, module_path))
return IsolationStatus(
name=name,
is_isolated=is_isolated,
@@ -301,5 +403,7 @@ 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),
+ has_narrowed_turbo=has_narrowed_turbo_inputs(product_dir, permanent_modules),
+ permanent_exposures=tuple(sorted(permanent_modules)),
+ uncovered_permanent_exposures=tuple(sorted(uncovered_permanent_modules(product_dir, permanent_modules))),
)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.py
index 90184fb86a74..b14f4dfda692 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py
@@ -25,7 +25,12 @@ from hogli_commands.product.checks import (
validate_interface_blocks,
validate_tach_references,
)
-from hogli_commands.product.isolation import has_narrowed_turbo_inputs, routes_in_turbo_inputs
+from hogli_commands.product.isolation import (
+ has_narrowed_turbo_inputs,
+ permanent_interface_modules,
+ routes_in_turbo_inputs,
+ uncovered_permanent_modules,
+)
# ---------------------------------------------------------------------------
# Helpers
@@ -675,6 +680,111 @@ from = [
assert has_legacy_interface_leaks(_TACH_SAMPLE, "products.mcp") is False
+# ---------------------------------------------------------------------------
+# permanent-interface marker
+# ---------------------------------------------------------------------------
+
+_TACH_PERMANENT = """\
+# Facade + views: canonical public surface
+[[interfaces]]
+expose = [
+ "backend\\.facade.*",
+ "backend\\.presentation\\.views.*",
+]
+from = [
+ "products\\.(error_tracking|experiments)",
+]
+
+# isolation:permanent-interface
+# error_tracking exposes its ClickHouse DDL to core's schema registry + frozen migrations.
+[[interfaces]]
+expose = [
+ "backend\\.embedding.*",
+ "backend\\.indexed_embedding.*",
+ "backend\\.sql.*",
+]
+from = [
+ "products.error_tracking",
+]
+
+# Legacy leaks — experiments (unmarked, a real leak)
+[[interfaces]]
+expose = [
+ "backend\\.models.*",
+]
+from = [
+ "products.experiments",
+]
+"""
+
+
+class TestPermanentInterface:
+ def test_marked_block_is_not_a_leak(self) -> None:
+ # The DDL exposure carries the marker, so it must not hold the external seal open.
+ assert has_legacy_interface_leaks(_TACH_PERMANENT, "products.error_tracking") is False
+
+ def test_unmarked_block_is_still_a_leak(self) -> None:
+ # The experiments block exposes internals with no marker — a genuine leak.
+ assert has_legacy_interface_leaks(_TACH_PERMANENT, "products.experiments") is True
+
+ def test_marker_does_not_leak_across_blocks(self) -> None:
+ # The marker sits above the error_tracking block; the previous block's body separates
+ # it from the facade block, so the facade block is not mistaken for permanent (and the
+ # experiments leak below stays a leak — already covered above).
+ assert permanent_interface_modules(_TACH_PERMANENT, "products.experiments") == set()
+
+ def test_exposed_modules_returned(self) -> None:
+ assert permanent_interface_modules(_TACH_PERMANENT, "products.error_tracking") == {
+ "backend.embedding",
+ "backend.indexed_embedding",
+ "backend.sql",
+ }
+
+ def test_unmarked_exposure_is_not_permanent(self) -> None:
+ assert permanent_interface_modules(_TACH_SAMPLE, "products.experiments") == set()
+
+ @pytest.mark.parametrize(
+ "inputs, expected",
+ [
+ # the three DDL modules + facade satisfy the extended-surface narrowing
+ (["backend/facade/**", "backend/sql.py", "backend/embedding.py", "backend/indexed_embedding.py"], True),
+ # facade alone still narrows (permanent modules are allowed, not required, here)
+ (["backend/facade/**"], True),
+ # a broad glob alongside still keeps the skip inert
+ (["backend/**", "backend/sql.py"], False),
+ # a permanent module without any facade/presentation glob is not a real surface
+ (["backend/sql.py"], False),
+ ],
+ )
+ def test_permanent_modules_count_as_extended_surface(
+ self, tmp_path: Path, inputs: list[str], expected: bool
+ ) -> None:
+ (tmp_path / "turbo.json").write_text(json.dumps({"tasks": {"backend:contract-check": {"inputs": inputs}}}))
+ permanent = frozenset({"backend.sql", "backend.embedding", "backend.indexed_embedding"})
+ assert has_narrowed_turbo_inputs(tmp_path, permanent) is expected
+
+ def test_uncovered_permanent_modules_detected(self, tmp_path: Path) -> None:
+ (tmp_path / "turbo.json").write_text(
+ json.dumps({"tasks": {"backend:contract-check": {"inputs": ["backend/facade/**", "backend/sql.py"]}}})
+ )
+ permanent = frozenset({"backend.sql", "backend.embedding", "backend.indexed_embedding"})
+ assert uncovered_permanent_modules(tmp_path, permanent) == {"backend.embedding", "backend.indexed_embedding"}
+
+ def test_all_permanent_modules_covered(self, tmp_path: Path) -> None:
+ (tmp_path / "turbo.json").write_text(
+ json.dumps(
+ {
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": ["backend/facade/**", "backend/sql.py", "backend/embedding.py"]
+ }
+ }
+ }
+ )
+ )
+ assert uncovered_permanent_modules(tmp_path, frozenset({"backend.sql", "backend.embedding"})) == set()
+
+
# ---------------------------------------------------------------------------
# ProductYamlCheck
# ---------------------------------------------------------------------------