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.

chore(devex): catch taxonomy JSON drift before the push (#92948)

Phil Haackcda5cfdd567d
diff --git a/.agents/skills/running-ci-preflight/SKILL.md b/.agents/skills/running-ci-preflight/SKILL.md
index 9aa375d9732c..74dcdd635bfd 100644
--- a/.agents/skills/running-ci-preflight/SKILL.md
+++ b/.agents/skills/running-ci-preflight/SKILL.md
@@ -35,7 +35,7 @@ hogli ci:preflight --fix
- **`type-check` is a nudge, not a run.** Only a repo-wide mypy run matches CI (mypy follows imports, so a changed-file subset misses reverse-dependency breakage), and that costs minutes cold — too much to tax every push with. So preflight names the command instead of running it: judge whether your change is type-risky and run it yourself. CI blocks on the same command, so a type error you skip here comes back as a full re-run.
- **`complexity` warns only.** Cyclomatic complexity above 10 in a changed file shows as `⚠ warning` and never blocks; CI annotates the same warning and posts it to the CI report comment. Simplify the function when you next touch it rather than gaming the number.
- **Staleness is risk-based.** It fires when merging master _now_ would actually break something — textual merge conflicts (computed via `git merge-tree`, working tree untouched), migrations added on both sides, generated-file inputs changed on both sides, or CI workflows changed on master — plus a behind/age backstop, aggressive by default (5 commits / 2 days; env-tunable via `HOGLI_PREFLIGHT_STALE_COMMITS`/`HOGLI_PREFLIGHT_STALE_DAYS`) so we over-warn to start and tune down from telemetry. Merge master in when it fires. Advisory only, never auto-merged.
-- **`· skipped (needs stack/node)`** is expected on a bare checkout or sandbox. Start the stack with `hogli start` to run those, or let CI cover them. No hooks in your environment (no `node_modules`)? Run the loop yourself before pushing.
+- **`· skipped (needs …)`** is expected on a bare checkout or sandbox. `needs stack`/`needs clickhouse` want a running dev stack (`hogli start`), `needs node` wants `pnpm install`, `needs desktop-node` wants `pnpm --dir products/desktop install` (the nested desktop workspace is excluded from the root install and has its own lockfile), and `needs python-env` wants `uv sync`, so the synced project environment is the `python` on PATH. Satisfy what you can, or let CI cover the rest. No hooks in your environment (no `node_modules`)? Run the loop yourself before pushing.
- **Flags.** `--against <ref>` diffs against an explicit base; `--json` emits a machine-readable summary.
- **Kill switch.** `HOGLI_PREFLIGHT_DISABLED=1` makes the command (and the hook) a no-op with exit 0. It is a rollout/emergency lever — respect it; never unset it to force a run.
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.yml
index 727c691fa2ba..41409cf16f38 100644
--- a/.github/workflows/ci-python.yml
+++ b/.github/workflows/ci-python.yml
@@ -203,8 +203,7 @@ jobs:
- name: Check if the taxonomy JSON is up to date
shell: bash
run: |
- python3 bin/build-taxonomy-json.py
- git diff --exit-code -- frontend/src/taxonomy/core-filter-definitions-by-group.json
+ python3 bin/build-taxonomy-json.py --check
# Warn-only while the pre-existing violation backlog settles: findings annotate
# the diff and land in the shared CI report comment, never a job failure.
diff --git a/bin/build-taxonomy-json.py b/bin/build-taxonomy-json.py
old mode 100644
new mode 100755
index 09dda082da7e..23c6d59f840f
--- a/bin/build-taxonomy-json.py
+++ b/bin/build-taxonomy-json.py
@@ -1,23 +1,68 @@
-import os
+#!/usr/bin/env python
+"""Make CORE_FILTER_DEFINITIONS_BY_GROUP accessible frontend-side.
+
+Run via hogli: `hogli build:taxonomy-json`. `--check` is what ci-python.yml and
+`hogli ci:preflight` call to fail on drift without writing.
+"""
+# ruff: noqa: T201
+
import sys
import json
+import argparse
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+# Ahead of site-packages, so the repo's posthog wins over an installed one of the
+# same name and the check cannot compare against a different taxonomy.
+sys.path.insert(0, str(REPO_ROOT))
-# Add the project root to Python path
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP # noqa: E402 — needs the sys.path line above
-from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP
+OUTPUT = REPO_ROOT / "frontend/src/taxonomy/core-filter-definitions-by-group.json"
-filename = "frontend/src/taxonomy/core-filter-definitions-by-group.json"
-# Make CORE_FILTER_DEFINITIONS_BY_GROUP accessible frontend-side
-with open(filename, "w") as json_file:
+def render() -> str:
+ """The exact contents the generated file must hold.
+
+ The write path and --check both go through this, so the two cannot disagree
+ about the output.
+ """
with_comment = {
"//": "THIS FILE IS AUTOGENERATED. DO NOT EDIT MANUALLY. To update: pnpm run taxonomy:build",
**CORE_FILTER_DEFINITIONS_BY_GROUP, # Unpack the dictionary to include its contents
}
- json.dump(with_comment, json_file, indent=4, sort_keys=True)
+ return json.dumps(with_comment, indent=4, sort_keys=True)
+
+
+def check() -> int:
+ # Bytes, not text, so no newline translation can hide or invent a difference.
+ on_disk = OUTPUT.read_bytes() if OUTPUT.exists() else b""
+ if on_disk == render().encode():
+ return 0
+ # stdout, because ci:preflight reports `result.stdout or result.stderr`.
+ print(f"{OUTPUT.relative_to(REPO_ROOT)} is out of date with posthog/taxonomy/taxonomy.py.")
+ print("Run `hogli build:taxonomy-json` and commit the result.")
+ return 1
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Generate the frontend-side taxonomy JSON.")
+ parser.add_argument(
+ "--check",
+ action="store_true",
+ help="Exit 1 if the file on disk differs from the taxonomy, without writing anything.",
+ )
+ args = parser.parse_args()
+ if args.check:
+ return check()
+ # Do not add a formatter pass here. Nothing reformats render()'s output before it
+ # reaches the file, so the output stays byte-stable and the taxonomy drift check in
+ # ci-python.yml cannot flap. The other half of that guarantee is the ignorePatterns
+ # entry in .oxfmtrc.json, which keeps lint-staged's `bin/hogli format:yaml` (oxfmt)
+ # off this file. Keep both.
+ OUTPUT.write_bytes(render().encode())
+ return 0
+
-# Do not add a formatter pass here. json.dump is the only writer, so the output stays
-# byte-stable and the taxonomy drift check in ci-python.yml cannot flap. The other half
-# of that guarantee is the ignorePatterns entry in .oxfmtrc.json, which keeps
-# lint-staged's `bin/hogli format:yaml` (oxfmt) off this file. Keep both.
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/posthog/taxonomy/test/test_build_taxonomy_json.py b/posthog/taxonomy/test/test_build_taxonomy_json.py
new file mode 100644
index 000000000000..49a6a44b871a
--- /dev/null
+++ b/posthog/taxonomy/test/test_build_taxonomy_json.py
@@ -0,0 +1,45 @@
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+from types import ModuleType
+
+import pytest
+
+GENERATOR = Path(__file__).resolve().parents[3] / "bin" / "build-taxonomy-json.py"
+
+
+def _load_generator() -> ModuleType:
+ # Loaded by path because the dash in the filename rules out a plain import.
+ spec = importlib.util.spec_from_file_location("build_taxonomy_json", GENERATOR)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _retarget(module: ModuleType, monkeypatch: pytest.MonkeyPatch, target: Path) -> None:
+ # REPO_ROOT moves with OUTPUT because the drift branch prints
+ # OUTPUT.relative_to(REPO_ROOT), which raises for a path outside the repo.
+ monkeypatch.setattr(module, "REPO_ROOT", target.parent)
+ monkeypatch.setattr(module, "OUTPUT", target)
+
+
+class TestTaxonomyDriftDetection:
+ @pytest.mark.parametrize("on_disk", [None, b"{}"])
+ def test_check_reports_drift(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, on_disk: bytes | None) -> None:
+ module = _load_generator()
+ target = tmp_path / "core-filter-definitions-by-group.json"
+ if on_disk is not None:
+ target.write_bytes(on_disk)
+ _retarget(module, monkeypatch, target)
+
+ assert module.check() == 1
+
+ def test_check_accepts_the_rendered_bytes(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ module = _load_generator()
+ target = tmp_path / "core-filter-definitions-by-group.json"
+ target.write_bytes(module.render().encode())
+ _retarget(module, monkeypatch, target)
+
+ assert module.check() == 0
diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.py
index cc6d4d1f89ce..77ac52c12391 100644
--- a/tools/hogli-commands/hogli_commands/ci_preflight.py
+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py
@@ -50,7 +50,7 @@ from hogli_commands.complexity_lint import PYTHON_SCOPE, TEST_WARN_AT, TYPESCRIP
from hogli_commands.devenv.generator import TRACKED_MPROCS_FILES
from hogli_commands.size_lint import SCOPE as SIZE_SCOPE
-Requirement = Literal["node", "desktop-node", "stack", "clickhouse"]
+Requirement = Literal["node", "desktop-node", "stack", "clickhouse", "python-env"]
@dataclass
@@ -256,6 +256,21 @@ DIFF_CHECKS: list[DiffCheck] = [
fix=["hogli", "build:openapi"],
requires=("stack",),
),
+ DiffCheck(
+ key="taxonomy",
+ label="taxonomy JSON out of sync with posthog/taxonomy/taxonomy.py",
+ # From build.py so preflight and build:taxonomy-json can't drift on which diffs
+ # need a regen, plus the generator and its output, so an edit to any side of the
+ # relation is caught.
+ triggers=[
+ *BUILD_TRIGGERS["build:taxonomy-json"],
+ "bin/build-taxonomy-json.py",
+ "frontend/src/taxonomy/core-filter-definitions-by-group.json",
+ ],
+ verify=["hogli", "build:taxonomy-json", "--check"],
+ fix=["hogli", "build:taxonomy-json"],
+ requires=("python-env",),
+ ),
DiffCheck(
key="migrations",
label="migration conflict / orphaned migration",
@@ -312,12 +327,38 @@ def _port_open(port: int) -> bool:
return False
+def _project_python_ready() -> bool:
+ """Whether the synced project environment is the `python` on PATH.
+
+ `import posthog` is the proxy for it, because it runs `posthog/__init__.py`,
+ which is where the generator fails when the environment is stale. A narrower
+ probe such as `import django` passes on a venv that has fallen behind
+ `uv.lock`, and the check then blocks the push under a drift label it never
+ measured. `cwd` is required, because `python -c` resolves `posthog` from the
+ working directory. The probe spawns the same interpreter a
+ `#!/usr/bin/env python` script gets, so probe and subject agree. A checkout
+ without the environment must read as "skipped", not "fail".
+ """
+ try:
+ probe = subprocess.run(
+ ["python", "-c", "import posthog"],
+ cwd=REPO_ROOT,
+ capture_output=True,
+ timeout=10,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return probe.returncode == 0
+
+
def _capability_met(req: Requirement) -> bool:
if req == "node":
return _has_node_modules()
if req == "desktop-node":
# products/desktop is a nested standalone workspace with its own install.
return (REPO_ROOT / "products" / "desktop" / "node_modules" / ".pnpm").exists()
+ if req == "python-env":
+ return _project_python_ready()
if req == "stack":
# Postgres reachable — proxy for "dev stack is running".
return _port_open(5432)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py
index 7a8d4ddefcad..71540819086b 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py
@@ -7,6 +7,8 @@ from unittest.mock import MagicMock, patch
from click.testing import CliRunner
from hogli.cli import cli
+from hogli.manifest import REPO_ROOT
+from hogli_commands.change_detection import matches_globs
from hogli_commands.ci_preflight import (
COMPANION_CHECKS,
DIFF_CHECKS,
@@ -126,6 +128,94 @@ class TestStrictAndFixContracts:
assert "mypy" not in ran
+class TestTaxonomyDriftCheck:
+ @pytest.mark.parametrize(
+ "changed",
+ [
+ "posthog/taxonomy/taxonomy.py",
+ "bin/build-taxonomy-json.py",
+ "frontend/src/taxonomy/core-filter-definitions-by-group.json",
+ ],
+ )
+ def test_every_side_of_the_drift_relation_triggers(self, changed: str) -> None:
+ check = next(chk for chk in DIFF_CHECKS if chk.key == "taxonomy")
+ assert matches_globs(changed, check.triggers)
+
+ def test_concrete_triggers_still_point_at_real_files(self) -> None:
+ check = next(chk for chk in DIFF_CHECKS if chk.key == "taxonomy")
+ # Renaming the generator or its output leaves these triggers matching nothing,
+ # and preflight stops catching a hand-edit with nothing else to notice.
+ concrete = [trigger for trigger in check.triggers if "*" not in trigger]
+ assert concrete, "the generator and its output are no longer triggers"
+ # Every check carrying a hardcoded path has that same failure mode. Glob
+ # triggers cannot be checked this way, because matches_globs uses fnmatch,
+ # where `*` spans `/`, while Path.glob does not.
+ missing = {
+ chk.key: gone
+ for chk in DIFF_CHECKS
+ if (gone := [t for t in chk.triggers if "*" not in t and not (REPO_ROOT / t).exists()])
+ }
+ assert not missing, f"triggers no longer on disk: {missing}"
+
+ @patch("hogli_commands.ci_preflight._emit_telemetry")
+ @patch("hogli_commands.ci_preflight._capability_met", return_value=False)
+ @patch("hogli_commands.ci_preflight._staleness", return_value=("pass", "even with master", {}))
+ @patch("hogli_commands.ci_preflight._fetch_master")
+ @patch("hogli_commands.ci_preflight.subprocess.run")
+ @patch(
+ "hogli_commands.ci_preflight.changed_files",
+ return_value=["frontend/src/taxonomy/core-filter-definitions-by-group.json"],
+ )
+ def test_missing_project_env_skips_instead_of_failing(
+ self,
+ mock_changed: MagicMock,
+ mock_run: MagicMock,
+ mock_fetch: MagicMock,
+ mock_stale: MagicMock,
+ mock_capability: MagicMock,
+ mock_emit: MagicMock,
+ ) -> None:
+ result = runner.invoke(cli, ["ci:preflight", "--strict"])
+
+ # The generator imports Django, so a bare checkout cannot run it. Without the
+ # capability gate the run would exit ModuleNotFoundError, and --strict would
+ # block the push on a failure the diff did not cause.
+ assert result.exit_code == 0
+ assert "needs python-env" in result.output
+ ran = [arg for call in mock_run.call_args_list for arg in call.args[0]]
+ assert "build:taxonomy-json" not in ran
+
+ @patch("hogli_commands.ci_preflight._emit_telemetry")
+ @patch("hogli_commands.ci_preflight._staleness", return_value=("pass", "even with master", {}))
+ @patch("hogli_commands.ci_preflight._fetch_master")
+ @patch("hogli_commands.ci_preflight.shutil.which", return_value="/usr/bin/hogli")
+ @patch("hogli_commands.ci_preflight.subprocess.run")
+ @patch("hogli_commands.ci_preflight._project_python_ready", return_value=True)
+ @patch(
+ "hogli_commands.ci_preflight.changed_files",
+ return_value=["frontend/src/taxonomy/core-filter-definitions-by-group.json"],
+ )
+ def test_present_project_env_verifies_without_writing(
+ self,
+ mock_changed: MagicMock,
+ mock_ready: MagicMock,
+ mock_run: MagicMock,
+ mock_which: MagicMock,
+ mock_fetch: MagicMock,
+ mock_stale: MagicMock,
+ mock_emit: MagicMock,
+ ) -> None:
+ mock_run.return_value = MagicMock(returncode=1, stdout="taxonomy json is out of date", stderr="")
+
+ result = runner.invoke(cli, ["ci:preflight", "--strict"])
+
+ # Without --check the verify command is the write path, which rewrites the JSON
+ # and exits 0, so a drifted push would report pass instead of blocking.
+ assert result.exit_code == 1
+ dispatched = [call.args[0] for call in mock_run.call_args_list]
+ assert ["hogli", "build:taxonomy-json", "--check"] in dispatched
+
+
class TestStalenessRisks:
@pytest.mark.parametrize(
"branch_files,master_files,conflicts,expected_fragments",