: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
fix(devex): detect facade functions in facade submodules (#113803)
Julian Beza6ae3be3f85f
diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex 7451c676eed2..ea3848822257 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -34,6 +34,7 @@ from .ast_helpers import (decorator_name,get_imported_module_names,get_model_names,+ get_public_function_names,has_any_function_defs,iter_public_callables,lazy_reexport_map,@@ -156,12 +157,6 @@ def has_contracts_module(backend_dir: Path) -> bool:return (backend_dir / "facade" / "contracts.py").exists() or (backend_dir / "facade" / "contracts").exists()-def has_real_facade(backend_dir: Path) -> bool:- """A real facade defines functions; a re-export shim from logic does not count."""- facade_api = backend_dir / "facade" / "api.py"- return facade_api.exists() and has_any_function_defs(facade_api)--def has_routes_module(backend_dir: Path) -> bool:"""The product-local route-registration entry point (a routes.py file or routes/ package).@@ -722,6 +717,65 @@ def _iter_facade_modules(backend_dir: Path) -> Iterator[Path]:yield path+_NON_LOGIC_FACADE_MODULES = frozenset({"contracts.py", "enums.py", "testing.py"})+++def iter_facade_logic_modules(backend_dir: Path) -> Iterator[Path]:+ """Facade modules that can hold facade logic: every module except contracts, enums and testing.++ Products split their facade across submodules, so the walk is recursive. The three names are+ skipped at any depth: they hold types and test helpers, never the facade surface."""+ for path in _iter_facade_modules(backend_dir):+ if path.name in _NON_LOGIC_FACADE_MODULES:+ continue+ # A contracts/ package holds types like contracts.py does.+ if "contracts" in path.relative_to(backend_dir / "facade").parts[:-1]:+ continue+ yield path+++def facade_function_names(backend_dir: Path) -> list[str]:+ """Public functions defined across the facade modules; re-export-only modules add none."""+ names: list[str] = []+ for path in iter_facade_logic_modules(backend_dir):+ names.extend(get_public_function_names(path))+ return names+++_FACADE_MODULE_PATTERN = re.compile(r"\.backend\.facade(\.|$)")+++def _api_reexports_internals(api_path: Path) -> bool:+ """`api.py` defines nothing and re-exports from outside the facade package, e.g. `from ..logic import x`."""+ if has_any_function_defs(api_path):+ return False+ tree = ast_parse_safe(api_path)+ if tree is None:+ return False+ # Only runtime imports at module level count. An `if TYPE_CHECKING:` import is a type hint.+ for node in tree.body:+ if not isinstance(node, ast.ImportFrom):+ continue+ if node.level >= 2:+ return True+ module = node.module or ""+ if node.level == 0 and ".backend." in module and not _FACADE_MODULE_PATTERN.search(module):+ return True+ return False+++def has_real_facade(backend_dir: Path) -> bool:+ """A real facade defines functions in any of its modules; a re-export shim from logic does not count.++ An `api.py` that only re-exports internals marks the whole facade as a shim, so one helper in a+ sibling module does not promote it. Private functions count, so a facade with only helpers is not+ read as a shim."""+ api_path = backend_dir / "facade" / "api.py"+ if api_path.exists() and _api_reexports_internals(api_path):+ return False+ return any(has_any_function_defs(path) for path in iter_facade_logic_modules(backend_dir))++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()diff --git a/tools/hogli-commands/hogli_commands/product/maturity.py b/tools/hogli-commands/hogli_commands/product/maturity.pyindex bb19dab4a1c1..2416ee3f598b 100644--- a/tools/hogli-commands/hogli_commands/product/maturity.py+++ b/tools/hogli-commands/hogli_commands/product/maturity.py@@ -30,8 +30,6 @@ from .ast_helpers import (get_frozen_dataclass_names,get_model_names,get_orm_bound_serializer_names,- get_public_function_names,- has_any_function_defs,imports_any,view_facade_usage,)@@ -39,8 +37,11 @@ from .isolation import (IsolationRung,IsolationStatus,compute_isolation_status,+ facade_function_names,has_legacy_interface_leaks,+ has_real_facade,has_tach_interface,+ iter_facade_logic_modules,presentation_bypass_entries,)from .paths import PRODUCTS_DIR, REPO_ROOT, TACH_TOML, find_views_path, get_tach_block@@ -271,43 +272,41 @@ def score_facade(backend_dir: Path) -> DimensionScore:"the public contract other products read against.")- # Facade — must have actual function definitions, not just re-exports+ # Facade — must have actual function definitions in some facade module, not just re-exportsfacade_path = backend_dir / "facade" / "api.py"- real_facade = False- if facade_path.exists():- real_facade = has_any_function_defs(facade_path)- if not real_facade:- parts.append("facade (re-export only)")+ fn_names = facade_function_names(backend_dir)+ real_facade = has_real_facade(backend_dir)+ if real_facade:+ impure = any(imports_any(path, ["rest_framework"]) for path in iter_facade_logic_modules(backend_dir))+ if not impure:+ score += 20+ else:+ score += 5+ parts.append("facade (impure)")next_steps.append(- "backend/facade/api.py only re-exports; it doesn't define any functions. Move "- "logic into real `def` entrypoints (`list_*`, `get_*`, `create_*`, `update_*`, "- "`delete_*`) that map ORM rows to contract dataclasses before returning."+ "Remove `rest_framework` imports from the backend/facade/ modules. The facade must "+ "return contract dataclasses; serializing to DRF Response belongs in "+ "presentation/views.py.")- else:- impure = imports_any(facade_path, ["rest_framework"])- fn_names = get_public_function_names(facade_path)- if not impure:- score += 20- else:- score += 5- parts.append("facade (impure)")- next_steps.append(- "Remove `rest_framework` imports from backend/facade/api.py. The facade must "- "return contract dataclasses; serializing to DRF Response belongs in "- "presentation/views.py."- )-- if len(fn_names) >= 3:- score += 20- parts.append(f"facade ({len(fn_names)} methods)")- elif fn_names:- score += 5- parts.append(f"facade (stub, {len(fn_names)} method)")- next_steps.append(- f"Facade is a stub ({len(fn_names)} method). Add a method per capability the "- "product exposes — list, retrieve, create, update, delete, plus any async "- "task entrypoints. Each viewset action and Celery task should call exactly one."- )++ if len(fn_names) >= 3:+ score += 20+ parts.append(f"facade ({len(fn_names)} methods)")+ elif fn_names:+ score += 5+ parts.append(f"facade (stub, {len(fn_names)} method)")+ next_steps.append(+ f"Facade is a stub ({len(fn_names)} method). Add a method per capability the "+ "product exposes — list, retrieve, create, update, delete, plus any async "+ "task entrypoints. Each viewset action and Celery task should call exactly one."+ )+ elif facade_path.exists():+ parts.append("facade (re-export only)")+ next_steps.append(+ "backend/facade/api.py only re-exports; it doesn't define any functions. Move "+ "logic into real `def` entrypoints (`list_*`, `get_*`, `create_*`, `update_*`, "+ "`delete_*`) that map ORM rows to contract dataclasses before returning."+ )else:parts.append("no facade")next_steps.append(@@ -429,8 +428,7 @@ def score_presentation(name: str, backend_dir: Path, pyproject_text: str | Noneorm_queries = len(orm_locations)# Check if the facade is real (has function definitions, not re-exports)- facade_api = backend_dir / "facade" / "api.py"- real_facade = facade_api.exists() and has_any_function_defs(facade_api)+ real_facade = has_real_facade(backend_dir)# Ground truth wins over the AST heuristic: each open import-linter deferral is a# view that still bypasses the facade, so the product is not internally sealed.diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex 3dbf259e506d..d4575d9a41aa 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -39,10 +39,12 @@ from hogli_commands.product.isolation import (IsolationRung,facade_carveout_modules,facade_class_imports,+ facade_function_names,facade_model_crossings,facade_shape_findings,facade_unapproved_wiring,has_narrowed_turbo_inputs,+ has_real_facade,permanent_interface_modules,routes_in_turbo_inputs,uncovered_carveout_modules,@@ -421,6 +423,76 @@ class TestIsolationChainTurnOn:assert not any("inert" in i for i in result.issues)+class TestHasRealFacade:+ @pytest.mark.parametrize(+ "facade_files, expected_names",+ [+ pytest.param({"api.py": "def list_items() -> list[int]:\n return []\n"}, ["list_items"], id="api_py"),+ pytest.param(+ {+ "api.py": "from .writes import create_item as create_item\n",+ "writes.py": "def create_item() -> None:\n pass\n",+ },+ ["create_item"],+ id="submodule_with_reexport_only_api",+ ),+ pytest.param(+ {"nested/reads.py": "def get_item() -> None:\n pass\n"}, ["get_item"], id="nested_submodule"+ ),+ pytest.param({"api.py": "from .writes import create_item\n"}, [], id="reexport_only"),+ pytest.param(+ {"enums.py": "def label() -> str:\n return ''\n", "testing.py": "def fake() -> None:\n pass\n"},+ [],+ id="only_contracts_enums_testing",+ ),+ pytest.param(+ {"contracts/widgets.py": "def build_widget() -> None:\n pass\n"}, [], id="contracts_package"+ ),+ pytest.param({"test_api.py": "def test_it() -> None:\n pass\n"}, [], id="test_module_ignored"),+ ],+ )+ def test_functions_in_any_facade_module(+ self, tmp_path: Path, facade_files: dict[str, str], expected_names: list[str]+ ) -> None:+ _, backend_dir = _write_facade_product(tmp_path, facade_files=facade_files)++ assert facade_function_names(backend_dir) == expected_names+ assert has_real_facade(backend_dir) is bool(expected_names)++ @pytest.mark.parametrize(+ "api_source",+ [+ pytest.param("from ..logic import run as run\n", id="relative_logic_reexport"),+ pytest.param("from products.my_product.backend.logic import run as run\n", id="absolute_logic_reexport"),+ pytest.param(+ "from products.my_product.backend.facade_legacy import run as run\n", id="facade_prefix_is_not_facade"+ ),+ ],+ )+ def test_logic_reexport_api_is_a_shim_despite_sibling_helpers(self, tmp_path: Path, api_source: str) -> None:+ _, backend_dir = _write_facade_product(+ tmp_path,+ facade_files={"api.py": api_source, "activity.py": "def model_activity() -> None:\n pass\n"},+ sources={"logic.py": "def run() -> None:\n pass\n"},+ )++ assert has_real_facade(backend_dir) is False++ def test_type_checking_import_does_not_make_a_shim(self, tmp_path: Path) -> None:+ api_source = (+ "from typing import TYPE_CHECKING\n"+ "if TYPE_CHECKING:\n"+ " from ..logic import Thing\n"+ "from .reads import get_thing as get_thing\n"+ )+ _, backend_dir = _write_facade_product(+ tmp_path,+ facade_files={"api.py": api_source, "reads.py": "def get_thing() -> None:\n pass\n"},+ )++ assert has_real_facade(backend_dir) is True++class TestIsolationRung:@pytest.mark.parametrize("strict, real_facade, tach_interface, skip_configured, expected",