:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(devex): mechanically validate the permanent-interface marker (#68654)
Julian Bezef62bdb9e842
diff --git a/tools/hogli-commands/hogli_commands/product/ast_helpers.py b/tools/hogli-commands/hogli_commands/product/ast_helpers.pyindex 4315d6f09856..de4ef1842864 100644--- a/tools/hogli-commands/hogli_commands/product/ast_helpers.py+++ b/tools/hogli-commands/hogli_commands/product/ast_helpers.py@@ -20,6 +20,21 @@ def ast_parse_safe(file_path: Path) -> ast.Module | None:return None+def get_imported_module_names(tree: ast.Module) -> set[str]:+ """Every dotted module path the tree imports via real import statements.++ 'from a.b import c' records both 'a.b' and 'a.b.c' (c may be a submodule); relative+ imports are skipped — they can't name a path outside the importing package."""+ imported: set[str] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ imported.update(alias.name for alias in node.names)+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:+ imported.add(node.module)+ imported.update(f"{node.module}.{alias.name}" for alias in node.names)+ return imported++def _file_imports_django_models(tree: ast.Module) -> bool:"""Check whether a file imports from django.db.models (or django.db)."""for node in ast.walk(tree):diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex c46065631d91..e4e1ee67e51a 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -726,6 +726,20 @@ class IsolationChainCheck(ProductCheck):f"would skip the Django suite. Add the matching input(s) ({globs}) to keep the skip sound")+ # Guarding against marker abuse: the permanent-interface marker is only legitimate for+ # modules core depends on outside the import graph (ClickHouse DDL in a frozen migration or+ # the schema registry). Without this check the marker is mechanically unrestricted — a+ # product could mark backend.models/backend.logic permanent, list it in turbo inputs, and+ # pass the chain. Fires regardless of has_narrowed: the abuse lives in tach.toml itself, not+ # in turbo config, so it must block even before the product narrows.+ if status.unqualified_permanent_exposures:+ modules = ", ".join(status.unqualified_permanent_exposures)+ result.issues.append(+ f"permanent-interface marker covers module(s) {modules}, but they are not imported by any "+ "frozen ClickHouse migration or the ClickHouse schema registry — so they don't qualify as a "+ "permanent interface. Route them through the facade instead (or remove the marker)"+ )+# 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.@@ -736,11 +750,14 @@ class IsolationChainCheck(ProductCheck):# script, and no narrowing). routes_unwatched can co-occur with them (it only needs# has_narrowed + a routes module), but turbo.json is still where the routes omission is# fixed, so it wins; the co-firing mismatch issues still print in the lint output.- result.file = (- f"products/{ctx.name}/turbo.json"- if needs_turn_on or routes_unwatched- else f"products/{ctx.name}/backend/facade/api.py"- )+ # An unqualified permanent exposure is a defect in the tach.toml marker itself, so point+ # there; it takes precedence because it's the most fundamental of these issues.+ if status.unqualified_permanent_exposures:+ result.file = "tach.toml"+ elif needs_turn_on or routes_unwatched:+ result.file = f"products/{ctx.name}/turbo.json"+ else:+ result.file = f"products/{ctx.name}/backend/facade/api.py"if result.issues:result.lines = [f"✗ {len(result.issues)} issue(s)"] + [f" → {i}" for i in result.issues]elif result.warnings:diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex 94638222af51..a731d71e6e3d 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -22,11 +22,12 @@ from __future__ import annotationsimport reimport jsonimport tomllib+import functoolsfrom collections.abc import Iteratorfrom dataclasses import dataclassfrom pathlib import Path-from .ast_helpers import has_any_function_defs+from .ast_helpers import ast_parse_safe, get_imported_module_names, has_any_function_defsfrom .paths import REPO_ROOT, TACH_TOML, get_tach_block# ---------------------------------------------------------------------------@@ -317,6 +318,68 @@ def uncovered_permanent_modules(product_dir: Path, permanent_modules: frozenset[return {m for m in permanent_modules if not any(i.startswith(_module_input_prefixes(m)) for i in inputs)}+# ---------------------------------------------------------------------------+# Permanent-interface qualification — the marker can only cover genuinely irreducible DDL+# ---------------------------------------------------------------------------+++# Products whose permanent-interface marker is justified by a coupling channel other than+# ClickHouse DDL, so the DDL-qualification rule below doesn't apply. warehouse_sources: core's+# HogQL direct-SQL adapters and system tables reach source internals through the facade's lazy+# (PEP 562) re-exports; the exposed set is pinned by the product's own guard test+# (test_ci_core_coupled_sources.py) and stays watched via the turbo-input rule above. Extending+# this set requires a devex-reviewed change here — which is the point.+_QUALIFICATION_EXEMPT_PRODUCTS: frozenset[str] = frozenset({"products.warehouse_sources"})+++def _clickhouse_ddl_imports(repo_root: Path) -> frozenset[str]:+ """Dotted module paths imported by the consumers of a permanent DDL interface outside the+ import-reroute path: the frozen ClickHouse migrations and the schema registry.++ Extracted from real import statements via AST (get_imported_module_names), so a module path+ that only appears in a comment, docstring, or string literal can't qualify a marker.++ Cached per repo_root — product:lint runs the qualification check once per product, and+ re-parsing ~250 migration files each time would dominate the lint.+ """+ migrations_dir = repo_root / "posthog" / "clickhouse" / "migrations"+ schema_file = repo_root / "posthog" / "clickhouse" / "schema.py"+ files = sorted(migrations_dir.glob("*.py")) if migrations_dir.is_dir() else []+ if schema_file.exists():+ files.append(schema_file)+ imported: set[str] = set()+ for path in files:+ tree = ast_parse_safe(path)+ if tree is not None:+ imported.update(get_imported_module_names(tree))+ return frozenset(imported)+++def _module_is_imported(imported: frozenset[str], full_dotted_path: str) -> bool:+ """True if the module itself or any of its submodules is imported."""+ return any(imp == full_dotted_path or imp.startswith(full_dotted_path + ".") for imp in imported)+++def unqualified_permanent_modules(+ module_path: str, permanent_modules: frozenset[str], *, repo_root: Path = REPO_ROOT+) -> set[str]:+ """Permanently-exposed module roots that don't actually qualify as an irreducible interface.++ The permanent-interface marker is only legitimate for modules core depends on outside the+ import graph — ClickHouse DDL imported by a frozen migration or the schema registry. This is+ the mechanical guard against abusing it: a module (e.g. 'backend.sql') qualifies only if its+ full dotted path (e.g. 'products.error_tracking.backend.sql') is imported by one of those+ consumers. Any marked module with no such import is returned, and IsolationChainCheck turns+ a non-empty result into a blocking issue — the marker can't be used to smuggle 'backend.models'+ or 'backend.logic' past the isolation seal.+ """+ if not permanent_modules or module_path in _QUALIFICATION_EXEMPT_PRODUCTS:+ return set()+ imported = _clickhouse_ddl_imports(repo_root)+ return {root for root in permanent_modules if not _module_is_imported(imported, f"{module_path}.{root}")}++def routes_in_turbo_inputs(product_dir: Path) -> bool:"""True if contract-check inputs watch the routes module specifically — backend/routes.py or abackend/routes/ package. Anchored and negation-aware, so a glob that merely contains 'routes',@@ -349,6 +412,10 @@ class IsolationStatus:# in its contract-check inputs — uncovered_permanent_exposures lists any that don't.permanent_exposures: tuple[str, ...] = ()uncovered_permanent_exposures: tuple[str, ...] = ()+ # Marked permanent modules that aren't imported by any frozen ClickHouse migration or the+ # schema registry — so they don't qualify as irreducible interfaces and the marker is being+ # abused to keep an internal (models/logic) walled off. IsolationChainCheck blocks on these.+ unqualified_permanent_exposures: tuple[str, ...] = ()@propertydef deferred_count(self) -> int:@@ -387,12 +454,15 @@ def compute_isolation_status(is_isolated: bool | None = None,tach_content: str | None = None,pyproject_text: str | None = None,+ repo_root: Path | None = None,) -> IsolationStatus:"""Compute the full isolation seal status for one product."""if is_isolated is None:is_isolated = is_isolated_product(backend_dir)if tach_content is None:tach_content = TACH_TOML.read_text() if TACH_TOML.exists() else ""+ if repo_root is None:+ repo_root = REPO_ROOTmodule_path = f"products.{name}"permanent_modules = frozenset(permanent_interface_modules(tach_content, module_path))return IsolationStatus(@@ -406,4 +476,7 @@ def compute_isolation_status(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))),+ unqualified_permanent_exposures=tuple(+ sorted(unqualified_permanent_modules(module_path, permanent_modules, repo_root=repo_root))+ ),)diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex b14f4dfda692..7cf8b6324ac9 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -30,6 +30,7 @@ from hogli_commands.product.isolation import (permanent_interface_modules,routes_in_turbo_inputs,uncovered_permanent_modules,+ unqualified_permanent_modules,)# ---------------------------------------------------------------------------@@ -785,6 +786,70 @@ class TestPermanentInterface:assert uncovered_permanent_modules(tmp_path, frozenset({"backend.sql", "backend.embedding"})) == set()+def _make_ddl_repo(tmp_path: Path, *, migration_body: str = "", schema_body: str = "") -> Path:+ migrations = tmp_path / "posthog" / "clickhouse" / "migrations"+ migrations.mkdir(parents=True)+ (migrations / "0001_x.py").write_text(migration_body)+ (tmp_path / "posthog" / "clickhouse" / "schema.py").write_text(schema_body)+ return tmp_path+++class TestPermanentInterfaceQualification:+ @pytest.mark.parametrize(+ "migration_body, schema_body, marked, expected",+ [+ # DDL module imported by a frozen migration qualifies.+ ("from products.foo.backend.sql import CREATE_X", "", {"backend.sql"}, set()),+ # A reference from the schema registry alone qualifies too.+ ("", "from products.foo.backend.sql import CREATE_X", {"backend.sql"}, set()),+ # A submodule import still counts as a reference to the root.+ ("from products.foo.backend.sql.tables import CREATE_X", "", {"backend.sql"}, set()),+ # The abuse case: an internal marked permanent with no DDL consumer is flagged.+ ("", "", {"backend.models"}, {"backend.models"}),+ # Word boundary: backend.sql_extra must not qualify backend.sql.+ ("from products.foo.backend.sql_extra import CREATE_X", "", {"backend.sql"}, {"backend.sql"}),+ # Leaf import form counts as a reference.+ ("from products.foo.backend import sql", "", {"backend.sql"}, set()),+ # An unrelated leaf-name token on a later line must not qualify the module.+ ("from products.foo.backend import models\nsql = 1", "", {"backend.sql"}, {"backend.sql"}),+ # A path mentioned only in a comment must not qualify — imports come from the AST.+ ("# depends on products.foo.backend.models\nimport datetime", "", {"backend.models"}, {"backend.models"}),+ # Same for a string literal (e.g. DDL text or a log message naming the module).+ ('TABLE_SQL = "see products.foo.backend.models"', "", {"backend.models"}, {"backend.models"}),+ ],+ )+ def test_qualification(+ self, tmp_path: Path, migration_body: str, schema_body: str, marked: set[str], expected: set[str]+ ) -> None:+ repo_root = _make_ddl_repo(tmp_path, migration_body=migration_body, schema_body=schema_body)+ assert unqualified_permanent_modules("products.foo", frozenset(marked), repo_root=repo_root) == expected++ def test_exempt_product_skips_qualification(self, tmp_path: Path) -> None:+ # warehouse_sources' marker is justified by a non-DDL channel; dropping the exemption+ # would turn product:lint --all red for it.+ repo_root = _make_ddl_repo(tmp_path)+ assert (+ unqualified_permanent_modules(+ "products.warehouse_sources", frozenset({"backend.models"}), repo_root=repo_root+ )+ == set()+ )++ def test_unqualified_exposure_blocks_isolation_chain(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ # A marked module that no migration/schema-registry imports must hard-block, and the issue+ # must point at tach.toml where the bogus marker lives.+ _seal_externally(monkeypatch)+ import hogli_commands.product.isolation as isolation_module++ monkeypatch.setattr(isolation_module, "permanent_interface_modules", lambda *_a, **_k: {"backend.models"})+ # Controlled corpus — don't let the assertion depend on the real repo's migrations.+ monkeypatch.setattr(isolation_module, "_clickhouse_ddl_imports", lambda _root: frozenset())+ ctx = _make_product(tmp_path, scripts=_WITH_SCRIPT, isolated=True)+ result = chain_check.run(ctx)+ assert any("don't qualify as a permanent interface" in i for i in result.issues)+ assert result.file == "tach.toml"++# ---------------------------------------------------------------------------# ProductYamlCheck# ---------------------------------------------------------------------------