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): read facade modules in subfolders in product:lint (#110576)

Julian Bezf184aeed0c6f
diff --git a/tools/hogli-commands/hogli_commands/product/crossings.py b/tools/hogli-commands/hogli_commands/product/crossings.py
index 9dc829078b82..840b2bdd6b90 100644
--- a/tools/hogli-commands/hogli_commands/product/crossings.py
+++ b/tools/hogli-commands/hogli_commands/product/crossings.py
@@ -65,6 +65,7 @@ from .isolation import (
COMPUTED_WIRING_LOCATIONS,
MODEL_CROSSINGS,
FacadeShapeFinding,
+ _iter_facade_modules,
facade_model_crossings,
facade_shape_findings,
)
@@ -808,12 +809,14 @@ def _wiring_location_exports(product: str, location: str) -> dict[_Export, str]:
module = _dotted_module(path)
for name in _top_level_names(tree):
exports[_Export(module, name)] = label
- for facade_path in sorted((PRODUCTS_DIR / product / "backend" / "facade").glob("*.py")):
+ for facade_path in _iter_facade_modules(PRODUCTS_DIR / product / "backend"):
tree = ast_parse_safe(facade_path)
if tree is None:
continue
for name, source in _lazy_reexports(tree, product, _module_exists).items():
- if (REPO_ROOT / source.replace(".", "/")).with_suffix(".py").is_relative_to(root):
+ # The source is a module or a package, so test both the package directory and the .py file.
+ source_path = REPO_ROOT / source.replace(".", "/")
+ if source_path.is_relative_to(root) or source_path.with_suffix(".py").is_relative_to(root):
exports[_Export(_dotted_module(facade_path), name)] = label
return exports
diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.py
index 6a85b9fcb076..ed5faed22840 100644
--- a/tools/hogli-commands/hogli_commands/product/isolation.py
+++ b/tools/hogli-commands/hogli_commands/product/isolation.py
@@ -629,7 +629,7 @@ MODEL_SURFACE_PREFIXES: tuple[str, ...] = (*_MODEL_SOURCE_PREFIXES, "backend/mig
class FacadeClassImport:
"""A class a facade module re-exports from a product-internal module outside a wiring location."""
- facade_module: str # e.g. "queries.py"
+ facade_module: str # path inside facade/, e.g. "queries.py" or "destinations/s3.py"
class_name: str # e.g. "MetricsQueryRunner"
source_path: str # backend-relative, e.g. "backend/metrics_query_runner.py"
@@ -701,18 +701,32 @@ def _is_test_module(filename: str) -> bool:
def _iter_facade_modules(backend_dir: Path) -> Iterator[Path]:
- """Every facade module the facade checks read, in name order.
-
- Flat by design: facade/ holds no packages, and both callers key a finding on the file name. Test
- modules that happen to sit here are pytest files, not part of the surface."""
+ """Every facade module the facade checks read, in path order.
+
+ The walk is recursive, so a module in a facade subfolder (`facade/destinations/s3.py`) gets the
+ same checks as a flat one. A finding is keyed on the module's path inside facade/
+ (`_facade_module_key`). Rules that read a module's content apply at any depth. Exemptions by
+ name (contracts.py, enums.py, testing.py, api*.py and the capability stems) apply to top-level
+ modules only: a nested `destinations/contracts.py` is an ordinary module. Test modules that
+ happen to sit here are pytest files, not part of the surface."""
facade_dir = backend_dir / "facade"
if not facade_dir.is_dir():
return
- for path in sorted(facade_dir.glob("*.py")):
- if not _is_test_module(path.name):
+ for path in sorted(facade_dir.rglob("*.py")):
+ if "__pycache__" not in path.parts and not _is_test_module(path.name):
yield path
+def _facade_module_key(backend_dir: Path, path: Path) -> str:
+ """A facade module's path inside facade/ as a posix string: `api.py`, `destinations/s3.py`."""
+ return path.relative_to(backend_dir / "facade").as_posix()
+
+
+def _facade_package_parts(module_key: str) -> list[str]:
+ """The package a facade module sits in, for resolving its relative imports."""
+ return ["facade", *module_key.split("/")[:-1]]
+
+
@dataclass(frozen=True)
class _HandedOutName:
"""A product-internal name one facade module hands out, and the module that defines it."""
@@ -722,7 +736,9 @@ class _HandedOutName:
source_path: str # backend-relative, e.g. "backend/logic/crud.py"
-def _iter_handed_out_names(tree: ast.Module, backend_dir: Path) -> Iterator[_HandedOutName]:
+def _iter_handed_out_names(
+ tree: ast.Module, backend_dir: Path, package_parts: Sequence[str]
+) -> Iterator[_HandedOutName]:
"""Every product-internal name one facade module hands out, wiring locations included (callers
filter). Three shapes are read:
@@ -739,7 +755,7 @@ def _iter_handed_out_names(tree: ast.Module, backend_dir: Path) -> Iterator[_Han
"""
is_pure_reexport = not tree_has_top_level_functions(tree)
allowed = None if is_pure_reexport else module_dunder_all(tree)
- for imported in iter_module_imported_names(tree, ("facade",), backend_dir):
+ for imported in iter_module_imported_names(tree, package_parts, backend_dir):
if imported.source_path is None:
continue
handed_out = (
@@ -761,17 +777,19 @@ def _iter_facade_class_reexports(backend_dir: Path) -> Iterator[FacadeClassImpor
nor wiring location — carve-outs included (callers filter)."""
parse_cache: dict[Path, ast.Module | None] = {}
for module_file in _iter_facade_modules(backend_dir):
+ module_key = _facade_module_key(backend_dir, module_file)
# contracts/enums are the sanctioned homes for data types, so neither is a wiring re-export.
- if module_file.name in ("contracts.py", "enums.py"):
+ # The exemption is for the top-level modules only.
+ if module_key in ("contracts.py", "enums.py"):
continue
tree = ast_parse_safe(module_file)
if tree is None:
continue
- for handed in _iter_handed_out_names(tree, backend_dir):
+ for handed in _iter_handed_out_names(tree, backend_dir, _facade_package_parts(module_key)):
if _is_facade_or_garage(handed.source_path):
continue
if _name_is_class(handed.source_path, handed.original, backend_dir, cache=parse_cache):
- yield FacadeClassImport(module_file.name, handed.original, handed.source_path)
+ yield FacadeClassImport(module_key, handed.original, handed.source_path)
@dataclass(frozen=True)
@@ -1068,7 +1086,7 @@ def _facade_import_env(
tree: ast.Module,
model_names: _ModelNames,
backend_dir: Path,
- package_parts: Sequence[str] = ("facade",),
+ package_parts: Sequence[str],
) -> _FacadeImportEnv:
types: dict[str, _ForbiddenType] = {}
modules: dict[str, str] = {}
@@ -1469,7 +1487,7 @@ def _iter_reexport_signature_findings(
}
parse_cache: dict[str, ast.Module | None] = {}
env_cache: dict[str, _FacadeImportEnv] = {}
- handed_out = set(_iter_handed_out_names(tree, backend_dir))
+ handed_out = set(_iter_handed_out_names(tree, backend_dir, _facade_package_parts(facade_module)))
for handed in sorted(handed_out, key=lambda h: (h.bound, h.original, h.source_path)):
# A real definition wins over a re-export, and the module scan already read it.
if handed.bound.startswith("_") or handed.bound in defined_here:
@@ -1547,29 +1565,34 @@ def _capability_finding(
)
-def _is_capability_module(tree: ast.Module, filename: str, backend_dir: Path) -> bool:
+def _is_capability_module(tree: ast.Module, module_key: str, backend_dir: Path) -> bool:
"""True when a facade module is a capability submodule: one whose job is to hand out wiring or
model classes.
Read from what the module hands out rather than from its name, because a product may call the
same wiring anything (`workflow_tasks.py`, `tools.py`) and a filename allowlist then misses it.
- The doctrine stems stay a floor, so such a module keeps the rule before it hands anything out."""
- stem = filename.removesuffix(".py")
- if stem in CAPABILITY_SUBMODULES:
- return True
- if stem.startswith("api") or stem in _NON_CAPABILITY_FACADE_STEMS:
- return False
+ The doctrine stems stay a floor, so such a module keeps the rule before it hands anything out.
+ The stems apply to top-level modules only; what a module hands out is read at any depth."""
+ if "/" not in module_key:
+ stem = module_key.removesuffix(".py")
+ if stem in CAPABILITY_SUBMODULES:
+ return True
+ if stem.startswith("api") or stem in _NON_CAPABILITY_FACADE_STEMS:
+ return False
wiring = (*GARAGE_PREFIXES, *MODEL_SURFACE_PREFIXES)
- return any(handed.source_path.startswith(wiring) for handed in _iter_handed_out_names(tree, backend_dir))
+ package_parts = _facade_package_parts(module_key)
+ return any(
+ handed.source_path.startswith(wiring) for handed in _iter_handed_out_names(tree, backend_dir, package_parts)
+ )
-def _facade_module_dotted(product: str, filename: str) -> str:
- """`products.<product>.backend.facade.<module>` for one facade file. A package __init__ names
- the package itself, the same rule the crossings scan uses for a repo path."""
- parts = ["products", product, "backend", "facade"]
- stem = filename.removesuffix(".py")
- if stem != "__init__":
- parts.append(stem)
+def _facade_module_dotted(product: str, module_key: str) -> str:
+ """`products.<product>.backend.facade.<module>` for one facade file, from its path inside
+ facade/ (`destinations/s3.py` -> `...facade.destinations.s3`). A package __init__ names the
+ package itself, the same rule the crossings scan uses for a repo path."""
+ parts = ["products", product, "backend", "facade", *module_key.removesuffix(".py").split("/")]
+ if parts[-1] == "__init__":
+ parts.pop()
return ".".join(parts)
@@ -1587,14 +1610,15 @@ def facade_shape_findings(backend_dir: Path, name: str) -> list[FacadeShapeFindi
tree = ast_parse_safe(path)
if tree is None:
continue
- dotted_module = _facade_module_dotted(name, path.name)
- env = _facade_import_env(tree, model_names, backend_dir)
- findings.extend(_iter_module_signature_findings(tree, env, name, path.name, dotted_module))
+ module_key = _facade_module_key(backend_dir, path)
+ dotted_module = _facade_module_dotted(name, module_key)
+ env = _facade_import_env(tree, model_names, backend_dir, _facade_package_parts(module_key))
+ findings.extend(_iter_module_signature_findings(tree, env, name, module_key, dotted_module))
findings.extend(
- _iter_reexport_signature_findings(tree, backend_dir, name, path.name, dotted_module, model_names)
+ _iter_reexport_signature_findings(tree, backend_dir, name, module_key, dotted_module, model_names)
)
- if _is_capability_module(tree, path.name, backend_dir):
- logic = _capability_finding(tree, name, path.name, dotted_module)
+ if _is_capability_module(tree, module_key, backend_dir):
+ logic = _capability_finding(tree, name, module_key, dotted_module)
if logic is not None:
findings.append(logic)
return sorted(findings, key=lambda f: (f.facade_module, f.symbol, f.kind, f.type_name, f.parameter))
diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.py
index e35d69a99455..afcd7ef9f2e7 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py
@@ -117,6 +117,7 @@ def _write_facade_product(
facade.mkdir(parents=True)
(facade / "contracts.py").write_text("")
for fname, content in (facade_files or {}).items():
+ (facade / fname).parent.mkdir(parents=True, exist_ok=True)
(facade / fname).write_text(content)
for rel, content in (sources or {}).items():
path = backend_dir / rel
@@ -1910,6 +1911,35 @@ class TestFacadeClassImports:
_, backend = _write_facade_product(tmp_path, facade_files=facade_files, sources=sources)
assert {f.class_name for f in facade_class_imports(backend, "my_product")} == expected
+ @pytest.mark.parametrize(
+ "facade_files, expected_modules",
+ [
+ # a flat module keeps its bare file name as the key
+ ({"api.py": "from ..logic import Thing\n__all__ = ['Thing']\n"}, {"api.py"}),
+ # a module in a subfolder is read and keyed by its path inside facade/
+ ({"destinations/s3.py": "from ...logic import Thing\n__all__ = ['Thing']\n"}, {"destinations/s3.py"}),
+ # contracts.py and enums.py are exempt at the top level only
+ ({"contracts.py": "from ..logic import Thing\n__all__ = ['Thing']\n"}, set()),
+ (
+ {"destinations/contracts.py": "from ...logic import Thing\n__all__ = ['Thing']\n"},
+ {"destinations/contracts.py"},
+ ),
+ ({"destinations/enums.py": "from ...logic import Thing\n__all__ = ['Thing']\n"}, {"destinations/enums.py"}),
+ # a tests/ folder is no hiding place: only test file names are skipped
+ (
+ {"destinations/tests/s3.py": "from ....logic import Thing\n__all__ = ['Thing']\n"},
+ {"destinations/tests/s3.py"},
+ ),
+ ],
+ )
+ def test_leaks_are_keyed_by_path_inside_facade(
+ self, tmp_path: Path, facade_files: dict[str, str], expected_modules: set[str]
+ ) -> None:
+ _, backend = _write_facade_product(
+ tmp_path, facade_files=facade_files, sources={"logic.py": "class Thing:\n pass\n"}
+ )
+ assert {f.facade_module for f in facade_class_imports(backend, "my_product")} == expected_modules
+
def test_carveout_is_not_a_violation_but_is_tracked_for_coverage(self, tmp_path: Path) -> None:
facade = {
"team_extension.py": "from ..models.tcac import TeamCustomerAnalyticsConfig\n__all__ = ['TeamCustomerAnalyticsConfig']\n"
@@ -2708,6 +2738,46 @@ class TestFacadeShape:
logic = [f for f in facade_shape_findings(backend, "my_product") if f.kind == "logic"]
assert [f.bodies for f in logic] == ([expected] if expected else [])
+ @pytest.mark.parametrize(
+ "module_key, expected_dotted",
+ [
+ ("api.py", "products.my_product.backend.facade.api"),
+ ("destinations/s3.py", "products.my_product.backend.facade.destinations.s3"),
+ ("destinations/__init__.py", "products.my_product.backend.facade.destinations"),
+ ],
+ )
+ def test_a_finding_carries_the_module_path_and_dotted_name(
+ self, tmp_path: Path, module_key: str, expected_dotted: str
+ ) -> None:
+ # A nested module reaches the models with `...`, a flat one with `..`.
+ dots = "." * (module_key.count("/") + 2)
+ backend = _write_shape_product(
+ tmp_path, {module_key: f"from {dots}models import Thing\n\n\ndef get_thing() -> Thing:\n ...\n"}
+ )
+ findings = facade_shape_findings(backend, "my_product")
+ assert [(f.facade_module, f.dotted_module) for f in findings] == [(module_key, expected_dotted)]
+
+ @pytest.mark.parametrize(
+ "module_key, expected",
+ [
+ ("testing.py", None),
+ ("destinations/testing.py", ("helper",)),
+ ],
+ )
+ def test_name_exemptions_apply_to_top_level_modules_only(
+ self, tmp_path: Path, module_key: str, expected: tuple[str, ...] | None
+ ) -> None:
+ dots = "." * (module_key.count("/") + 2)
+ backend = _write_shape_product(
+ tmp_path,
+ {
+ module_key: f"from {dots}temporal.flows import run_it\n\n__all__ = ['run_it']\n\n\ndef helper():\n return 1\n"
+ },
+ sources={"temporal/flows.py": "def run_it():\n ...\n"},
+ )
+ logic = [f for f in facade_shape_findings(backend, "my_product") if f.kind == "logic"]
+ assert [f.bodies for f in logic] == ([expected] if expected else [])
+
class TestFacadeShapeLedgerRows:
@pytest.mark.parametrize(
diff --git a/tools/hogli-commands/hogli_commands/tests/test_crossings.py b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
index 14341b2b2e7c..dda66a766edd 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_crossings.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import os
import ast
import textwrap
from pathlib import Path
@@ -678,6 +679,30 @@ class TestGarageDrives:
"helper": "products.product_analytics.backend.logic.helpers",
}
+ @pytest.mark.parametrize(
+ "source",
+ ["products.acme.backend.temporal.workflows", "products.acme.backend.temporal"],
+ ids=["module", "package"],
+ )
+ def test_lazy_map_in_a_nested_facade_module_exports_the_wiring_location(
+ self, source: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ backend = tmp_path / "products" / "acme" / "backend"
+ (backend / "temporal").mkdir(parents=True)
+ (backend / "temporal" / "__init__.py").write_text("class SyncWorkflow: ...\n")
+ (backend / "temporal" / "workflows.py").write_text("class SyncWorkflow: ...\n")
+ (backend / "facade" / "destinations").mkdir(parents=True)
+ (backend / "facade" / "destinations" / "lazy.py").write_text(
+ f'_LAZY = {{"SyncWorkflow": "{source}"}}\n\ndef __getattr__(name):\n return None\n'
+ )
+ monkeypatch.setattr(crossings, "REPO_ROOT", tmp_path)
+ monkeypatch.setattr(crossings, "PRODUCTS_DIR", tmp_path / "products")
+ monkeypatch.setattr(crossings, "_REPO_PREFIX", f"{tmp_path}{os.sep}")
+
+ exports = crossings._wiring_location_exports("acme", "backend/temporal/")
+
+ assert crossings._Export("products.acme.backend.facade.destinations.lazy", "SyncWorkflow") in exports
+
def test_top_level_names_include_constants(self) -> None:
module = "BOT_DEFINITIONS = [...]\nLIMIT: int = 5\n_private = 1\n\nclass Runner: ...\n\ndef helper(): ...\n"
assert crossings._top_level_names(ast.parse(module)) == ["BOT_DEFINITIONS", "LIMIT", "Runner", "helper"]