Skip to content

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

fix(devex): close isolation skip soundness holes in product lint (#128069)

Julian Bezff6c1e8b8011
diff --git a/products/alerts_platform/turbo.json b/products/alerts_platform/turbo.json
index 2ed03ebce7eb..1ff7e1cd9b3f 100644
--- a/products/alerts_platform/turbo.json
+++ b/products/alerts_platform/turbo.json
@@ -6,6 +6,9 @@
"backend/facade/**",
"backend/presentation/**",
"backend/routes.py",
+ "backend/delivery/email.py",
+ "backend/delivery/pagerduty.py",
+ "backend/delivery/team_flags.py",
"backend/models/**",
"backend/temporal/**",
"backend/migrations/**"
diff --git a/products/analytics_platform/backend/api/__init__.py b/products/analytics_platform/backend/api/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/architecture.md b/products/architecture.md
index 4b240fa740f0..35d445392536 100644
--- a/products/architecture.md
+++ b/products/architecture.md
@@ -82,6 +82,8 @@ Because this channel can't be enumerated, it is closed by construction rather th
A model is reachable with no import: `apps.get_model("label", "Class")`, migrations, admin, fixtures.
tach cannot see that, so a model or migration change always re-runs the full suite.
`hogli product:lint` blocks a narrowing that leaves the surface out.
+4. Keep in the inputs every module that outside suites run without an import: a module with a signal receiver on a sender of core or another product, a module that a test outside the product names by dotted path, as a patch target does, and a module that core loads by name through `load_product_modules`.
+ `hogli product:lint` finds both and fails until each module is in the inputs.
A product whose views still hold business logic is not soundly skippable even if nothing imports it.
This 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.
diff --git a/products/authorization/turbo.json b/products/authorization/turbo.json
index 0f13f3b421f9..4dce81889aff 100644
--- a/products/authorization/turbo.json
+++ b/products/authorization/turbo.json
@@ -7,6 +7,8 @@
"backend/presentation/**",
"backend/webhook_consumers.py",
"backend/tasks/**",
+ "backend/apps.py",
+ "backend/logic/session.py",
"backend/models.py",
"backend/migrations/**"
],
diff --git a/products/autoresearch/turbo.json b/products/autoresearch/turbo.json
index d6c8e16283b9..f721f426e955 100644
--- a/products/autoresearch/turbo.json
+++ b/products/autoresearch/turbo.json
@@ -7,6 +7,8 @@
"backend/presentation/**",
"backend/routes.py",
"backend/temporal/**",
+ "backend/apps.py",
+ "backend/signals.py",
"backend/models.py",
"backend/migrations/**"
],
diff --git a/products/commands/turbo.json b/products/commands/turbo.json
index 51fc5e97a7b0..a0833aa20fcc 100644
--- a/products/commands/turbo.json
+++ b/products/commands/turbo.json
@@ -6,6 +6,7 @@
"backend/facade/**",
"backend/webhook_consumers.py",
"backend/tasks/**",
+ "backend/receivers.py",
"backend/migrations/**"
],
"outputs": [],
diff --git a/products/customer_analytics/turbo.json b/products/customer_analytics/turbo.json
index e9f285d53d98..753184ea6ebd 100644
--- a/products/customer_analytics/turbo.json
+++ b/products/customer_analytics/turbo.json
@@ -11,6 +11,7 @@
"backend/max_tools.py",
"backend/tasks/**",
"backend/temporal/**",
+ "backend/signals.py",
"backend/models/**",
"backend/migrations/**"
],
diff --git a/products/error_tracking/turbo.json b/products/error_tracking/turbo.json
index 8bb3273e238f..198e8a581c23 100644
--- a/products/error_tracking/turbo.json
+++ b/products/error_tracking/turbo.json
@@ -14,6 +14,7 @@
"backend/temporal/**",
"backend/tasks/**",
"backend/webhook_consumers.py",
+ "backend/data_freshness.py",
"backend/models.py",
"backend/migrations/**"
],
diff --git a/products/knowledge_writer/turbo.json b/products/knowledge_writer/turbo.json
index 7b89954b9ee4..1d8b859c9c57 100644
--- a/products/knowledge_writer/turbo.json
+++ b/products/knowledge_writer/turbo.json
@@ -8,6 +8,10 @@
"backend/webhook_consumers.py",
"backend/tasks/**",
"backend/temporal/**",
+ "backend/feature_flags.py",
+ "backend/logic/intake.py",
+ "backend/receivers.py",
+ "backend/settings.py",
"backend/migrations/**"
],
"outputs": [],
diff --git a/products/managed_warehouse/turbo.json b/products/managed_warehouse/turbo.json
index 2ef5864f8b1a..8322996c63c2 100644
--- a/products/managed_warehouse/turbo.json
+++ b/products/managed_warehouse/turbo.json
@@ -17,6 +17,8 @@
"backend/presentation/**",
"backend/temporal/**",
"backend/tasks/**",
+ "backend/logic/sql_editor_trino.py",
+ "backend/managed_ingress.py",
"backend/models.py",
"backend/migrations/**"
],
diff --git a/products/metrics/turbo.json b/products/metrics/turbo.json
index 453fda78fe96..8bf8dcd66e50 100644
--- a/products/metrics/turbo.json
+++ b/products/metrics/turbo.json
@@ -9,6 +9,8 @@
"backend/hogql_queries/**",
"backend/tasks/**",
"backend/temporal/**",
+ "backend/metric_query_runner.py",
+ "backend/dashboard_import/receivers.py",
"backend/models.py",
"backend/migrations/**"
],
diff --git a/products/product_analytics/turbo.json b/products/product_analytics/turbo.json
index 6b64e49f7047..0495d0b02351 100644
--- a/products/product_analytics/turbo.json
+++ b/products/product_analytics/turbo.json
@@ -6,6 +6,7 @@
"backend/facade/**",
"backend/presentation/**",
"backend/routes.py",
+ "backend/data_freshness.py",
"backend/models/**",
"backend/migrations/**",
"backend/temporal/**",
diff --git a/products/review_hog/turbo.json b/products/review_hog/turbo.json
index 908ed09e3c03..e6a0e6d41c04 100644
--- a/products/review_hog/turbo.json
+++ b/products/review_hog/turbo.json
@@ -9,6 +9,7 @@
"backend/webhook_consumers.py",
"backend/tasks/**",
"backend/temporal/**",
+ "backend/receivers.py",
"backend/models.py",
"backend/migrations/**"
],
diff --git a/products/signals/backend/activity_summary/__init__.py b/products/signals/backend/activity_summary/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/turbo.json b/products/warehouse_sources/turbo.json
index 875d96621911..fe1a9ba0cf2a 100644
--- a/products/warehouse_sources/turbo.json
+++ b/products/warehouse_sources/turbo.json
@@ -6,11 +6,17 @@
"backend/facade/**",
"backend/presentation/**",
"backend/routes.py",
+ "backend/data_freshness.py",
+ "backend/integration_usages.py",
"backend/models/**",
"backend/migrations/**",
"backend/tasks/**",
+ "backend/activity_logging.py",
+ "backend/file_upload_sources.py",
"backend/temporal/data_imports/naming_convention.py",
+ "backend/temporal/data_imports/pipelines/core/account_property_row_sink.py",
"backend/temporal/data_imports/pipelines/core/consts.py",
+ "backend/temporal/data_imports/pipelines/core/person_property_row_sink.py",
"backend/temporal/data_imports/sources/generated_configs/__init__.py",
"backend/temporal/data_imports/sources/generated_configs/bigquery.py",
"backend/temporal/data_imports/sources/generated_configs/clickhouse.py",
@@ -29,6 +35,7 @@
"backend/temporal/data_imports/sources/bigquery/**",
"backend/temporal/data_imports/sources/clickhouse/**",
"backend/temporal/data_imports/sources/common/**",
+ "backend/temporal/data_imports/sources/file_upload/storage.py",
"backend/temporal/data_imports/sources/google_search_console/**",
"backend/temporal/data_imports/sources/motherduck/**",
"backend/temporal/data_imports/sources/mssql/**",
diff --git a/products/workflows/turbo.json b/products/workflows/turbo.json
index 156e9dd206df..920c1d8398a9 100644
--- a/products/workflows/turbo.json
+++ b/products/workflows/turbo.json
@@ -9,7 +9,11 @@
"backend/webhook_consumers.py",
"backend/tasks/**",
"backend/max_tools.py",
+ "backend/integration_usages.py",
+ "backend/receivers.py",
+ "backend/data_freshness.py",
"backend/models/**",
+ "backend/providers/ses.py",
"backend/migrations/**"
],
"outputs": [],
diff --git a/pyproject.toml b/pyproject.toml
index e72cefffc7e6..798bb86c26d5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -810,6 +810,14 @@ ignore_imports = [
"products.access_control.backend.presentation.access_control_settings -> products.access_control.backend.models.access_control",
"products.access_control.backend.presentation.access_control_settings -> products.access_control.backend.models.role",
"products.access_control.backend.presentation.role -> products.access_control.backend.models.role",
+ # TODO: signals presentation wave. The activity summary viewset reads its modes, limits and
+ # render types from backend/activity_summary/ directly. That directory has no __init__.py, so
+ # grimp cannot see these edges and only the AST surface check in `hogli product:lint` holds
+ # them. Expose what the view needs through the facade and delete each entry.
+ "products.signals.backend.presentation.activity_summary -> products.signals.backend.activity_summary.prompt",
+ "products.signals.backend.presentation.activity_summary -> products.signals.backend.activity_summary.read",
+ "products.signals.backend.presentation.activity_summary -> products.signals.backend.activity_summary.render",
+ "products.signals.backend.presentation.activity_summary -> products.signals.backend.activity_summary.search",
]
# routes.py is the one module core reads to assemble a product's API router, so it is the
@@ -831,6 +839,7 @@ ignore_imports = [
# TODO: views still registered from backend/api/ — move them into presentation/ and drop the line
"products.actions.backend.routes -> products.actions.backend.api.action",
"products.ai_observability.backend.routes -> products.ai_observability.backend.api",
+ "products.analytics_platform.backend.routes -> products.analytics_platform.backend.api.precompute_debug",
"products.annotations.backend.routes -> products.annotations.backend.api.annotation",
"products.approvals.backend.routes -> products.approvals.backend.api",
"products.business_knowledge.backend.routes -> products.business_knowledge.backend.api",
diff --git a/tach.toml b/tach.toml
index 7a0d9b41a387..8fec22ae1020 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1230,7 +1230,7 @@ expose = [
"backend\\.routes.*",
]
from = [
- "products\\.(autoresearch|batch_exports|canvas|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|groups|managed_warehouse|mcp_analytics|mcp_store|messaging|metrics|notebooks|notifications|streamlit_apps|subscriptions|tasks|tracing|visual_review|warehouse_sources|workflows)",
+ "products\\.(autoresearch|batch_exports|canvas|customer_analytics|data_modeling|data_warehouse|demo|endpoints|error_tracking|experiments|groups|managed_warehouse|mcp_analytics|mcp_store|messaging|metrics|notebooks|notifications|review_hog|streamlit_apps|subscriptions|tasks|tracing|visual_review|warehouse_sources|workflows)",
]
# signals is not isolated, so it gets its own blocks instead of a place in the shared one above.
diff --git a/tools/hogli-commands/hogli_commands/product/ast_helpers.py b/tools/hogli-commands/hogli_commands/product/ast_helpers.py
index e140a925db75..dc173eba78e1 100644
--- a/tools/hogli-commands/hogli_commands/product/ast_helpers.py
+++ b/tools/hogli-commands/hogli_commands/product/ast_helpers.py
@@ -38,6 +38,24 @@ def get_imported_module_names(tree: ast.Module) -> set[str]:
return imported
+def product_app_labels(products_dir: Path) -> dict[str, str]:
+ """Django app label -> product name, read off each product's AppConfig."""
+ labels: dict[str, str] = {}
+ for apps_py in sorted(products_dir.glob("*/backend/apps.py")):
+ product = apps_py.parents[1].name
+ try:
+ tree = ast.parse(apps_py.read_text(encoding="utf-8", errors="ignore"))
+ except (SyntaxError, OSError):
+ continue
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Assign):
+ continue
+ target = node.targets[0]
+ if isinstance(target, ast.Name) and target.id == "label" and isinstance(node.value, ast.Constant):
+ labels[str(node.value.value)] = product
+ return labels
+
+
# The bases a Django model reaches. `Model` is django.db.models.Model under both the bare and the
# `models.Model` spelling, because _base_names keeps the attribute and drops the module. The rest are
# the abstract bases posthog/models/utils.py and posthog/models/scoping/ export, every one of which
@@ -534,7 +552,7 @@ def _importing_package(file_path: Path, package_root: Path, package_prefix: str)
return ".".join([package_prefix, *file_path.relative_to(package_root).parent.parts])
-def _import_from_module(node: ast.ImportFrom, package: str) -> str | None:
+def import_from_module(node: ast.ImportFrom, package: str) -> str | None:
"""The absolute module an `ImportFrom` reads from, with relative forms resolved.
None when the import climbs past the top of the package and so names nothing.
@@ -575,7 +593,7 @@ def module_import_targets(file_path: Path, package_root: Path, package_prefix: s
if isinstance(node, ast.Import):
targets.extend((node.lineno, a.name) for a in node.names if a.name.startswith(prefix_dot))
elif isinstance(node, ast.ImportFrom):
- module = _import_from_module(node, package)
+ module = import_from_module(node, package)
if not module or (module != package_prefix and not module.startswith(prefix_dot)):
continue
for alias in node.names:
diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.py
index 3f6373de8b5c..4c2785430e09 100644
--- a/tools/hogli-commands/hogli_commands/product/checks.py
+++ b/tools/hogli-commands/hogli_commands/product/checks.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import re
import json
import shlex
+import tomllib
from abc import ABC, abstractmethod
from collections.abc import Iterator
from dataclasses import dataclass, field
@@ -36,9 +37,11 @@ from .isolation import (
names_from_pattern as _names_from_pattern,
pattern_targets_public_surface as _pattern_targets_public_surface,
routes_in_turbo_inputs,
+ unwatched_modules,
webhook_consumers_unwatched,
)
from .paths import TACH_TOML, get_tach_block
+from .watched_channels import unwatched_channel_issue
from .wiring_interfaces import APPROVED_WIRING_BASES, APPROVED_WIRING_DECORATORS, WiringVerdict
# ---------------------------------------------------------------------------
@@ -59,15 +62,17 @@ def check_file_exists(backend_dir: Path, path: str) -> bool:
def _iter_module_blocks(tach_content: str) -> Iterator[tuple[str, list[str]]]:
- """Yield (path, depends_on) for every [[modules]] block."""
- for match in re.finditer(r"\[\[modules\]\]\s*\n(.*?)(?=\[\[|\Z)", tach_content, re.DOTALL):
- block = match.group(1)
- path_match = re.search(r'path\s*=\s*"(.*?)"', block)
- if not path_match:
+ """Yield (path, depends_on) for every [[modules]] block.
+
+ Reads the parsed TOML because a comment inside a depends_on list can name `[[interfaces]]`,
+ which ends a text match early and drops the rest of the list.
+ """
+ for module in tomllib.loads(tach_content).get("modules", []):
+ path = module.get("path")
+ if not path:
continue
- path = path_match.group(1)
- deps_match = re.search(r"depends_on\s*=\s*\[(.*?)\]", block, re.DOTALL)
- depends_on = re.findall(r'"(.*?)"', deps_match.group(1)) if deps_match else []
+ # tach accepts a dependency as a bare path or as a table such as {path = "...", deprecated = true}.
+ depends_on = [dep if isinstance(dep, str) else dep["path"] for dep in module.get("depends_on", [])]
yield path, depends_on
@@ -458,26 +463,19 @@ class ImportSurfaceCheck(ProductCheck):
watch. This check reads the same imports straight from the AST, honors the same
ignore_imports deferrals, and fails on what grimp cannot see.
- A product that is not sealed yet holds the webhook_consumers surface alone: posthog/ingress/
- imports that module by name and must not reach the product's internals through it, whether or
- not the product has a contract.
+ The contracts name `products.*.backend.<surface>`, so they hold for every product whether or
+ not it has facade/contracts.py, and this check holds every surface for every product too.
"""
label = "import surface"
# (source subtree or module, allowed destination subtrees)
- WEBHOOK_CONSUMERS_SURFACE = ("webhook_consumers", ("facade",))
SURFACES = (
("routes", ("presentation",)),
("presentation", ("presentation", "facade")),
- WEBHOOK_CONSUMERS_SURFACE,
+ ("webhook_consumers", ("facade",)),
)
- def _surfaces(self, ctx: CheckContext) -> tuple[tuple[str, tuple[str, ...]], ...]:
- """A product that is not sealed yet has no routes/presentation contract to hold, so
- only its ingress entry point is checked."""
- return self.SURFACES if ctx.has_facade_contracts else (self.WEBHOOK_CONSUMERS_SURFACE,)
-
def _surface_files(self, ctx: CheckContext, source: str) -> list[Path]:
root = ctx.backend_dir / source
files = [root.with_suffix(".py")] if root.with_suffix(".py").exists() else []
@@ -488,7 +486,7 @@ class ImportSurfaceCheck(ProductCheck):
def should_run(self, ctx: CheckContext) -> bool:
if not super().should_run(ctx) or not ctx.backend_dir.is_dir():
return False
- return any(self._surface_files(ctx, source) for source, _ in self._surfaces(ctx))
+ return any(self._surface_files(ctx, source) for source, _ in self.SURFACES)
def _module_name(self, ctx: CheckContext, path: Path) -> str:
rel = path.relative_to(ctx.backend_dir).with_suffix("")
@@ -499,7 +497,7 @@ class ImportSurfaceCheck(ProductCheck):
prefix = f"products.{ctx.name}.backend"
ignored = ignored_import_edges()
issues = []
- for source, allowed in self._surfaces(ctx):
+ for source, allowed in self.SURFACES:
allowed_prefixes = tuple(f"{prefix}.{a}" for a in allowed)
for f in self._surface_files(ctx, source):
importer = self._module_name(ctx, f)
@@ -510,9 +508,9 @@ class ImportSurfaceCheck(ProductCheck):
continue
issues.append(
f"{f.relative_to(ctx.product_dir)}:{line} imports {target} — {source} may only import "
- f"{'/'.join(allowed)}. If import-linter did not flag this, either the target sits "
- "under a directory without __init__.py, which grimp cannot see, or this product "
- "carries no contract yet"
+ f"{'/'.join(allowed)}. If import-linter did not flag this, the target sits under a "
+ "directory without __init__.py, which grimp cannot see. To defer the edge, add that "
+ "__init__.py first: import-linter rejects an ignore_imports entry it cannot match"
)
if issues:
return CheckResult(
@@ -1359,6 +1357,33 @@ class OrphanedTestFilesCheck(ProductCheck):
return result
+class WatchedChannelsCheck(ProductCheck):
+ """Hold the modules that outside suites run without an import edge in the contract-check inputs.
+
+ watched_channels.py finds them: receivers on a sender the product does not own, and modules that
+ outside tests name by dotted path. Only a product with 'backend:contract-check' skips the suite,
+ so no other product runs this check.
+ """
+
+ label = "watched channels"
+
+ def should_run(self, ctx: CheckContext) -> bool:
+ return super().should_run(ctx) and ctx.isolation_status().has_contract_check_script
+
+ def run(self, ctx: CheckContext) -> CheckResult:
+ channels = ctx.isolation_status().channel_modules
+ unwatched = unwatched_modules(ctx.product_dir, {c.path for c in channels})
+ result = CheckResult(file=f"products/{ctx.name}/turbo.json")
+ result.issues = [
+ unwatched_channel_issue(path, [c for c in channels if c.path == path]) for path in sorted(unwatched)
+ ]
+ if result.issues:
+ result.lines = [f"✗ {len(result.issues)} issue(s)"] + [f" → {i}" for i in result.issues]
+ else:
+ result.lines = ["✓ ok"]
+ return result
+
+
CHECKS: list[ProductCheck] = [
ProductYamlCheck(),
RequiredRootFilesCheck(),
@@ -1371,5 +1396,6 @@ CHECKS: list[ProductCheck] = [
IsolationChainCheck(),
FacadeShapeCheck(),
WiringInterfaceCheck(),
+ WatchedChannelsCheck(),
OrphanedTestFilesCheck(),
]
diff --git a/tools/hogli-commands/hogli_commands/product/crossings.py b/tools/hogli-commands/hogli_commands/product/crossings.py
index c5d9b6c831dd..f5acda1ab50c 100644
--- a/tools/hogli-commands/hogli_commands/product/crossings.py
+++ b/tools/hogli-commands/hogli_commands/product/crossings.py
@@ -64,7 +64,7 @@ from pathlib import Path
from posthog.dataclasses import frozen
-from .ast_helpers import ast_parse_safe, get_model_names, lazy_reexport_map, lazy_reexport_prefixes
+from .ast_helpers import ast_parse_safe, get_model_names, lazy_reexport_map, lazy_reexport_prefixes, product_app_labels
from .isolation import (
COMPUTED_WIRING_LOCATIONS,
MODEL_CROSSINGS,
@@ -239,24 +239,6 @@ def crossing_classes(products: Iterable[str] | None = None) -> list[CrossingClas
return resolved
-def _app_labels() -> dict[str, str]:
- """Django app label -> product name, read off each product's AppConfig."""
- labels: dict[str, str] = {}
- for apps_py in sorted(PRODUCTS_DIR.glob("*/backend/apps.py")):
- product = apps_py.parents[1].name
- try:
- tree = ast.parse(apps_py.read_text(encoding="utf-8", errors="ignore"))
- except (SyntaxError, OSError):
- continue
- for node in ast.walk(tree):
- if not isinstance(node, ast.Assign):
- continue
- target = node.targets[0]
- if isinstance(target, ast.Name) and target.id == "label" and isinstance(node.value, ast.Constant):
- labels[str(node.value.value)] = product
- return labels
-
-
def product_model_labels(products: Iterable[str] | None = None) -> dict[str, str]:
"""`product.Class` -> owning product, for every model class a product's app registers.
@@ -264,7 +246,7 @@ def product_model_labels(products: Iterable[str] | None = None) -> dict[str, str
through the app registry, so neither tach nor import-linter sees the edge and the watched-models
allowance never had to name the class. The label scan therefore covers every product model, not
only the allowance ones. A product without an `apps.py` registers nothing and is skipped."""
- registered = set(_app_labels().values())
+ registered = set(product_app_labels(PRODUCTS_DIR).values())
wanted = registered if products is None else registered & set(products)
return {
f"{product}.{class_name}": product
@@ -1559,7 +1541,7 @@ def scan_crossing_uses(products: Iterable[str] | None = None) -> list[CrossingUs
origins = _grow_origins(candidates, seeds)
origin_modules = {export.module for export in origins}
query_products = {location.product for location in locations if location.location == QUERY_WIRING_LOCATION}
- product_by_label = _app_labels()
+ product_by_label = product_app_labels(PRODUCTS_DIR)
# Django resolves a model name case-insensitively, so the get_model scan matches on the lowered form.
label_by_lower = {label.lower(): label for label in owning_dir}
diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.py
index ea3848822257..277ae4751116 100644
--- a/tools/hogli-commands/hogli_commands/product/isolation.py
+++ b/tools/hogli-commands/hogli_commands/product/isolation.py
@@ -24,7 +24,7 @@ import ast
import json
import tomllib
import functools
-from collections.abc import Iterator, Sequence
+from collections.abc import Iterable, Iterator, Sequence
from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
@@ -54,7 +54,8 @@ from .import_resolution import (
resolve_absolute_module,
source_file,
)
-from .paths import REPO_ROOT, TACH_TOML, get_tach_block
+from .paths import REPO_ROOT, TACH_TOML
+from .watched_channels import ChannelModule, find_channel_modules
from .wiring_interfaces import WiringInterfaceResolver, WiringVerdict
# ---------------------------------------------------------------------------
@@ -168,21 +169,17 @@ def has_routes_module(backend_dir: Path) -> bool:
def has_tach_interface(name: str, tach_content: str | None = None) -> bool:
- """True if the product is named in a tach [[interfaces]] block (inline or global).
+ """True if the product is named in the `from` list of a tach [[interfaces]] table.
- Names are matched structurally against each block's `from` list. A loose regex
- over the whole file false-positives on any product whose name appears later (e.g.
- in its own [[modules]] block), which made nearly every product read as sealed.
+ Names are matched against the parsed TOML, so a comment that mentions `[[interfaces]]`
+ or a neighbouring block's table cannot count. A loose match over the file text
+ false-positives on any product whose name or block text happens to contain the word.
+ [[interfaces]] is the only form tach reads: it rejects an `interfaces` key on a
+ [[modules]] table.
"""
- block = get_tach_block(f"products.{name}")
- if block and "interfaces" in block and "interfaces = []" not in block:
- return True
content = tach_content if tach_content is not None else (TACH_TOML.read_text() if TACH_TOML.exists() else "")
- return any(
- name in names_from_pattern(pattern)
- for _expose, from_patterns in iter_interface_blocks(content)
- for pattern in from_patterns
- )
+ interface_tables = tomllib.loads(content).get("interfaces", [])
+ return any(name in names_from_pattern(pattern) for table in interface_tables for pattern in table.get("from", []))
def has_legacy_interface_leaks(tach_content: str, module_path: str) -> bool:
@@ -417,17 +414,18 @@ def has_narrowed_turbo_inputs(
permanent_modules: frozenset[str] = frozenset(),
carveout_modules: frozenset[str] = frozenset(),
model_surface: tuple[str, ...] = (),
+ channel_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.
- Permanently-exposed modules, wiring locations, carve-out modules, and the model surface
- 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/model coverage
- checks).
+ Permanently-exposed modules, wiring locations, carve-out modules, the model surface, and the
+ modules outside suites run without an import edge (watched_channels.py) 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/model coverage checks).
A webhook_consumers.py module is the one extended surface that is also required once it exists:
listing it is optional for a product that has none, mandatory for a product that has one, and
@@ -447,6 +445,7 @@ def has_narrowed_turbo_inputs(
+ permanent_prefixes
+ tuple(carveout_modules)
+ model_surface
+ + tuple(channel_modules)
)
return all(_glob_targets(i, accepted) for i in inputs) and any(
_glob_targets(i, _FACADE_PRESENTATION_PREFIXES) for i in inputs
@@ -999,6 +998,25 @@ def uncovered_carveout_modules(product_dir: Path, carveout_modules: frozenset[st
return _uncovered_locations(product_dir, {m: (m,) for m in carveout_modules})
+def unwatched_modules(product_dir: Path, modules: Iterable[str]) -> set[str]:
+ """Module files, relative to the product, that the narrowed contract-check inputs do not watch.
+
+ Empty when the product has no narrowing override, because the inputs then watch everything.
+ Negations are read conservatively, like _webhook_consumers_unwatched reads them: a negation that
+ may reach the file leaves it unwatched, because the safe failure is a suite that runs."""
+ raw = contract_check_inputs(product_dir)
+ positive = [i.removeprefix("./") for i in raw if not i.startswith("!")]
+ if not positive:
+ return set()
+ negations = [i.removeprefix("!").removeprefix("./") for i in raw if i.startswith("!")]
+ return {
+ module
+ for module in modules
+ if any(_input_covers(n, module) or _literal_prefix_overlaps(n, module) for n in negations)
+ or not any(_input_covers(i, module) for i in positive)
+ }
+
+
def unwatched_model_surface(product_dir: Path) -> set[str]:
"""Model-surface locations present in the product but not wholly watched by its (narrowed)
contract-check inputs. Every narrowed product must watch its models and migrations: a model is
@@ -1794,6 +1812,8 @@ class IsolationStatus:
# Classes from wiring locations without an approved interface (see facade_unapproved_wiring).
# Information below the Isolated rung; on an Isolated product each one needs a ledger row.
unapproved_wiring: tuple[UnapprovedWiringClass, ...] = ()
+ # Read only for a product with 'backend:contract-check', the one kind that skips the suite.
+ channel_modules: tuple[ChannelModule, ...] = ()
@property
def deferred_count(self) -> int:
@@ -1861,6 +1881,8 @@ def compute_isolation_status(
permanent_modules = frozenset(permanent_interface_modules(tach_content, module_path))
reexports = _split_facade_reexports(backend_dir, name)
carveout_modules = reexports.carveout_modules
+ has_script = has_contract_check_script(product_dir)
+ channel_modules = find_channel_modules(product_dir, repo_root) if has_script else ()
return IsolationStatus(
name=name,
has_facade_contracts=has_facade_contracts,
@@ -1868,9 +1890,13 @@ def compute_isolation_status(
has_tach_interface=has_tach_interface(name, tach_content),
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_contract_check_script=has_script,
has_narrowed_turbo=has_narrowed_turbo_inputs(
- product_dir, permanent_modules, carveout_modules, MODEL_SURFACE_PREFIXES
+ product_dir,
+ permanent_modules,
+ carveout_modules,
+ MODEL_SURFACE_PREFIXES,
+ frozenset(c.path for c in channel_modules),
),
permanent_exposures=tuple(sorted(permanent_modules)),
uncovered_permanent_exposures=tuple(sorted(uncovered_permanent_modules(product_dir, permanent_modules))),
@@ -1884,4 +1910,5 @@ def compute_isolation_status(
model_crossings=reexports.model_crossings,
uncovered_model_surface=tuple(sorted(unwatched_model_surface(product_dir))),
unapproved_wiring=tuple(facade_unapproved_wiring(backend_dir, name)),
+ channel_modules=channel_modules,
)
diff --git a/tools/hogli-commands/hogli_commands/product/maturity.py b/tools/hogli-commands/hogli_commands/product/maturity.py
index 2d7e641fcd51..bd133ec8d154 100644
--- a/tools/hogli-commands/hogli_commands/product/maturity.py
+++ b/tools/hogli-commands/hogli_commands/product/maturity.py
@@ -623,9 +623,8 @@ def score_boundaries(
score += 5
parts.append("tach (no interfaces)")
next_steps.append(
- f'Add `interfaces = ["products.{name}.backend.facade.*", '
- f'"products.{name}.backend.presentation.*"]` to the [[modules]] entry in '
- f"tach.toml so tach enforces what's public."
+ f"Add {name} to the `from` regex of the shared [[interfaces]] block in tach.toml that "
+ f"exposes `backend.facade.*` and `backend.presentation.views.*`, so tach enforces what's public."
)
# Cross-product depends_on: each one is an explicit coupling
@@ -645,8 +644,9 @@ def score_boundaries(
else:
parts.append("not in tach.toml")
next_steps.append(
- f"Add a [[modules]] entry for products.{name} to tach.toml with explicit "
- f"`depends_on` and `interfaces`. Without it, tach won't catch boundary regressions."
+ f"Add a [[modules]] entry for products.{name} to tach.toml with an explicit "
+ f"`depends_on`, and name it in an [[interfaces]] block. Without them, tach won't catch "
+ f"boundary regressions."
)
# Outbound: this product importing other products' internals
diff --git a/tools/hogli-commands/hogli_commands/product/watched_channels.py b/tools/hogli-commands/hogli_commands/product/watched_channels.py
new file mode 100644
index 000000000000..940be0e79cb6
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/product/watched_channels.py
@@ -0,0 +1,490 @@
+"""Product modules that outside suites run without an import edge.
+
+An Isolated product skips the full Django suite when a change touches only files outside its
+`backend:contract-check` inputs (products/architecture.md § What makes the skip sound). tach and
+import-linter prove that no outside code imports past the facade. Three channels run a product module
+in an outside suite with no import, so those checks cannot see them:
+
+- A signal receiver on a sender the product does not own. It runs inside the save and delete paths
+ of every suite that writes the sender.
+- A test outside the product that names a product module by its dotted path, which is how a patch
+ target is written. The test depends on the names in that module and runs the code around them.
+- A module that core loads by name through `load_product_modules(...)`, such as
+ `integration_usages` or `data_freshness`. Core imports it for every product that has one.
+
+This module finds the module files each channel reaches. It reads source and never imports it.
+isolation.py accepts these files as contract-check inputs, and the lint fails while one is unwatched.
+"""
+
+from __future__ import annotations
+
+import re
+import ast
+import functools
+from collections.abc import Iterator, Mapping, Sequence
+from enum import StrEnum
+from pathlib import Path
+
+from posthog.dataclasses import frozen
+
+from .ast_helpers import ast_parse_safe, decorator_name, import_from_module, product_app_labels
+from .paths import FIRST_PARTY_ROOTS
+
+_SKIPPED_DIRS: frozenset[str] = frozenset({"node_modules", ".venv", "venv", "__pycache__", ".git", ".mypy_cache"})
+
+# Matches the string literal, not the patch call, so a `MODULE = "products.x.backend.mod"` constant
+# that an f-string extends later counts too. A long target split by implicit concatenation
+# ("products.x.backend.a." "b.name") puts a quote break next to a dot.
+_QUOTE_BREAK = rb"""(?:["']\s*["'])?"""
+_PRODUCT_MODULE_STRING_RE = re.compile(
+ rb"""["']products\.([A-Za-z0-9_]+)\.(backend(?:""" + _QUOTE_BREAK + rb"\." + _QUOTE_BREAK + rb"[A-Za-z0-9_]+)+)"
+)
+_QUOTES_AND_SPACE_RE = re.compile(rb"""["'\s]""")
+
+_ARCHITECTURE_SECTION = "products/architecture.md § What makes the skip sound"
+
+
+class ChannelKind(StrEnum):
+ FOREIGN_RECEIVER = "foreign-receiver"
+ OUTSIDE_TEST = "outside-test"
+ DISCOVERED_BY_NAME = "discovered-by-name"
+
+
+@frozen
+class ChannelModule:
+ """A product module file that an outside suite runs without an import edge."""
+
+ path: str # relative to the product directory, e.g. "backend/apps.py"
+ kind: ChannelKind
+ source: str # the foreign sender as the source spells it, or the repo path of the outside test
+
+
+@frozen
+class _NamedModule:
+ product: str
+ path: str
+ test: str
+
+
+@frozen
+class _ModuleNames:
+ """What the names in one scanned module refer to."""
+
+ module: str
+ imported: Mapping[str, str] # each imported name and the qualified name it refers to
+ defined: frozenset[str]
+
+
+def _is_test_path(parts: Sequence[str]) -> bool:
+ name = parts[-1]
+ if "test" in parts or "tests" in parts:
+ return True
+ return name.startswith("test_") or name.endswith("_test.py") or name == "conftest.py"
+
+
+def _module_file(root: Path, parts: Sequence[str]) -> str | None:
+ """The longest prefix of a dotted path that names a module file under `root`.
+
+ ['backend', 'delivery', 'email', 'send'] -> 'backend/delivery/email.py' when that file exists.
+ A package resolves to its __init__.py."""
+ for end in range(len(parts), 0, -1):
+ stem = "/".join(parts[:end])
+ if (root / f"{stem}.py").is_file():
+ return f"{stem}.py"
+ if (root / stem / "__init__.py").is_file():
+ return f"{stem}/__init__.py"
+ return None
+
+
+def _keyword(call: ast.Call, name: str) -> ast.expr | None:
+ for keyword in call.keywords:
+ if keyword.arg == name:
+ return keyword.value
+ return None
+
+
+def _dotted_name(node: ast.expr) -> str | None:
+ if isinstance(node, ast.Name):
+ return node.id
+ if isinstance(node, ast.Attribute):
+ base = _dotted_name(node.value)
+ return f"{base}.{node.attr}" if base else None
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Channel 1: receivers on a sender the product does not own
+# ---------------------------------------------------------------------------
+
+
+def _app_labels(products_dir: Path) -> Mapping[str, str]:
+ return product_app_labels(products_dir)
+
+
+def _module_names(tree: ast.Module, module: str, is_package: bool) -> _ModuleNames:
+ """Read every import in the module, function-local ones too, because an AppConfig.ready()
+ imports its receivers and senders inside the method."""
+ package = module if is_package else module.rpartition(".")[0]
+ imported: dict[str, str] = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.asname:
+ imported[alias.asname] = alias.name
+ else:
+ root = alias.name.partition(".")[0]
+ imported[root] = root
+ elif isinstance(node, ast.ImportFrom):
+ source = import_from_module(node, package)
+ if source is None:
+ continue
+ for alias in node.names:
+ imported[alias.asname or alias.name] = f"{source}.{alias.name}"
+ defined = frozenset(
+ node.name for node in tree.body if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))
+ )
+ return _ModuleNames(module=module, imported=imported, defined=defined)
+
+
+def _qualified_name(node: ast.expr, names: _ModuleNames) -> str | None:
+ """The qualified name an expression refers to, or None when the source does not name it
+ statically (a loop variable, a call, a subscript)."""
+ dotted = _dotted_name(node)
+ if dotted is None:
+ return None
+ root, _, rest = dotted.partition(".")
+ if root in names.defined:
+ base = f"{names.module}.{root}"
+ elif root in names.imported:
+ base = names.imported[root]
+ else:
+ return None
+ return f"{base}.{rest}" if rest else base
+
+
+def _sender_is_own(sender: ast.expr, product: str, names: _ModuleNames, products_dir: Path) -> bool:
+ """Whether the sender is a model of the product itself.
+
+ Fails closed: a sender the source does not name statically counts as foreign. A string sender
+ is an "app_label.Model" reference, so its owner is the product whose AppConfig declares that
+ label. settings.AUTH_USER_MODEL and get_user_model() resolve to core, so they are foreign too."""
+ if isinstance(sender, ast.Constant) and isinstance(sender.value, str):
+ label = sender.value.partition(".")[0]
+ return _app_labels(products_dir).get(label) == product
+ qualified = _qualified_name(sender, names)
+ return qualified is not None and qualified.startswith(f"products.{product}.")
+
+
+def _receiver_sites(tree: ast.Module) -> Iterator[tuple[ast.expr, ast.expr | None]]:
+ """(sender, receiver function) for every receiver connected with a sender.
+
+ The function is None for `@receiver(...)`, because the decorated function sits in the scanned
+ module itself. For `signal.connect(fn, sender=X)` it is the expression that names `fn`."""
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ name = decorator_name(node)
+ if name not in ("receiver", "connect"):
+ continue
+ sender = _keyword(node, "sender")
+ if sender is None:
+ continue
+ if name == "receiver":
+ yield sender, None
+ continue
+ function = node.args[0] if node.args else _keyword(node, "receiver")
+ yield sender, function
+
+
+def _module_source(repo_root: Path, qualified: str) -> tuple[Path, str] | None:
+ """The file that defines a qualified function name, and the function's name."""
+ module, _, function = qualified.rpartition(".")
+ stem = repo_root / module.replace(".", "/")
+ for candidate in (stem.with_suffix(".py"), stem / "__init__.py"):
+ if candidate.is_file():
+ return candidate, function
+ return None
+
+
+def _forwards_to_connect(path: Path, function: str) -> bool:
+ """Whether a top-level function passes its first parameter on to a `.connect(...)` call.
+
+ A product exposes a signal on its own model through such a hook (`connect_task_run_post_save`)
+ so that consumers never name the sender. The receiver still runs in the sender's save path."""
+ tree = ast_parse_safe(path)
+ if tree is None:
+ return False
+ for node in tree.body:
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) or node.name != function:
+ continue
+ params = [*node.args.posonlyargs, *node.args.args]
+ if not params:
+ return False
+ first = params[0].arg
+ for call in ast.walk(node):
+ if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)):
+ continue
+ if call.func.attr != "connect":
+ continue
+ target = call.args[0] if call.args else _keyword(call, "receiver")
+ if isinstance(target, ast.Name) and target.id == first:
+ return True
+ return False
+
+
+def _hook_sites(
+ tree: ast.Module, product: str, names: _ModuleNames, repo_root: Path
+) -> Iterator[tuple[str, ast.expr | None]]:
+ """(hook name, receiver function) for every call to another boundary's signal hook."""
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ qualified = _qualified_name(node.func, names)
+ if qualified is None or qualified.startswith(f"products.{product}."):
+ continue
+ source = _module_source(repo_root, qualified)
+ if source is None or not _forwards_to_connect(*source):
+ continue
+ yield qualified, node.args[0] if node.args else _keyword(node, "receiver")
+
+
+def _function_module(function: ast.expr, product_dir: Path, names: _ModuleNames) -> str | None:
+ """The product module file that defines a connected receiver function, when the source names it."""
+ prefix = f"products.{product_dir.name}."
+ qualified = _qualified_name(function, names)
+ if qualified is None or not qualified.startswith(prefix):
+ return None
+ return _module_file(product_dir, qualified.removeprefix(prefix).split("."))
+
+
+def _iter_backend_modules(product_dir: Path) -> Iterator[tuple[str, Path]]:
+ """(product-relative path, file) for every non-test, non-migration module under backend/."""
+ for path in sorted((product_dir / "backend").rglob("*.py")):
+ parts = path.relative_to(product_dir).parts
+ if _is_test_path(parts) or "migrations" in parts or _SKIPPED_DIRS.intersection(parts):
+ continue
+ yield "/".join(parts), path
+
+
+def foreign_receiver_modules(product_dir: Path) -> list[ChannelModule]:
+ """The modules of a product that connect a receiver on a foreign sender, and the modules that
+ define those receiver functions. Both run inside the sender's save and delete paths.
+
+ A receiver connects either with `sender=` or through another boundary's signal hook."""
+ product = product_dir.name
+ repo_root = product_dir.parent.parent
+ found: list[ChannelModule] = []
+ for rel_path, path in _iter_backend_modules(product_dir):
+ source = path.read_bytes()
+ if b"sender" not in source and b"connect" not in source:
+ continue
+ tree = ast_parse_safe(path)
+ if tree is None:
+ continue
+ module_parts = ["products", product, *rel_path.removesuffix(".py").split("/")]
+ is_package = module_parts[-1] == "__init__"
+ if is_package:
+ module_parts.pop()
+ names = _module_names(tree, ".".join(module_parts), is_package)
+ sites: list[tuple[str, ast.expr | None]] = [
+ (ast.unparse(sender), function)
+ for sender, function in _receiver_sites(tree)
+ if not _sender_is_own(sender, product, names, product_dir.parent)
+ ]
+ sites += _hook_sites(tree, product, names, repo_root)
+ for spelled, function in sites:
+ found.append(ChannelModule(path=rel_path, kind=ChannelKind.FOREIGN_RECEIVER, source=spelled))
+ function_module = _function_module(function, product_dir, names) if function is not None else None
+ if function_module is not None and function_module != rel_path:
+ found.append(ChannelModule(path=function_module, kind=ChannelKind.FOREIGN_RECEIVER, source=spelled))
+ return found
+
+
+# ---------------------------------------------------------------------------
+# Channel 2: product modules that tests outside the product name by dotted path
+# ---------------------------------------------------------------------------
+
+
+def _iter_test_files(repo_root: Path) -> Iterator[tuple[tuple[str, ...], Path]]:
+ for root in FIRST_PARTY_ROOTS:
+ top = repo_root / root
+ if not top.is_dir():
+ continue
+ for directory, dirnames, filenames in top.walk():
+ dirnames[:] = [d for d in dirnames if d not in _SKIPPED_DIRS]
+ directory_parts = directory.relative_to(repo_root).parts
+ for filename in filenames:
+ parts = (*directory_parts, filename)
+ if filename.endswith(".py") and _is_test_path(parts):
+ yield parts, directory / filename
+
+
+def _outside_test_names(repo_root: Path) -> tuple[_NamedModule, ...]:
+ """Every product module that a test outside that product names by dotted path.
+
+ Scans the whole repository once per process, because product:lint asks for every product.
+ Reads bytes with one regular expression and parses no file, so the scan stays cheap."""
+ found: set[_NamedModule] = set()
+ for parts, path in _iter_test_files(repo_root):
+ for match in _PRODUCT_MODULE_STRING_RE.finditer(path.read_bytes()):
+ product = match.group(1).decode()
+ if parts[:2] == ("products", product):
+ continue
+ dotted = _QUOTES_AND_SPACE_RE.sub(b"", match.group(2)).decode()
+ module = _module_file(repo_root / "products" / product, dotted.split("."))
+ if module is not None:
+ found.add(_NamedModule(product=product, path=module, test="/".join(parts)))
+ return tuple(found)
+
+
+def outside_named_modules(product: str, repo_root: Path) -> list[ChannelModule]:
+ return [
+ ChannelModule(path=named.path, kind=ChannelKind.OUTSIDE_TEST, source=named.test)
+ for named in _outside_test_names(repo_root)
+ if named.product == product
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Channel 3: product modules that core loads by name
+# ---------------------------------------------------------------------------
+
+_LOADER = "load_product_modules"
+UNRESOLVED_SUBMODULE_PREFIX = "<unresolved load_product_modules name at "
+
+
+@frozen
+class _LoadedName:
+ submodule: str | None # None when the call passes a name the scan cannot read
+ caller: str # repo path and line of the load_product_modules call
+
+
+def _module_string_constants(tree: ast.Module) -> Mapping[str, str]:
+ constants: dict[str, str] = {}
+ for node in tree.body:
+ if not (isinstance(node, ast.Assign) and isinstance(node.value, ast.Constant)):
+ continue
+ if not isinstance(node.value.value, str):
+ continue
+ for target in node.targets:
+ if isinstance(target, ast.Name):
+ constants[target.id] = node.value.value
+ return constants
+
+
+def _loaded_submodule(argument: ast.expr, constants: Mapping[str, str]) -> str | None:
+ if isinstance(argument, ast.Constant) and isinstance(argument.value, str):
+ return argument.value
+ if isinstance(argument, ast.Name):
+ return constants.get(argument.id)
+ return None
+
+
+def _iter_source_files(repo_root: Path) -> Iterator[tuple[tuple[str, ...], Path]]:
+ for root in FIRST_PARTY_ROOTS:
+ top = repo_root / root
+ if not top.is_dir():
+ continue
+ for directory, dirnames, filenames in top.walk():
+ dirnames[:] = [d for d in dirnames if d not in _SKIPPED_DIRS]
+ directory_parts = directory.relative_to(repo_root).parts
+ for filename in filenames:
+ parts = (*directory_parts, filename)
+ if filename.endswith(".py") and not _is_test_path(parts):
+ yield parts, directory / filename
+
+
+def _loaded_names(repo_root: Path) -> tuple[_LoadedName, ...]:
+ """Every submodule name that production code passes to load_product_modules.
+
+ core imports `<product app>.<name>` for every product that has one, so no import edge names
+ the product module. Scans the repository once per process."""
+ found: set[_LoadedName] = set()
+ loader = _LOADER.encode()
+ for parts, path in _iter_source_files(repo_root):
+ if loader not in path.read_bytes():
+ continue
+ tree = ast_parse_safe(path)
+ if tree is None:
+ continue
+ constants = _module_string_constants(tree)
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.Call) and decorator_name(node) == _LOADER and node.args):
+ continue
+ caller = f"{'/'.join(parts)}:{node.lineno}"
+ found.add(_LoadedName(submodule=_loaded_submodule(node.args[0], constants), caller=caller))
+ return tuple(sorted(found, key=lambda n: n.caller))
+
+
+def _exact_module_file(root: Path, parts: Sequence[str]) -> str | None:
+ """The module file for exactly this dotted path under `root`, or None. Unlike _module_file it
+ never falls back to a parent package: load_product_modules skips a product without the module."""
+ stem = "/".join(parts)
+ if (root / f"{stem}.py").is_file():
+ return f"{stem}.py"
+ if (root / stem / "__init__.py").is_file():
+ return f"{stem}/__init__.py"
+ return None
+
+
+def discovered_modules(product_dir: Path, repo_root: Path) -> list[ChannelModule]:
+ """The product modules core loads by name. A name the scan cannot read fails closed: it
+ becomes a placeholder module that no input can watch, so the lint asks for a readable name."""
+ found: list[ChannelModule] = []
+ for loaded in _loaded_names(repo_root):
+ if loaded.submodule is None:
+ path = f"{UNRESOLVED_SUBMODULE_PREFIX}{loaded.caller}>"
+ found.append(ChannelModule(path=path, kind=ChannelKind.DISCOVERED_BY_NAME, source=loaded.caller))
+ continue
+ module = _exact_module_file(product_dir, ["backend", *loaded.submodule.split(".")])
+ if module is not None:
+ found.append(ChannelModule(path=module, kind=ChannelKind.DISCOVERED_BY_NAME, source=loaded.caller))
+ return found
+
+
+def find_channel_modules(product_dir: Path, repo_root: Path) -> tuple[ChannelModule, ...]:
+ found = (
+ set(foreign_receiver_modules(product_dir))
+ | set(outside_named_modules(product_dir.name, repo_root))
+ | set(discovered_modules(product_dir, repo_root))
+ )
+ return tuple(sorted(found, key=lambda c: (c.path, c.kind, c.source)))
+
+
+def _first_few(values: Sequence[str], limit: int = 3) -> str:
+ shown = ", ".join(values[:limit])
+ rest = len(values) - limit
+ return f"{shown} and {rest} more" if rest > 0 else shown
+
+
+def unwatched_channel_issue(path: str, channels: Sequence[ChannelModule]) -> str:
+ """The lint issue for one module file the contract-check inputs do not watch."""
+ if path.startswith(UNRESOLVED_SUBMODULE_PREFIX):
+ return (
+ f"{channels[0].source} passes load_product_modules a name the lint cannot read, so it cannot tell "
+ "which product modules core loads. Pass a string literal or a module-level string constant "
+ f"({_ARCHITECTURE_SECTION})"
+ )
+ senders = sorted({c.source for c in channels if c.kind is ChannelKind.FOREIGN_RECEIVER})
+ tests = sorted({c.source for c in channels if c.kind is ChannelKind.OUTSIDE_TEST})
+ loaders = sorted({c.source for c in channels if c.kind is ChannelKind.DISCOVERED_BY_NAME})
+ reasons: list[str] = []
+ moves: list[str] = []
+ if senders:
+ reasons.append(f"it holds a receiver on a sender the product does not own ({_first_few(senders)})")
+ moves.append("flip the receiver direction")
+ if tests:
+ reasons.append(f"tests outside the product name it by dotted path, as patch targets do ({_first_few(tests)})")
+ moves.append("move the test into the owning product")
+ if loaders:
+ reasons.append(f"core loads it by name through load_product_modules ({_first_few(loaders)})")
+ remedy = f" or {' and '.join(moves)}" if moves else ""
+ return (
+ f"{path} runs in other suites without an import edge: {'; '.join(reasons)}. The "
+ "backend:contract-check inputs do not watch it, so a change to it skips those suites. "
+ f'Add "{path}" to the inputs in turbo.json{remedy} ({_ARCHITECTURE_SECTION})'
+ )
diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.py
index 39911dda2fad..8c53567e2034 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py
@@ -45,6 +45,7 @@ from hogli_commands.product.isolation import (
facade_unapproved_wiring,
has_narrowed_turbo_inputs,
has_real_facade,
+ has_tach_interface,
permanent_interface_modules,
routes_in_turbo_inputs,
uncovered_carveout_modules,
@@ -1089,6 +1090,56 @@ from = [
assert has_legacy_interface_leaks(_TACH_SAMPLE, "products.mcp") is False
+# ---------------------------------------------------------------------------
+# has_tach_interface
+# ---------------------------------------------------------------------------
+
+_TACH_INTERFACE_MENTIONS = r"""
+[[modules]]
+path = "products.review_hog"
+depends_on = [
+ # Facade-only (enforced by stamphog's [[interfaces]] block)
+ "products.stamphog",
+]
+layer = "modules"
+
+[[modules]]
+path = "products.field_notes"
+depends_on = ["posthog"]
+layer = "modules"
+
+[[interfaces]]
+expose = [
+ "backend\\.models\\.Task",
+]
+from = [
+ "products.tasks",
+]
+
+[[interfaces]]
+expose = [
+ "backend\\.facade.*",
+]
+from = [
+ "products\\.(stamphog|visual_review)",
+]
+"""
+
+
+class TestHasTachInterface:
+ @pytest.mark.parametrize(
+ "name, expected",
+ [
+ pytest.param("review_hog", False, id="comment_mentions_interfaces"),
+ pytest.param("field_notes", False, id="next_product_interfaces_block_follows"),
+ pytest.param("tasks", True, id="named_in_from"),
+ pytest.param("stamphog", True, id="named_in_from_regex"),
+ ],
+ )
+ def test_detection(self, name: str, expected: bool) -> None:
+ assert has_tach_interface(name, _TACH_INTERFACE_MENTIONS) is expected
+
+
# ---------------------------------------------------------------------------
# permanent-interface marker
# ---------------------------------------------------------------------------
@@ -1563,24 +1614,22 @@ class TestImportSurfaceCheck:
0,
id="unsealed_consumer_reaching_facade",
),
- # An unsealed product has no routes/presentation contract, so that layout stays
- # its own business.
+ # The routes and presentation contracts name every product, so an unsealed product
+ # without a consumer is held to them too.
pytest.param(
- {
- "webhook_consumers.py": "from .facade.api import f\n",
- "facade/api.py": "",
- "routes.py": "from .api.views import V\n",
- "api/views.py": "",
- },
+ {"routes.py": "from .api.views import V\n", "api/views.py": ""},
True,
- 0,
- id="unsealed_routes_stay_unchecked",
+ 1,
+ id="unsealed_routes_from_unmarked_package",
),
pytest.param(
- {"routes.py": "from .api.views import V\n", "api/views.py": ""},
- False,
- 0,
- id="unsealed_without_consumer_does_not_run",
+ {
+ "presentation/views.py": "from products.p.backend.summary.read import LIMIT\n",
+ "summary/read.py": "",
+ },
+ True,
+ 1,
+ id="unsealed_presentation_from_unmarked_package",
),
],
)
@@ -1882,6 +1931,13 @@ class TestValidateTachReferences:
'[[interfaces]]\nexpose = ["backend\\\\.x.*"]\nfrom = ["products.missing_iface"]\n',
[("missing_dep", "dangling dependency"), ("missing_iface", "dangling interface")],
),
+ # Dangling depends_on listed after a comment that names [[interfaces]].
+ (
+ '[[modules]]\npath = "products.alpha"\ndepends_on = [\n'
+ " # Facade-only (enforced by beta's [[interfaces]] block)\n"
+ ' "products.ghost",\n]\n',
+ [("products.ghost", "dangling dependency")],
+ ),
],
ids=[
"clean_interface",
@@ -1889,6 +1945,7 @@ class TestValidateTachReferences:
"dangling_depends_on",
"clean_depends_on",
"both_dangling",
+ "dangling_depends_on_after_interfaces_comment",
],
)
def test_references(self, tach: str, expected_substrings: list[tuple[str, str]]) -> None:
diff --git a/tools/hogli-commands/hogli_commands/tests/test_watched_channels.py b/tools/hogli-commands/hogli_commands/tests/test_watched_channels.py
new file mode 100644
index 000000000000..0f3ce8d6c35b
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_watched_channels.py
@@ -0,0 +1,237 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from hogli_commands.product.checks import CheckContext, WatchedChannelsCheck
+from hogli_commands.product.isolation import compute_isolation_status
+from hogli_commands.product.watched_channels import (
+ UNRESOLVED_SUBMODULE_PREFIX,
+ discovered_modules,
+ foreign_receiver_modules,
+ outside_named_modules,
+)
+
+_SIGNAL_IMPORTS = "from django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\n"
+
+
+def _write(root: Path, files: dict[str, str]) -> None:
+ for rel, content in files.items():
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content)
+
+
+def _write_products(repo_root: Path, mine: dict[str, str]) -> Path:
+ for name in ("mine", "other"):
+ _write(
+ repo_root / "products" / name / "backend",
+ {"__init__.py": "", "apps.py": f'class Config:\n label = "{name}"\n', "models.py": ""},
+ )
+ product_dir = repo_root / "products" / "mine"
+ _write(product_dir / "backend", mine)
+ return product_dir
+
+
+class TestForeignReceivers:
+ @pytest.mark.parametrize(
+ "source, expected",
+ [
+ ('@receiver(post_save, sender="other.Thing")\ndef on_save(**kwargs): ...\n', {"backend/signals.py"}),
+ (
+ "from products.other.backend.models import Thing\n\n"
+ "@receiver(post_save, sender=Thing)\ndef on_save(**kwargs): ...\n",
+ {"backend/signals.py"},
+ ),
+ (
+ "from posthog.models.user import User\n\n"
+ "@receiver(post_save, sender=User)\ndef on_save(**kwargs): ...\n",
+ {"backend/signals.py"},
+ ),
+ (
+ "from django.conf import settings\n\n"
+ "@receiver(post_save, sender=settings.AUTH_USER_MODEL)\ndef on_save(**kwargs): ...\n",
+ {"backend/signals.py"},
+ ),
+ (
+ 'def on_save(**kwargs): ...\n\nfor model in ("mine.Widget",):\n'
+ " post_save.connect(on_save, sender=model)\n",
+ {"backend/signals.py"},
+ ),
+ ('@receiver(post_save, sender="mine.Widget")\ndef on_save(**kwargs): ...\n', set()),
+ (
+ "from products.mine.backend.models import Widget\n\n"
+ "@receiver(post_save, sender=Widget)\ndef on_save(**kwargs): ...\n",
+ set(),
+ ),
+ (
+ "from .models import Widget\n\n@receiver(post_save, sender=Widget)\ndef on_save(**kwargs): ...\n",
+ set(),
+ ),
+ ],
+ ids=[
+ "string-sender-of-another-product",
+ "imported-model-of-another-product",
+ "imported-core-model",
+ "auth-user-model-setting",
+ "unresolvable-sender-fails-closed",
+ "string-sender-of-own-product",
+ "imported-own-model",
+ "relative-import-of-own-model",
+ ],
+ )
+ def test_sender_resolution(self, tmp_path: Path, source: str, expected: set[str]) -> None:
+ product_dir = _write_products(tmp_path, {"signals.py": _SIGNAL_IMPORTS + source})
+ assert {c.path for c in foreign_receiver_modules(product_dir)} == expected
+
+ def test_connected_function_module_is_held_with_the_connecting_module(self, tmp_path: Path) -> None:
+ product_dir = _write_products(
+ tmp_path,
+ {
+ "handlers.py": "def on_save(**kwargs): ...\n",
+ "apps.py": (
+ 'class Config:\n label = "mine"\n\n def ready(self):\n'
+ " from django.db.models.signals import post_save\n\n"
+ " from . import handlers\n\n"
+ ' post_save.connect(handlers.on_save, sender="other.Thing")\n'
+ ),
+ },
+ )
+ assert {c.path for c in foreign_receiver_modules(product_dir)} == {"backend/apps.py", "backend/handlers.py"}
+
+ @pytest.mark.parametrize(
+ "hook_body, expected",
+ [
+ (
+ "def connect_thing_saved(receiver, *, dispatch_uid):\n"
+ " post_save.connect(receiver, sender=Thing, dispatch_uid=dispatch_uid)\n",
+ {"backend/receivers.py", "backend/handlers.py"},
+ ),
+ ("def connect_thing_saved(receiver, *, dispatch_uid):\n return None\n", set()),
+ ],
+ ids=["hook-forwards-receiver-to-connect", "same-name-without-connect"],
+ )
+ def test_signal_hook_of_another_product(self, tmp_path: Path, hook_body: str, expected: set[str]) -> None:
+ product_dir = _write_products(
+ tmp_path,
+ {
+ "handlers.py": "def on_save(**kwargs): ...\n",
+ "receivers.py": (
+ "from products.other.backend.facade.signals import connect_thing_saved\n\n"
+ "from .handlers import on_save\n\n"
+ "def connect():\n"
+ ' connect_thing_saved(on_save, dispatch_uid="mine")\n'
+ ),
+ },
+ )
+ _write(tmp_path / "products" / "other" / "backend" / "facade", {"signals.py": hook_body})
+ assert {c.path for c in foreign_receiver_modules(product_dir)} == expected
+
+
+class TestOutsideTestNames:
+ @pytest.mark.parametrize(
+ "test_path, source, expected",
+ [
+ (
+ "posthog/api/test/test_thing.py",
+ 'patch("products.mine.backend.delivery.email.send_email")\n',
+ {"backend/delivery/email.py"},
+ ),
+ (
+ "products/other/backend/tests/test_thing.py",
+ 'MODULE = "products.mine.backend.delivery.email"\npatch(f"{MODULE}.send_email")\n',
+ {"backend/delivery/email.py"},
+ ),
+ (
+ "ee/tests/test_thing.py",
+ 'patch(\n "products.mine.backend.delivery."\n "email.send_email"\n)\n',
+ {"backend/delivery/email.py"},
+ ),
+ (
+ "products/mine/backend/tests/test_thing.py",
+ 'patch("products.mine.backend.delivery.email.send_email")\n',
+ set(),
+ ),
+ ],
+ ids=["patch-string", "module-constant-with-f-string", "implicit-concatenation", "test-inside-the-owner"],
+ )
+ def test_resolves_to_the_longest_module_file(
+ self, tmp_path: Path, test_path: str, source: str, expected: set[str]
+ ) -> None:
+ _write_products(tmp_path, {"delivery/__init__.py": "", "delivery/email.py": ""})
+ _write(tmp_path, {test_path: source})
+ assert {c.path for c in outside_named_modules("mine", tmp_path)} == expected
+
+
+class TestWatchedChannelsCheck:
+ @pytest.mark.parametrize(
+ "inputs, narrowed, unwatched",
+ [
+ (["backend/facade/**", "backend/delivery/email.py"], True, []),
+ (["backend/facade/**", "backend/delivery/**"], False, []),
+ (["backend/facade/**"], True, ["backend/delivery/email.py"]),
+ (
+ ["backend/facade/**", "backend/delivery/**", "!backend/delivery/email.py"],
+ False,
+ ["backend/delivery/email.py"],
+ ),
+ ],
+ ids=["listed", "inside-a-listed-directory", "not-listed", "negated"],
+ )
+ def test_patched_module_must_be_in_the_inputs(
+ self, tmp_path: Path, inputs: list[str], narrowed: bool, unwatched: list[str]
+ ) -> None:
+ product_dir = _write_products(tmp_path, {"facade/__init__.py": "", "delivery/email.py": ""})
+ _write(
+ product_dir,
+ {
+ "package.json": json.dumps({"scripts": {"backend:contract-check": "true"}}),
+ "turbo.json": json.dumps({"tasks": {"backend:contract-check": {"inputs": inputs}}}),
+ },
+ )
+ _write(tmp_path, {"posthog/test/test_thing.py": 'patch("products.mine.backend.delivery.email.send")\n'})
+ backend_dir = product_dir / "backend"
+ status = compute_isolation_status(
+ "mine", product_dir, backend_dir, tach_content="", pyproject_text="", repo_root=tmp_path
+ )
+ ctx = CheckContext(
+ name="mine",
+ product_dir=product_dir,
+ backend_dir=backend_dir,
+ has_facade_contracts=False,
+ structure={},
+ detailed=False,
+ _isolation=status,
+ )
+
+ result = WatchedChannelsCheck().run(ctx)
+
+ assert status.has_narrowed_turbo is narrowed
+ assert [issue.split(" ", 1)[0] for issue in result.issues] == unwatched
+
+
+class TestDiscoveredByName:
+ @pytest.mark.parametrize(
+ "loader_source, expected",
+ [
+ ('load_product_modules("data_freshness")\n', {"backend/data_freshness.py"}),
+ ('NAME = "data_freshness"\n\nload_product_modules(NAME)\n', {"backend/data_freshness.py"}),
+ ('load_product_modules("facade.highlights")\n', {"backend/facade/highlights.py"}),
+ ('load_product_modules("missing_here")\n', set()),
+ ],
+ ids=["literal-name", "module-constant", "dotted-name", "product-without-the-module"],
+ )
+ def test_names_resolve_to_product_modules(self, tmp_path: Path, loader_source: str, expected: set[str]) -> None:
+ product_dir = _write_products(tmp_path, {"data_freshness.py": "", "facade/highlights.py": ""})
+ _write(
+ tmp_path / "posthog", {"loader.py": "from posthog.products import load_product_modules\n\n" + loader_source}
+ )
+ assert {c.path for c in discovered_modules(product_dir, tmp_path)} == expected
+
+ def test_unreadable_name_fails_closed(self, tmp_path: Path) -> None:
+ product_dir = _write_products(tmp_path, {})
+ _write(tmp_path / "posthog", {"loader.py": "def load(name):\n return load_product_modules(name)\n"})
+ paths = [c.path for c in discovered_modules(product_dir, tmp_path)]
+ assert len(paths) == 1 and paths[0].startswith(UNRESOLVED_SUBMODULE_PREFIX)