: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(hogli): validate canonical facade alternation in tach.toml (#56699)
Julian Bezc5f8bf2372a1
diff --git a/tach.toml b/tach.tomlindex ddbefece76e3..5260d1b5de4b 100644--- a/tach.toml+++ b/tach.toml@@ -491,7 +491,7 @@ expose = ["backend\\.presentation\\.views.*",]from = [- "products\\.(experiments|mcp_store|notifications|visual_review|tracing|metrics|mcp_analytics|platform_features)",+ "products\\.(experiments|mcp_analytics|mcp_store|metrics|notifications|tracing|visual_review)",]# TODO: Experiments-specific temporary interfacediff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex 1d7d47585b49..d848ee89fca5 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -12,6 +12,7 @@ import reimport jsonimport shlexfrom abc import ABC, abstractmethod+from collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -35,31 +36,57 @@ def check_file_exists(backend_dir: Path, path: str) -> bool:return False+def _iter_interface_blocks(tach_content: str) -> Iterator[tuple[list[str], list[str]]]:+ """Yield (expose_patterns, from_patterns) for every [[interfaces]] block."""+ for match in re.finditer(r"\[\[interfaces\]\]\s*\n(.*?)(?=\[\[|\Z)", tach_content, re.DOTALL):+ block = match.group(1)+ expose_match = re.search(r"expose\s*=\s*\[(.*?)\]", block, re.DOTALL)+ from_match = re.search(r"from\s*=\s*\[(.*?)\]", block, re.DOTALL)+ if not expose_match or not from_match:+ continue+ expose_patterns = re.findall(r'"(.*?)"', expose_match.group(1))+ from_patterns = re.findall(r'"(.*?)"', from_match.group(1))+ yield expose_patterns, from_patterns+++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:+ 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 []+ yield path, depends_on+++def _pattern_targets_public_surface(pattern: str) -> bool:+ """True if a tach expose pattern targets backend.facade or backend.presentation.++ Strips backslashes first so it works on both the on-disk TOML form (`\\.`,+ two literal backslashes) and Python-string fixtures (single backslash).+ """+ normalized = pattern.replace("\\", "")+ return normalized.startswith("backend.facade") or normalized.startswith("backend.presentation")++def has_legacy_interface_leaks(tach_content: str, module_path: str) -> bool:"""Check if a product has legacy interface leak blocks in tach.toml.These are products where core (posthog/ee) still imports internals directly,so they can't safely be tested in isolation via contract-check.- Detected structurally: an [[interfaces]] block that exposes non-facade paths- (anything other than backend.facade or backend.presentation) and references- this specific module in its from = [...] field.+ Detected structurally: an [[interfaces]] block whose `from` is exactly this+ module and whose `expose` includes any non-facade/non-presentation pattern."""- # Find all [[interfaces]] blocks and check if any expose non-facade paths- # for this specific module.- for match in re.finditer(r"\[\[interfaces\]\]\s*\n(.*?)(?=\[\[|\Z)", tach_content, re.DOTALL):- block = match.group(1)- # Check if this block references our module in from = [...]- if not re.search(rf'from\s*=\s*\[\s*"{re.escape(module_path)}"\s*,?\s*\]', block):- continue- # Check if any expose pattern is NOT facade or presentation- expose_match = re.search(r"expose\s*=\s*\[(.*?)\]", block, re.DOTALL)- if not expose_match:+ for expose_patterns, from_patterns in _iter_interface_blocks(tach_content):+ normalized_from = [p.replace("\\", "") for p in from_patterns]+ if normalized_from != [module_path]:continue- patterns = re.findall(r'"(.*?)"', expose_match.group(1))- for pattern in patterns:- if not pattern.startswith("backend\\.facade") and not pattern.startswith("backend\\.presentation"):- return True+ if any(not _pattern_targets_public_surface(p) for p in expose_patterns):+ return Truereturn False@@ -67,6 +94,183 @@ def is_isolated_product(backend_dir: Path) -> bool:return (backend_dir / "facade" / "contracts.py").exists() or (backend_dir / "facade" / "contracts").exists()+# ---------------------------------------------------------------------------+# Canonical facade alternation validation (global, not per-product)+# ---------------------------------------------------------------------------+++def _is_canonical_facade_expose(expose_patterns: list[str]) -> bool:+ """Canonical = every expose pattern targets backend.facade or backend.presentation."""+ if not expose_patterns:+ return False+ return all(_pattern_targets_public_surface(p) for p in expose_patterns)+++def _names_from_pattern(pattern: str) -> set[str]:+ """Extract product short names from a tach `from` pattern.++ Handles three forms:+ - "products.experiments" -> {"experiments"}+ - "products\\.experiments" -> {"experiments"}+ - "products\\.(experiments|mcp_store|...)" -> {"experiments", "mcp_store", ...}+ """+ # Normalize backslashes — tach regex uses `\.` which appears as `\\.` when+ # read as raw TOML source.+ normalized = pattern.replace("\\", "")+ m = re.match(r"^products\.\(([^)]+)\)$", normalized)+ if m:+ return {n.strip() for n in m.group(1).split("|") if n.strip()}+ m = re.match(r"^products\.([A-Za-z0-9_]+)$", normalized)+ if m:+ return {m.group(1)}+ return set()+++def validate_facade_alternation(tach_content: str, products_dir: Path) -> list[str]:+ """Validate the canonical facade `[[interfaces]]` block(s).++ Catches stale entries:+ 1. Every product named in the canonical alternation must exist as+ products/<name>/.+ 2. Every product named in the canonical alternation must have+ backend/facade/contracts.py (be isolated).+ 3. Names in alternation regexes must be sorted alphabetically.++ The inverse direction ("every isolated product must be listed") is not+ enforced — having `facade/contracts.py` is just scaffolding and doesn't+ mean the product is ready for canonical exposure.+ """+ issues: list[str] = []++ canonical_names: set[str] = set()+ found_canonical_block = False+ for expose_patterns, from_patterns in _iter_interface_blocks(tach_content):+ if not _is_canonical_facade_expose(expose_patterns):+ continue+ found_canonical_block = True+ for pattern in from_patterns:+ names = _names_from_pattern(pattern)+ if not names:+ issues.append(+ f"canonical [[interfaces]] block has unparseable from pattern '{pattern}' — "+ "expected 'products.<name>' or 'products\\.(name1|name2|...)'"+ )+ continue+ canonical_names |= names+ names_list = _ordered_names_from_alternation(pattern)+ if names_list and names_list != sorted(names_list):+ issues.append(+ f"canonical alternation is not sorted alphabetically — expected '{('|'.join(sorted(names_list)))}'"+ )++ if not found_canonical_block:+ return issues++ for name in sorted(canonical_names):+ product_dir = products_dir / name+ if not product_dir.is_dir():+ issues.append(+ f"canonical facade alternation lists '{name}' but products/{name}/ does not exist — "+ "remove the stale entry from tach.toml"+ )+ continue+ if not is_isolated_product(product_dir / "backend"):+ issues.append(+ f"canonical facade alternation lists '{name}' but products/{name}/backend/facade/contracts.py "+ "is missing — either add contracts.py or remove the entry from tach.toml"+ )++ return issues+++def _ordered_names_from_alternation(pattern: str) -> list[str] | None:+ """Return names in their original order if the pattern is an alternation, else None."""+ normalized = pattern.replace("\\", "")+ m = re.match(r"^products\.\(([^)]+)\)$", normalized)+ if m:+ return [n.strip() for n in m.group(1).split("|") if n.strip()]+ return None+++def validate_interface_blocks(tach_content: str) -> list[str]:+ """Validate individual [[interfaces]] blocks for structural problems.++ Checks:+ 1. No mixed facade + internal expose in a single block.+ 2. No overly broad expose patterns (backend.* catches everything).+ """+ issues: list[str] = []++ for expose_patterns, from_patterns in _iter_interface_blocks(tach_content):+ products = set()+ for p in from_patterns:+ products |= _names_from_pattern(p)+ product_label = ", ".join(sorted(products)) or ", ".join(from_patterns)++ has_facade = any(_pattern_targets_public_surface(p) for p in expose_patterns)+ has_internal = any(not _pattern_targets_public_surface(p) for p in expose_patterns)+ if has_facade and has_internal:+ issues.append(+ f"[[interfaces]] for {product_label} mixes facade/presentation exposes with "+ "internal exposes — split into separate blocks or remove the facade patterns "+ "from the legacy leak block"+ )++ for pattern in expose_patterns:+ normalized = pattern.replace("\\", "")+ if re.match(r"^backend\.{0,2}\*", normalized):+ issues.append(+ f"[[interfaces]] for {product_label} has overly broad expose "+ f"'{pattern}' — enumerate specific submodules instead"+ )++ return issues+++def validate_tach_references(tach_content: str) -> list[str]:+ """Validate referential integrity in tach.toml.++ Checks:+ 1. Every [[interfaces]] from must reference an existing [[modules]] path.+ 2. Every [[modules]] depends_on entry must reference an existing module.+ """+ issues: list[str] = []++ module_paths: set[str] = set()+ for path, _deps in _iter_module_blocks(tach_content):+ module_paths.add(path)++ for _expose, from_patterns in _iter_interface_blocks(tach_content):+ for pattern in from_patterns:+ names = _names_from_pattern(pattern)+ for name in names:+ module_path = f"products.{name}"+ if module_path not in module_paths:+ issues.append(+ f"[[interfaces]] references '{module_path}' but no [[modules]] "+ f"block with that path exists — dangling interface declaration"+ )++ for path, depends_on in _iter_module_blocks(tach_content):+ for dep in depends_on:+ if dep not in module_paths:+ issues.append(+ f"[[modules]] '{path}' depends on '{dep}' but no [[modules]] "+ f"block with that path exists — dangling dependency"+ )++ return issues+++def validate_tach_toml(tach_content: str, products_dir: Path) -> list[str]:+ """Run all tach.toml validation checks."""+ issues: list[str] = []+ issues.extend(validate_facade_alternation(tach_content, products_dir))+ issues.extend(validate_interface_blocks(tach_content))+ issues.extend(validate_tach_references(tach_content))+ return issues++# ---------------------------------------------------------------------------# Check framework# ---------------------------------------------------------------------------diff --git a/tools/hogli-commands/hogli_commands/product/lint.py b/tools/hogli-commands/hogli_commands/product/lint.pyindex 74f72a98e2c6..9044dfda28a8 100644--- a/tools/hogli-commands/hogli_commands/product/lint.py+++ b/tools/hogli-commands/hogli_commands/product/lint.py@@ -6,8 +6,8 @@ import osimport click-from .checks import CHECKS, CheckContext, is_isolated_product-from .paths import PRODUCTS_DIR, load_structure+from .checks import CHECKS, CheckContext, is_isolated_product, validate_tach_toml+from .paths import PRODUCTS_DIR, TACH_TOML, load_structure_IN_GH_ACTIONS = os.environ.get("GITHUB_ACTIONS") == "true"@@ -71,6 +71,16 @@ def lint_product(name: str, verbose: bool = True, detailed: bool = False, structreturn issues+def _lint_tach_toml() -> list[str]:+ """Validate tach.toml structure and referential integrity."""+ if not TACH_TOML.exists():+ return []+ issues = validate_tach_toml(TACH_TOML.read_text(), PRODUCTS_DIR)+ for issue in issues:+ _gh_annotation("error", "tach", "tach.toml", issue, file="tach.toml")+ return issues++def lint_all_products() -> None:product_dirs = sorted(d@@ -97,8 +107,21 @@ def lint_all_products() -> None:failed.append(product_dir.name)click.echo("")- if failed:- click.echo(f"✗ {len(failed)} product(s) failed: {', '.join(failed)}")+ click.echo("─ tach.toml")+ tach_issues = _lint_tach_toml()+ if tach_issues:+ click.echo(f" ✗ {len(tach_issues)} issue(s)")+ for issue in tach_issues:+ click.echo(f" → {issue}")+ else:+ click.echo(" ✓ ok")+ click.echo("")++ if failed or tach_issues:+ if failed:+ click.echo(f"✗ {len(failed)} product(s) failed: {', '.join(failed)}")+ if tach_issues:+ click.echo(f"✗ {len(tach_issues)} tach.toml issue(s)")raise SystemExit(1)click.echo(f"✓ All {len(product_dirs)} products passed")diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex bce96c9ea007..b6e03a83eea4 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -16,8 +16,12 @@ from hogli_commands.product.checks import (ProductYamlOwnersCheck,_has_test_files,_is_noop_script,+ _names_from_pattern,_parse_pytest_paths,has_legacy_interface_leaks,+ validate_facade_alternation,+ validate_interface_blocks,+ validate_tach_references,)# ---------------------------------------------------------------------------@@ -662,3 +666,269 @@ class TestFileFolderConflictsCheck:assert len(result.issues) == len(expect_conflicts)for stem in expect_conflicts:assert any(f"backend/{stem}" in i and f"backend/{stem[:-3]}/" in i for i in result.issues), result.issues+++# ---------------------------------------------------------------------------+# validate_facade_alternation — global tach.toml check+# ---------------------------------------------------------------------------+++def _mkproduct(products_dir: Path, name: str, *, isolated: bool) -> None:+ p = products_dir / name+ (p / "backend").mkdir(parents=True)+ (p / "__init__.py").write_text("")+ (p / "backend" / "__init__.py").write_text("")+ if isolated:+ (p / "backend" / "facade").mkdir()+ (p / "backend" / "facade" / "contracts.py").write_text("")+++_CANONICAL_BLOCK = """\+[[interfaces]]+expose = [+ "backend\\\\.facade.*",+ "backend\\\\.presentation\\\\.views.*",+]+from = [+ "products\\\\.(alpha|beta)",+]+"""+++_LEGACY_ONLY_TACH = """\+[[interfaces]]+expose = ["backend\\\\.models.*"]+from = ["products.alpha"]+"""++# Real tach.toml on disk uses literal `\\.` (two backslashes + dot).+# `_CANONICAL_BLOCK` already encodes that form via escaped backslashes in+# the Python source — `\\\\` in source is two literal backslashes at runtime.+# This row uses a non-alternation single-name `from` so the parametrized+# test additionally exercises that branch of `_names_from_pattern`.+_CANONICAL_SINGLE_NAME_TACH = (+ "[[interfaces]]\n"+ 'expose = [\n "backend\\\\.facade.*",\n "backend\\\\.presentation\\\\.views.*",\n]\n'+ 'from = [\n "products\\\\.alpha",\n]\n'+)+++class TestValidateFacadeAlternation:+ @pytest.mark.parametrize(+ "products, tach, expected_substrings",+ [+ # Empty tach — nothing to validate.+ ([], "", []),+ # Only a legacy-leak block — TachCheck handles per-product, this+ # validator stays quiet.+ ([("alpha", True)], _LEGACY_ONLY_TACH, []),+ # Clean alternation: every listed product exists and is isolated.+ ([("alpha", True), ("beta", True)], _CANONICAL_BLOCK, []),+ # Stale entry: product listed but not on disk.+ ([("alpha", True)], _CANONICAL_BLOCK, [("beta", "does not exist")]),+ # Stale entry: product on disk but missing contracts.py.+ (+ [("alpha", True), ("beta", False)],+ _CANONICAL_BLOCK,+ [("beta", "contracts.py")],+ ),+ # On-disk single-name `from` (no alternation) parses.+ ([("alpha", True)], _CANONICAL_SINGLE_NAME_TACH, []),+ # Non-listed isolated products are tolerated — having+ # facade/contracts.py is just scaffolding, not a commitment to+ # canonical exposure.+ (+ [("alpha", True), ("beta", True), ("gamma", True)],+ _CANONICAL_BLOCK,+ [],+ ),+ ],+ ids=[+ "empty_tach",+ "legacy_only_block_silent",+ "clean_alternation",+ "stale_entry_missing_on_disk",+ "stale_entry_not_isolated",+ "on_disk_single_name_form_parses",+ "isolated_but_not_in_alternation_is_tolerated",+ ],+ )+ def test_validate(+ self,+ tmp_path: Path,+ products: list[tuple[str, bool]],+ tach: str,+ expected_substrings: list[tuple[str, ...]],+ ) -> None:+ for name, isolated in products:+ _mkproduct(tmp_path, name, isolated=isolated)+ issues = validate_facade_alternation(tach, tmp_path)+ if not expected_substrings:+ assert issues == []+ return+ for substrings in expected_substrings:+ assert any(all(s in issue for s in substrings) for issue in issues), (+ f"no issue matched all of {substrings!r}; got {issues!r}"+ )+++class TestNamesFromPattern:+ @pytest.mark.parametrize(+ "pattern, expected",+ [+ ("products.experiments", {"experiments"}),+ ("products\\.experiments", {"experiments"}),+ ("products\\\\.experiments", {"experiments"}),+ ("products\\.(a|b|c)", {"a", "b", "c"}),+ ("products\\\\.(a|b|c)", {"a", "b", "c"}),+ ("products\\.(experiments|mcp_store|tracing)", {"experiments", "mcp_store", "tracing"}),+ ("posthog.api", set()),+ ("products.something.deeper", set()),+ ("", set()),+ ],+ )+ def test_extraction(self, pattern: str, expected: set[str]) -> None:+ assert _names_from_pattern(pattern) == expected+++# ---------------------------------------------------------------------------+# validate_interface_blocks — per-block structural checks+# ---------------------------------------------------------------------------+++def _iface(expose: list[str], frm: str = "products.x") -> str:+ expose_str = ", ".join(f'"{e}"' for e in expose)+ return f'[[interfaces]]\nexpose = [{expose_str}]\nfrom = ["{frm}"]\n'+++class TestValidateInterfaceBlocks:+ @pytest.mark.parametrize(+ "expose, expected_issue",+ [+ # Pure facade — clean.+ (["backend\\\\.facade.*", "backend\\\\.presentation\\\\.views.*"], None),+ # Pure legacy — clean.+ (["backend\\\\.models.*", "backend\\\\.logic.*"], None),+ # Mixed facade + internal — error.+ (+ ["backend\\\\.facade.*", "backend\\\\.models.*"],+ "mixes facade/presentation",+ ),+ # Mixed presentation + internal — error.+ (+ ["backend\\\\.presentation\\\\.views.*", "backend\\\\.logic.*"],+ "mixes facade/presentation",+ ),+ # Overly broad: backend.* (raw).+ (["backend.*"], "overly broad"),+ # Overly broad: backend\\..* (tach regex form).+ (["backend\\\\..*"], "overly broad"),+ # Overly broad: backend.** (globstar).+ (["backend\\\\.**"], "overly broad"),+ # Specific submodule — not broad.+ (["backend\\\\.models.*"], None),+ ],+ ids=[+ "pure_facade",+ "pure_legacy",+ "mixed_facade_internal",+ "mixed_presentation_internal",+ "broad_raw",+ "broad_tach_regex",+ "broad_globstar",+ "specific_submodule",+ ],+ )+ def test_blocks(self, expose: list[str], expected_issue: str | None) -> None:+ tach = _iface(expose)+ issues = validate_interface_blocks(tach)+ if expected_issue is None:+ assert issues == [], f"unexpected issues: {issues}"+ else:+ assert any(expected_issue in i for i in issues), (+ f"expected substring {expected_issue!r} in issues; got {issues!r}"+ )+++# ---------------------------------------------------------------------------+# validate_tach_references — referential integrity+# ---------------------------------------------------------------------------+++class TestValidateTachReferences:+ @pytest.mark.parametrize(+ "tach, expected_substrings",+ [+ # Clean: interface references existing module.+ (+ '[[modules]]\npath = "products.alpha"\ndepends_on = []\n\n'+ '[[interfaces]]\nexpose = ["backend\\\\.models.*"]\nfrom = ["products.alpha"]\n',+ [],+ ),+ # Dangling interface: references nonexistent module.+ (+ '[[modules]]\npath = "products.alpha"\ndepends_on = []\n\n'+ '[[interfaces]]\nexpose = ["backend\\\\.models.*"]\nfrom = ["products.ghost"]\n',+ [("products.ghost", "dangling interface")],+ ),+ # Dangling depends_on.+ (+ '[[modules]]\npath = "products.alpha"\ndepends_on = ["products.ghost"]\n',+ [("products.ghost", "dangling dependency")],+ ),+ # Clean depends_on.+ (+ '[[modules]]\npath = "products.alpha"\ndepends_on = []\n\n'+ '[[modules]]\npath = "products.beta"\ndepends_on = ["products.alpha"]\n',+ [],+ ),+ # Both dangling.+ (+ '[[modules]]\npath = "products.a"\ndepends_on = ["products.missing_dep"]\n\n'+ '[[interfaces]]\nexpose = ["backend\\\\.x.*"]\nfrom = ["products.missing_iface"]\n',+ [("missing_dep", "dangling dependency"), ("missing_iface", "dangling interface")],+ ),+ ],+ ids=[+ "clean_interface",+ "dangling_interface",+ "dangling_depends_on",+ "clean_depends_on",+ "both_dangling",+ ],+ )+ def test_references(self, tach: str, expected_substrings: list[tuple[str, str]]) -> None:+ issues = validate_tach_references(tach)+ if not expected_substrings:+ assert issues == []+ return+ for substrings in expected_substrings:+ assert any(all(s in issue for s in substrings) for issue in issues), (+ f"no issue matched all of {substrings!r}; got {issues!r}"+ )+++# ---------------------------------------------------------------------------+# validate_facade_alternation — alphabetical sort check+# ---------------------------------------------------------------------------+++class TestAlternationSorting:+ def test_sorted_passes(self, tmp_path: Path) -> None:+ _mkproduct(tmp_path, "alpha", isolated=True)+ _mkproduct(tmp_path, "beta", isolated=True)+ tach = _iface(+ ["backend\\\\.facade.*", "backend\\\\.presentation\\\\.views.*"],+ "products\\\\.(alpha|beta)",+ )+ assert validate_facade_alternation(tach, tmp_path) == []++ def test_unsorted_fails(self, tmp_path: Path) -> None:+ _mkproduct(tmp_path, "alpha", isolated=True)+ _mkproduct(tmp_path, "beta", isolated=True)+ tach = _iface(+ ["backend\\\\.facade.*", "backend\\\\.presentation\\\\.views.*"],+ "products\\\\.(beta|alpha)",+ )+ issues = validate_facade_alternation(tach, tmp_path)+ assert any("not sorted" in i for i in issues)