:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): check relative imports in the product import surface (#103582)
Julian Bez4e4659fb320b
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.mdindex 0de77a05795d..e4089207539f 100644--- a/.agents/skills/adding-inbound-webhooks/SKILL.md+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md@@ -44,7 +44,7 @@ Rules that decide whether this works:- Keep the module cheap to import. The registry imports it on the first delivery through `load_product_modules("webhook_consumers")`, so defer heavy imports into the handler behind `# noqa: PLC0415` with a reason.- The handler runs synchronously inside the request. Enqueue a task for real work, the way stamphog and conversations do.- A handler that reads the database wraps the read in `bounded_statement_timeout(ms, models=...)` from `posthog.ingress.dispatch.database`, passing only the models the read actually uses. Opening an alias is itself unbounded, so naming one the read never touches can stall the delivery on connection setup.-- An import-linter contract (`webhook consumers must only import facade`) holds the module to its own product's `facade/`. Reach product internals through the facade.+- An import-linter contract (`webhook consumers must only import facade`) holds the module to its own product's `facade/`. Reach product internals through the facade. `hogli product:lint` holds the same rule by AST for every product that has a `webhook_consumers.py`, including relative imports and products with no contract yet.- A consumer whose resources are split across regions declares `ownership=`, pointing at a facade function that returns a `DeliveryOwnership`. Ingress forwards the signed request when the answer is `ELSEWHERE`, and dispatches locally either way. The lookup runs inside the request, so bound it with `bounded_statement_timeout(ms, models=...)`. Let a transient error out of the lookup rather than answering `LOCAL` or `UNDECIDED` through it: a lookup that raises asks a provider with `retry_status` for the delivery again, and a guessed answer receipts a delivery the other region never sees.Tests: extend the product's existing webhook test module rather than starting a parallel one.@@ -100,6 +100,7 @@ Each was a real proposal already; ["Non-goals" in the package README](../../../psemgrep --config .semgrep/rules/devex/ . # the ratchet entry is really gonesemgrep --test .semgrep/ # only if you changed the rule itselflint-imports # the webhook_consumers contract+hogli product:lint <product> # the AST backstop for that contracthogli test products/<product>/backend/tests/test_webhook_consumers.pyhogli test posthog/ingress/test/ruff check --fix <touched files> && ruff format <touched files>diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 2ae3b140deac..f117e9d011ff 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -152,6 +152,9 @@ The registry finds these through `posthog.products.load_product_modules("webhookThat is deliberate: eager loading would drag every product's webhook module onto the startup import path, which `posthog/test/repo_invariants/test_startup_import_budget.py` exists to keep clear.Keep the module itself cheap to import and defer the heavy work into the handler.+The module may import its own product's `facade/` and nothing else of the product.+An import-linter contract holds that for a sealed product, and `hogli product:lint` holds it by AST for every product that has a `webhook_consumers.py`, relative imports included.+Registration is validated and fail-closed.A consumer that names a provider app nobody declares, reuses a name already taken for that provider, or registers for an event type the provider does not declare raises `RegistryError` at build, rather than sitting there looking registered and never running.diff --git a/tools/hogli-commands/hogli_commands/product/ast_helpers.py b/tools/hogli-commands/hogli_commands/product/ast_helpers.pyindex 4f37643351de..e140a925db75 100644--- a/tools/hogli-commands/hogli_commands/product/ast_helpers.py+++ b/tools/hogli-commands/hogli_commands/product/ast_helpers.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport reimport astimport warnings+import importlib.utilfrom collections.abc import Iterator, Sequencefrom dataclasses import dataclassfrom pathlib import Path@@ -524,12 +525,38 @@ def count_viewset_files(directory: Path) -> int:return count+def _importing_package(file_path: Path, package_root: Path, package_prefix: str) -> str:+ """The dotted package a relative import in `file_path` resolves against.++ A module names the directory it sits in, and an `__init__.py` names its own directory,+ so both are the parent of the file path.+ """+ return ".".join([package_prefix, *file_path.relative_to(package_root).parent.parts])+++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.+ """+ if node.level == 0:+ return node.module+ try:+ return importlib.util.resolve_name("." * node.level + (node.module or ""), package)+ except ImportError:+ return None++def module_import_targets(file_path: Path, package_root: Path, package_prefix: str) -> list[tuple[int, str]]:- """(line, dotted module) for every absolute import in the file that names a module under+ """(line, dotted module) for every import in the file that names a module under`package_prefix` (e.g. "products.foo.backend"), resolved against `package_root` (thedirectory that prefix maps to) so `from a.b import c` yields `a.b.c` when c is amodule or package and `a.b` when c is a name.+ Relative imports (`from . import x`, `from ..services import y`) resolve to the same+ absolute form first, so a rule reads one shape and a writer cannot dodge it by spelling+ the import the other way.+Pure AST: unlike grimp it does not need __init__.py markers to see a module, which iswhat lets a lint hold an import-linter contract in directories grimp cannot descend into."""@@ -537,6 +564,7 @@ def module_import_targets(file_path: Path, package_root: Path, package_prefix: sif not tree:return []prefix_dot = package_prefix + "."+ package = _importing_package(file_path, package_root, package_prefix)def is_module(dotted: str) -> bool:rel = Path(*dotted[len(prefix_dot) :].split("."))@@ -546,12 +574,13 @@ def module_import_targets(file_path: Path, package_root: Path, package_prefix: sfor node in ast.walk(tree):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) and node.level == 0 and node.module:- if node.module != package_prefix and not node.module.startswith(prefix_dot):+ elif isinstance(node, ast.ImportFrom):+ module = _import_from_module(node, package)+ if not module or (module != package_prefix and not module.startswith(prefix_dot)):continuefor alias in node.names:- candidate = f"{node.module}.{alias.name}"- targets.append((node.lineno, candidate if is_module(candidate) else node.module))+ candidate = f"{module}.{alias.name}"+ targets.append((node.lineno, candidate if is_module(candidate) else module))return [(line, dotted) for line, dotted in targets if dotted.startswith(prefix_dot)]diff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex 42f2aa78b971..b2935d38ff9a 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -450,20 +450,38 @@ class ImportSurfaceCheck(ProductCheck):That is a live view outside presentation/ that the narrowed contract-check inputs do notwatch. This check reads the same imports straight from the AST, honors the sameignore_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."""label = "import surface"- for_lenient = False# (source subtree or module, allowed destination subtrees)+ WEBHOOK_CONSUMERS_SURFACE = ("webhook_consumers", ("facade",))SURFACES = (("routes", ("presentation",)),("presentation", ("presentation", "facade")),- ("webhook_consumers", ("facade",)),+ WEBHOOK_CONSUMERS_SURFACE,)+ 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.is_isolated 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 []+ if root.is_dir():+ files += sorted(f for f in root.rglob("*.py") if "__pycache__" not in f.parts)+ return files+def should_run(self, ctx: CheckContext) -> bool:- return super().should_run(ctx) and ctx.backend_dir.is_dir()+ 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))def _module_name(self, ctx: CheckContext, path: Path) -> str:rel = path.relative_to(ctx.backend_dir).with_suffix("")@@ -474,13 +492,9 @@ class ImportSurfaceCheck(ProductCheck):prefix = f"products.{ctx.name}.backend"ignored = ignored_import_edges()issues = []- for source, allowed in self.SURFACES:- root = ctx.backend_dir / source- files = [root.with_suffix(".py")] if root.with_suffix(".py").exists() else []- if root.is_dir():- files += sorted(f for f in root.rglob("*.py") if "__pycache__" not in f.parts)+ for source, allowed in self._surfaces(ctx):allowed_prefixes = tuple(f"{prefix}.{a}" for a in allowed)- for f in files:+ for f in self._surface_files(ctx, source):importer = self._module_name(ctx, f)for line, target in module_import_targets(f, ctx.backend_dir, prefix):# Segment boundary on purpose: `facade_legacy` must not pass as `facade`.@@ -489,8 +503,9 @@ class ImportSurfaceCheck(ProductCheck):continueissues.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, the target sits under a "- "directory without __init__.py, which grimp cannot see"+ 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")if issues:return CheckResult(diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex 7a2744a92873..a785580d0172 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -1175,9 +1175,15 @@ class TestImportSurfaceCheck:view there passes the contract vacuously. None of the fixtures below carry a marker."""def _ctx(- self, tmp_path: Path, files: dict[str, str], monkeypatch: pytest.MonkeyPatch, ignored=None+ self,+ tmp_path: Path,+ files: dict[str, str],+ monkeypatch: pytest.MonkeyPatch,+ ignored=None,+ is_isolated: bool = True,) -> CheckContext:ctx = _make_backend(tmp_path, list(files))+ ctx.is_isolated = is_isolatedfor path, content in files.items():(ctx.backend_dir / path).write_text(content)monkeypatch.setattr(checks_module, "ignored_import_edges", lambda: set(ignored or ()))@@ -1242,6 +1248,48 @@ class TestImportSurfaceCheck:1,id="webhook_consumers_from_facade_lookalike",),+ # A relative import names the same module as the absolute one, so every surface+ # has to read both shapes alike.+ pytest.param(+ {+ "webhook_consumers.py": "from .services.handlers import h\n",+ "services/handlers.py": "",+ },+ 1,+ id="webhook_consumers_from_internals_relatively",+ ),+ pytest.param(+ {"webhook_consumers.py": "from . import services\n", "services/__init__.py": ""},+ 1,+ id="webhook_consumers_from_internals_bare_relative",+ ),+ pytest.param(+ {"webhook_consumers.py": "from .facade.api import f\n", "facade/api.py": ""},+ 0,+ id="webhook_consumers_from_facade_relatively",+ ),+ pytest.param(+ {"presentation/views.py": "from ..services import thing\n", "services/thing.py": ""},+ 1,+ id="presentation_from_internals_relatively",+ ),+ pytest.param(+ {"presentation/views.py": "from ..facade.api import f\n", "facade/api.py": ""},+ 0,+ id="presentation_from_facade_relatively",+ ),+ pytest.param(+ {"routes.py": "from .presentation.views import V\n", "presentation/views.py": ""},+ 0,+ id="routes_from_presentation_relatively",+ ),+ # Climbing out of backend/ leaves this check's tree, so the resolver must not+ # report a module built from the leftover parts.+ pytest.param(+ {"presentation/views.py": "from ....other.backend.models import M\n"},+ 0,+ id="relative_import_above_the_product",+ ),],)def test_surface(@@ -1256,6 +1304,60 @@ class TestImportSurfaceCheck:ctx = self._ctx(tmp_path, files, monkeypatch, ignored={edge})assert ImportSurfaceCheck().run(ctx).issues == []+ @pytest.mark.parametrize(+ "files, should_run, expected",+ [+ # The ingress contract holds for any product that registers a consumer, sealed+ # or not.+ pytest.param(+ {+ "webhook_consumers.py": "from .services.handlers import h\n",+ "services/handlers.py": "",+ },+ True,+ 1,+ id="unsealed_consumer_reaching_internals",+ ),+ pytest.param(+ {"webhook_consumers.py": "from .facade.api import f\n", "facade/api.py": ""},+ True,+ 0,+ id="unsealed_consumer_reaching_facade",+ ),+ # An unsealed product has no routes/presentation contract, so that layout stays+ # its own business.+ 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": "",+ },+ True,+ 0,+ id="unsealed_routes_stay_unchecked",+ ),+ pytest.param(+ {"routes.py": "from .api.views import V\n", "api/views.py": ""},+ False,+ 0,+ id="unsealed_without_consumer_does_not_run",+ ),+ ],+ )+ def test_unsealed_product(+ self,+ tmp_path: Path,+ files: dict[str, str],+ should_run: bool,+ expected: int,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ ctx = self._ctx(tmp_path, files, monkeypatch, is_isolated=False)+ check = ImportSurfaceCheck()+ assert check.should_run(ctx) is should_run+ assert len(check.run(ctx).issues) == expected+class TestFileFolderConflictsCheck:def test_skip_when_no_backend(self, tmp_path: Path) -> None: