: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): refuse new lines in the crossings baseline (#98133)
Julian Bez2eb7ffbab655
diff --git a/posthog/test/repo_invariants/test_model_crossing_uses.py b/posthog/test/repo_invariants/test_model_crossing_uses.pyindex 3fd0c5b2c2b4..ce8d86714bc3 100644--- a/posthog/test/repo_invariants/test_model_crossing_uses.py+++ b/posthog/test/repo_invariants/test_model_crossing_uses.py@@ -26,48 +26,36 @@ something outside the watched subtree, because the watch would then miss the codThe check is strict equality, not "no worse than": a line that disappears must be deleted from thefile in the same change, so the file can never go stale behind the code.-Regenerate after removing uses:+The two directions are not symmetric. A line that went away is regenerated out:bin/hogli product:crossings --all --write-baseline++That command refuses to write while the scan holds a line the file does not, so a new line is+never absorbed. Change the caller back, or seal the relation. A coupling that must stand is a+hand-edited line in the baseline plus an amendment in products/architecture.md § Wiring couplings,+which is what a reviewer reads."""from hogli_commands.product.crossings import (BASELINE_PATH,all_crossing_uses,- disallowed_uses,+ baseline_drift,+ baseline_drift_message,names_defined_in,read_baseline,+ scanned_baseline_lines,wiring_location_label,)-REGENERATE = "bin/hogli product:crossings --all --write-baseline"-def test_disallowed_crossing_uses_match_the_baseline() -> None:- scanned = sorted(use.as_baseline_line() for use in disallowed_uses(all_crossing_uses()))+ scanned = scanned_baseline_lines(all_crossing_uses())recorded = sorted(read_baseline())if scanned == recorded:return- added = [line for line in scanned if line not in recorded]- removed = [line for line in recorded if line not in scanned]- report = "\n".join([*(f" + {line}" for line in added), *(f" - {line}" for line in removed)])- raise AssertionError(- f"{BASELINE_PATH.name} no longer matches the repo.\n"- "A '+' line is a new disallowed use of a product model class. Counts may only go down, so "- "change the caller: move the query, serializer or write into the model's own product and "- "call a facade function instead. A 'get_model' line is an apps.get_model reference from "- "outside the owning product; it is a coupling the import linters cannot see, and it belongs "- "behind a facade function too. A 'reverse-accessor(...)' line is a boundary-crossing relation "- 'field without related_name="+" (a query:<name> row means an explicit related_query_name '- "keeps filter() traversal alive); seal it, remove the explicit query name, and give "- "callers a facade read function. "- "A 'drives(...)' line is a test outside the product that executes "- "one of its query runners; move that test into the product. Only a doctrine amendment in "- "products/architecture.md § Wiring couplings can add a line.\n"- f"A '-' line means a use went away — good, but the file must record that too. Run: {REGENERATE}\n"- f"{report}"- )+ drift = baseline_drift(recorded, scanned)+ raise AssertionError(baseline_drift_message(drift.grown, drift.shrunk))# product_analytics watches backend/hogql_queries/trends/ alone, because trends is the only subtreediff --git a/products/architecture.md b/products/architecture.mdindex ddc823058f7b..7f4502f5d965 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -180,6 +180,11 @@ A use that goes away must leave the file in the same change.Run `hogli product:crossings <product>` to see the uses of one product's classes.Run `hogli product:crossings --all --write-baseline` to record a decrease.+**The baseline only shrinks.**+`--write-baseline` refuses to write when the scan holds a line the file does not, prints those lines, and changes nothing, so a new coupling cannot enter by regenerating.+A coupling that must stand is a hand-edited line in the baseline plus a note here that says why it stands.+Both are in the diff, which is what a reviewer reads; a regenerated line is not.+**What the check cannot see.**The check reads uses of the class name, plus `get_model` string references.It does not read three things:@@ -536,7 +541,7 @@ Django auto-generates a reverse accessor (`project.visualreview_set`), a reverse**Rule:** declare every relation field (FK, O2O, M2M) that crosses a product boundary with `related_name="+"`, and do not set an explicit `related_query_name` on it. `related_name="+"` alone removes the reverse accessor and the reverse query name; an explicit `related_query_name` keeps `filter()` traversal alive, and the ratchet records it as a `query:<name>` row. A product may point relations _at_ core models; other products must not reference models _inside_ this product. When a caller needs reverse access, add a facade read function — do not traverse the ORM.-A repo invariant enforces this: every cross-boundary reverse accessor is frozen as a `reverse-accessor(...)` line in `products/model_crossing_uses_baseline.txt`, next to the other crossing kinds. The set may only shrink. A new relation without `related_name="+"` fails CI until you seal it or a review adds a baseline line. Regenerate with `bin/hogli product:crossings --all --write-baseline`.+A repo invariant enforces this: every cross-boundary reverse accessor is frozen as a `reverse-accessor(...)` line in `products/model_crossing_uses_baseline.txt`, next to the other crossing kinds. The set may only shrink. A new relation without `related_name="+"` fails CI until you seal it or a review adds a hand-edited baseline line. Regenerate after a removal with `bin/hogli product:crossings --all --write-baseline`.`db_constraint` is a separate concern: it is migration safety (see the hot-table FK rules in [products/README.md](README.md)) and multi-database planning, not Python isolation. Both `db_constraint=False` and a two-phase validated constraint are sanctioned.diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex e78be0ccd59e..71eed67112db 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -20,9 +20,11 @@# access gets a facade read function. See products/architecture.md § Cross-product foreign keys.## Counts may only go down, and a line that disappears must be deleted here too.-# A new line needs a doctrine amendment, not a baseline edit.#-# Regenerate: bin/hogli product:crossings --all --write-baseline+# Regenerate after a removal: bin/hogli product:crossings --all --write-baseline+# That command refuses to write when the scan holds a line this file does not. A coupling that+# must stand is a hand-edited line here, together with the amendment in products/architecture.md+# § Wiring couplings that permits it, because a reviewer can see both.access_control.Role approvals.ApprovalPolicy.bypass_roles reverse-accessor(bypass_policies) 1access_control.Role posthog.Organization.default_role reverse-accessor(default_for_organizations) 1actions.Action cdp.PluginConfig.match_action reverse-accessor(plugin_configs) 1diff --git a/tools/hogli-commands/hogli_commands/product/cli.py b/tools/hogli-commands/hogli_commands/product/cli.pyindex afe02e0d8f21..6d9540e5650f 100644--- a/tools/hogli-commands/hogli_commands/product/cli.py+++ b/tools/hogli-commands/hogli_commands/product/cli.py@@ -189,13 +189,18 @@ def cmd_isolate_move(name: str, views: tuple[str, ...], dry_run: bool) -> None:@click.argument("name", required=False)@click.option("--all", "scan_all", is_flag=True, help="Scan every product that holds crossing entries")@click.option("--json", "as_json", is_flag=True, help="Emit one JSON object per use instead of the report")[email protected]("--write-baseline", is_flag=True, help="Regenerate products/model_crossing_uses_baseline.txt")+ "--write-baseline",+ is_flag=True,+ help="Record removals in products/model_crossing_uses_baseline.txt; refuses to add a line",+)def cmd_crossings(name: str | None, scan_all: bool, as_json: bool, write_baseline: bool) -> None:import json as json_modulefrom dataclasses import asdictfrom .crossings import (BASELINE_PATH,+ BaselineWouldGrow,all_crossing_uses,crossing_classes,render_report,@@ -210,7 +215,10 @@ def cmd_crossings(name: str | None, scan_all: bool, as_json: bool, write_baselinproducts = None if scan_all else [name] if name else Noneuses = all_crossing_uses(products)if write_baseline:- write_baseline_file(uses)+ try:+ write_baseline_file(uses)+ except BaselineWouldGrow as refusal:+ raise click.ClickException(str(refusal)) from refusalclick.echo(f"Baseline written: {BASELINE_PATH}")returnif as_json:diff --git a/tools/hogli-commands/hogli_commands/product/crossings.py b/tools/hogli-commands/hogli_commands/product/crossings.pyindex 95c19fc19dd7..1d098099b323 100644--- a/tools/hogli-commands/hogli_commands/product/crossings.py+++ b/tools/hogli-commands/hogli_commands/product/crossings.py@@ -49,7 +49,7 @@ import textwrapimport warningsimport functoolsfrom collections import Counter, defaultdict-from collections.abc import Callable, Iterable, Iterator, Mapping+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequencefrom dataclasses import dataclassfrom pathlib import Path@@ -1684,7 +1684,23 @@ def render_report(uses: list[CrossingUse], class_labels: Iterable[str] = ()) ->BASELINE_PATH = REPO_ROOT / "products" / "model_crossing_uses_baseline.txt"-BASELINE_HEADER = """\+REGENERATE_COMMAND = "bin/hogli product:crossings --all --write-baseline"++NEW_LINE_INSTRUCTION = (+ "A '+' line is a new disallowed use of a product model class, and counts may only go down. "+ "Change the caller: move the query, serializer or write into the model's own product and call "+ "a facade function instead. A 'get_model' line is an apps.get_model reference from outside the "+ "owning product; it is a coupling the import linters cannot see, and it belongs behind a facade "+ "function too. A 'reverse-accessor(...)' line is a boundary-crossing relation field without "+ 'related_name="+" (a query:<name> row means an explicit related_query_name keeps filter() '+ "traversal alive); seal it, remove the explicit query name, and give callers a facade read "+ "function. A 'drives(...)' line is a test outside the product that executes one of its query "+ "runners; move that test into the product. A coupling that must stand is a doctrine amendment: "+ "hand-edit the line in, and record why in products/architecture.md § Wiring couplings. "+ "Regenerating the baseline cannot add a line."+)++BASELINE_HEADER = f"""\# Disallowed uses of product model classes in consumer code.# One line per (product.Class, consumer module, kind, count); see products/architecture.md# § Wiring couplings for which shapes are allowed.@@ -1707,21 +1723,104 @@ BASELINE_HEADER = """\# access gets a facade read function. See products/architecture.md § Cross-product foreign keys.## Counts may only go down, and a line that disappears must be deleted here too.-# A new line needs a doctrine amendment, not a baseline edit.#-# Regenerate: bin/hogli product:crossings --all --write-baseline+# Regenerate after a removal: {REGENERATE_COMMAND}+# That command refuses to write when the scan holds a line this file does not, or a count that+# went up. A coupling that+# must stand is a hand-edited line here, together with the amendment in products/architecture.md+# § Wiring couplings that permits it, because a reviewer can see both."""+def scanned_baseline_lines(uses: Iterable[CrossingUse]) -> list[str]:+ return sorted(use.as_baseline_line() for use in disallowed_uses(uses))++def render_baseline(uses: Iterable[CrossingUse]) -> str:- lines = sorted(use.as_baseline_line() for use in disallowed_uses(uses))- return BASELINE_HEADER + "\n".join(lines) + "\n"+ return BASELINE_HEADER + "\n".join(scanned_baseline_lines(uses)) + "\n"def read_baseline(path: Path = BASELINE_PATH) -> list[str]:return [line for line in path.read_text().splitlines() if line.strip() and not line.startswith("#")]+def _counts_by_identity(lines: Iterable[str]) -> dict[str, int]:+ counts: dict[str, int] = {}+ for line in lines:+ identity, count = line.rsplit(" ", 1)+ counts[identity] = int(count)+ return counts+++@dataclass(frozen=True)+class BaselineDrift:+ """The difference between the file and a scan, split by direction.++ A line is (crossing, consumer, kind, count), and only the count is allowed to move down.+ So `grown` holds a scanned line whose identity the file does not hold, or whose count went+ up; `shrunk` holds a recorded line whose identity the scan no longer holds, or whose count+ went down. Comparing whole lines would call a count drop growth and refuse it."""++ grown: list[str]+ shrunk: list[str]+++def baseline_drift(recorded: Iterable[str], scanned: Iterable[str]) -> BaselineDrift:+ recorded_counts = _counts_by_identity(recorded)+ scanned_counts = _counts_by_identity(scanned)+ grown = [+ f"{identity} {count}"+ for identity, count in sorted(scanned_counts.items())+ if count > recorded_counts.get(identity, 0)+ ]+ shrunk = [+ f"{identity} {count}"+ for identity, count in sorted(recorded_counts.items())+ if count > scanned_counts.get(identity, 0)+ ]+ return BaselineDrift(grown=grown, shrunk=shrunk)+++def baseline_drift_message(added: Sequence[str], removed: Sequence[str]) -> str:+ """The ratchet failure text, split by direction.++ The two directions are not symmetric. A removal is recorded by a regenerate, an addition is+ not, so the regenerate command stays out of the text while an addition stands. A reader who is+ handed that command answers a new coupling by absorbing it, which is how the file grew."""+ parts = [f"{BASELINE_PATH.name} no longer matches the repo."]+ if added:+ parts.append(NEW_LINE_INSTRUCTION)+ parts.extend(f" + {line}" for line in added)+ if removed:+ parts.append("A '-' line means a use went away. Good, but the file must record that too.")+ parts.extend(f" - {line}" for line in removed)+ if removed and added:+ parts.append(f"Run {REGENERATE_COMMAND} once the '+' lines are gone.")+ elif removed:+ parts.append(f"Run: {REGENERATE_COMMAND}")+ return "\n".join(parts)+++class BaselineWouldGrow(Exception):+ """A regenerate that would record a coupling the baseline does not hold yet."""++ def __init__(self, path: Path, added: Sequence[str]) -> None:+ self.added = list(added)+ lines = "\n".join(f" + {line}" for line in added)+ super().__init__(f"{path.name} would gain lines, so nothing was written.\n{NEW_LINE_INSTRUCTION}\n{lines}")++def write_baseline(uses: Iterable[CrossingUse], path: Path = BASELINE_PATH) -> None:- path.write_text(render_baseline(uses))+ """Record the scan, but only while every difference against the file is a removal.++ A regenerate that absorbs a new line hides the coupling from the review of the change that+ caused it. A deliberate coupling therefore goes in by hand, next to the doctrine note that+ permits it. There is no flag to skip this: a hand-edited line is what a reviewer reads, and a+ flag would be pasted from one change into the next."""+ scanned = list(uses)+ if path.exists():+ drift = baseline_drift(read_baseline(path), scanned_baseline_lines(scanned))+ if drift.grown:+ raise BaselineWouldGrow(path, drift.grown)+ path.write_text(render_baseline(scanned))_baseline_lines.cache_clear()diff --git a/tools/hogli-commands/hogli_commands/tests/test_crossings.py b/tools/hogli-commands/hogli_commands/tests/test_crossings.pyindex ae82fa507619..81faadba7335 100644--- a/tools/hogli-commands/hogli_commands/tests/test_crossings.py+++ b/tools/hogli-commands/hogli_commands/tests/test_crossings.py@@ -218,6 +218,69 @@ class TestProductModelLabels:assert own == []+class TestBaselineRatchet:+ LINE_A = "alerts.AlertConfiguration posthog.api.a instance-many(all) 1"+ LINE_B = "alerts.AlertConfiguration posthog.api.b instance-many(all) 1"++ @staticmethod+ def _use(consumer: str, count: int = 1) -> crossings.CrossingUse:+ return crossings.CrossingUse("alerts.AlertConfiguration", consumer, "instance-many(all)", count)++ def _recorded(self, tmp_path: Path, *consumers: str) -> Path:+ path = tmp_path / "baseline.txt"+ crossings.write_baseline([self._use(consumer) for consumer in consumers], path)+ return path++ def test_a_line_the_file_does_not_hold_is_refused(self, tmp_path: Path) -> None:+ path = self._recorded(tmp_path, "posthog.api.a")+ before = path.read_text()+ with pytest.raises(crossings.BaselineWouldGrow) as refusal:+ crossings.write_baseline([self._use("posthog.api.a"), self._use("posthog.api.b")], path)+ assert refusal.value.added == [self.LINE_B]+ assert self.LINE_B in str(refusal.value)+ assert path.read_text() == before++ @pytest.mark.parametrize(("recorded", "scanned", "written"), [(2, 1, True), (1, 2, False)])+ def test_a_count_may_only_go_down(self, tmp_path: Path, recorded: int, scanned: int, written: bool) -> None:+ path = tmp_path / "baseline.txt"+ crossings.write_baseline([self._use("posthog.api.a", recorded)], path)+ if written:+ crossings.write_baseline([self._use("posthog.api.a", scanned)], path)+ assert crossings.read_baseline(path) == [+ f"alerts.AlertConfiguration posthog.api.a instance-many(all) {scanned}"+ ]+ return+ with pytest.raises(crossings.BaselineWouldGrow) as refusal:+ crossings.write_baseline([self._use("posthog.api.a", scanned)], path)+ assert refusal.value.added == [f"alerts.AlertConfiguration posthog.api.a instance-many(all) {scanned}"]++ def test_a_removal_is_written(self, tmp_path: Path) -> None:+ path = self._recorded(tmp_path, "posthog.api.a", "posthog.api.b")+ crossings.write_baseline([self._use("posthog.api.a")], path)+ assert crossings.read_baseline(path) == [self.LINE_A]++ @parameterized.expand(+ [+ ("an addition alone", [LINE_B], [], False),+ ("a removal alone", [], [LINE_A], True),+ ("both directions", [LINE_B], [LINE_A], True),+ ]+ )+ def test_the_regenerate_command_appears_only_with_a_removal(+ self, _name: str, added: list[str], removed: list[str], has_command: bool+ ) -> None:+ message = crossings.baseline_drift_message(added, removed)+ assert (crossings.REGENERATE_COMMAND in message) is has_command+ for line in [*added, *removed]:+ assert line in message++ def test_both_directions_lead_with_the_caller_instruction(self) -> None:+ message = crossings.baseline_drift_message([self.LINE_B], [self.LINE_A])+ assert message.index(crossings.NEW_LINE_INSTRUCTION) < message.index(f" + {self.LINE_B}")+ assert message.index(f" + {self.LINE_B}") < message.index(f" - {self.LINE_A}")+ assert message.index(f" - {self.LINE_A}") < message.index(crossings.REGENERATE_COMMAND)++class TestRenderReport:def test_allowed_counts_sum_across_modules(self) -> None:uses = [