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.

feat(devex): ratchet apps.get_model references to product models (#87082)

Julian Bezec45fc4a2d0c
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.md
index aa0698786fc7..2b6f475ec137 100644
--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md
+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md
@@ -204,6 +204,12 @@ says nothing about what the consumer does with it. Two rules cover that:
function is what the move leaves behind, and the consumer keeps orchestration
and ids.
+`apps.get_model('label', 'Class')` is counted too, and for **every** product model,
+not only the allowance ones. It leaves no import edge, so tach cannot refuse it.
+Test modules stay out of scope, so the fixture escape hatch this skill recommends
+for core tests still works. Migrations stay out too: the historical registry is the
+only way a migration can reach a model. Production code may not add a call.
+
`hogli product:crossings <product>` lists a product's crossing classes with every
consumer use bucketed by kind, disallowed first. Disallowed uses are frozen in
`products/model_crossing_uses_baseline.txt` and guarded by a repo-invariant test;
@@ -255,7 +261,8 @@ records the decrease. See `products/architecture.md` § Wiring couplings.
under the branch.
- Core test fixtures that need product models: use `apps.get_model("<app_label>",
"Model")` at runtime plus a `TYPE_CHECKING` import for annotations — tach ignores
- type-only imports.
+ type-only imports. Fixtures only: the same call in production code is a
+ ratcheted `get_model` crossing (see above).
- Compatibility shims exist to bridge between serial PRs — the one-pass shape rarely
needs them. If one is unavoidable, it dies in the final cleanup PR, not "later".
- Exception: callers with subtle behavior (transaction boundaries, write-path
diff --git a/posthog/test/repo_invariants/test_model_crossing_uses.py b/posthog/test/repo_invariants/test_model_crossing_uses.py
index 56a09e4f2da6..420d7233f7d4 100644
--- a/posthog/test/repo_invariants/test_model_crossing_uses.py
+++ b/posthog/test/repo_invariants/test_model_crossing_uses.py
@@ -1,9 +1,13 @@
-"""Two-way ratchet on disallowed uses of watched-models crossing classes.
+"""Two-way ratchet on disallowed uses of product model classes.
A model class listed in MODEL_CROSSINGS may leave its product, but consumer code may only use it in
the instance-free shapes `hogli product:crossings` recognizes. Every other use is disallowed and
frozen here, so the count can fall but never rise.
+`apps.get_model` is frozen the same way, for every product model rather than only the listed ones:
+it resolves through the Django app registry, so no import linter can see the edge. Test modules stay
+out of scope, which keeps the pattern available to core test fixtures.
+
The check is strict equality, not "no worse than": a line that disappears must be deleted from the
file in the same change, so the file can never go stale behind the code.
@@ -28,9 +32,11 @@ def test_disallowed_crossing_uses_match_the_baseline() -> None:
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 crossing model class. Counts may only go down, so "
+ "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. Only a doctrine amendment in products/architecture.md "
+ "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. 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}"
diff --git a/products/architecture.md b/products/architecture.md
index 21c7982a9f81..0e1c5e722e0b 100644
--- a/products/architecture.md
+++ b/products/architecture.md
@@ -146,8 +146,16 @@ Move the code into the owning product.
The facade function is what the move leaves behind.
The consumer keeps the orchestration and the ids.
+**`apps.get_model` is ratcheted for every product model.**
+`apps.get_model('label', 'Class')` reaches a model through the Django app registry.
+It leaves no import edge, so tach and import-linter cannot see it.
+The scan therefore does not stop at the watched-models allowance on this channel: a reference from outside the owning product to any class on any product's model surface is counted as the disallowed kind `get_model`.
+Test modules stay out of scope, so a core test fixture may keep using the pattern.
+Migrations stay out of scope too: a migration reaches a model through the historical registry, and that is the only way a migration can.
+Production code may not add one.
+
**The ratchet.**
-`products/model_crossing_uses_baseline.txt` records every disallowed use still in the tree: one line for each crossing class, consumer module, kind, and count.
+`products/model_crossing_uses_baseline.txt` records every disallowed use still in the tree: one line for each model class, consumer module, kind, and count.
A repo-invariant test compares that file against a fresh scan, in both directions.
A count can go down.
A count must not go up.
@@ -156,13 +164,14 @@ 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.
**What the check cannot see.**
-The check reads uses of the class name.
-It does not read two things:
+The check reads uses of the class name, plus `get_model` string references.
+It does not read three things:
- attribute access on an instance the consumer already holds, inside a function body;
-- traversal of a foreign key that the consumer's own model declares.
+- traversal of a foreign key that the consumer's own model declares;
+- a `get_model` call whose app label or model name is a variable.
-Both are a declared residual, not permission to add more.
+All three are a declared residual, not permission to add more.
A behavioral class that fits no approved interface must not cross at all.
Wrap it in a facade function returning contracts, or register a plain function (see the managed-view provider registry in `products/data_modeling/backend/facade/managed_viewset_hooks.py`).
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 9689aab3da6e..e5e62e7fa5b8 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -1,11 +1,28 @@
-# Disallowed uses of watched-models crossing classes in consumer code.
+# 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.
#
+# Two channels land here. Name-level uses of a watched-models crossing class, in any kind the
+# doctrine does not call instance-free. And the kind `get_model`: an `apps.get_model` reference
+# from outside the owning product, which covers every product model, not only the allowance ones.
+# Test modules and migrations are out of scope on both channels: a migration reaches a model
+# through the historical registry, which is the only way a migration can.
+#
# 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
+canvas.Canvas products.tasks.backend.logic.services.loop_runs get_model 1
+data_modeling.DataWarehouseSavedQuery products.customer_analytics.backend.facade.api get_model 5
+error_tracking.ErrorTrackingIssue products.demo.backend.logic.products.hedgebox.matrix get_model 1
+error_tracking.ErrorTrackingIssue products.posthog_ai.evals.error_tracking.seeders get_model 1
+error_tracking.ErrorTrackingIssue products.reminders.backend.constants get_model 1
+error_tracking.ErrorTrackingIssueFingerprintV2 posthog.management.commands.fingerprint_embeddings_backfill get_model 1
+error_tracking.ErrorTrackingIssueFingerprintV2 posthog.management.commands.sync_exceptions_to_clickhouse get_model 1
+error_tracking.ErrorTrackingIssueFingerprintV2 posthog.models.team.util get_model 1
+error_tracking.ErrorTrackingIssueFingerprintV2 products.demo.backend.logic.products.hedgebox.matrix get_model 1
+error_tracking.ErrorTrackingIssueFingerprintV2 products.posthog_ai.evals.error_tracking.seeders get_model 1
+error_tracking.ErrorTrackingStackFrame products.demo.backend.logic.products.hedgebox.matrix get_model 1
product_analytics.Insight ee.api.subscription instance-many(filter) 2
product_analytics.Insight ee.api.subscription instance-many(manager) 2
product_analytics.Insight ee.hogai.artifacts.handlers.visualization instance-many(filter) 1
@@ -87,6 +104,10 @@ product_analytics.InsightVariable products.exports.backend.tasks.image_exporter
product_analytics.InsightViewed posthog.api.sharing write(update_or_create) 2
product_analytics.InsightViewed products.demo.backend.logic.products.hedgebox.matrix construct 1
product_analytics.InsightViewed products.demo.backend.logic.products.hedgebox.matrix write(bulk_create) 1
+surveys.Survey products.early_access_features.backend.management.commands.migrate_enrollments_to_waitlist_surveys get_model 1
+tasks.CodeInvite products.posthog_ai.eval_harness.harness.demo_data get_model 1
+tasks.CodeInviteRedemption products.posthog_ai.eval_harness.harness.demo_data get_model 1
+tasks.TaskRun products.review_hog.backend.receivers get_model 1
warehouse_sources.DataWarehouseCredential posthog.hogql.database.database instance-many(filter) 1
warehouse_sources.DataWarehouseCredential products.data_warehouse.backend.presentation.views.table drf-model-serializer 1
warehouse_sources.DataWarehouseCredential products.data_warehouse.backend.presentation.views.table write(create) 1
@@ -201,9 +222,6 @@ warehouse_sources.ExternalDataSource posthog.hogql.direct_connection instance-si
warehouse_sources.ExternalDataSource products.data_warehouse.backend.logic.managed_warehouse_data_status instance-many(filter) 1
warehouse_sources.ExternalDataSource products.data_warehouse.backend.management.commands.backfill_discovery_schedules instance-many(exclude) 1
warehouse_sources.ExternalDataSource products.data_warehouse.backend.management.commands.repair_qualified_schema_duplicates instance-many(filter) 1
-warehouse_sources.ExternalDataSource products.data_warehouse.backend.migrations.0020_migrate_github_job_inputs_to_auth_type get_model 2
-warehouse_sources.ExternalDataSource products.data_warehouse.backend.migrations.0041_migrate_stripe_job_inputs_to_auth_type get_model 2
-warehouse_sources.ExternalDataSource products.data_warehouse.backend.migrations.0046_fix_vitally_region_job_inputs get_model 1
warehouse_sources.ExternalDataSource products.data_warehouse.backend.models.revenue_analytics_config other(keyword) 1
warehouse_sources.ExternalDataSource products.data_warehouse.backend.models.revenue_analytics_config passed-as-class(OneToOneField) 1
warehouse_sources.ExternalDataSource products.data_warehouse.backend.presentation.views.data_warehouse instance-many(filter) 2
diff --git a/tools/hogli-commands/hogli_commands/product/ast_helpers.py b/tools/hogli-commands/hogli_commands/product/ast_helpers.py
index af6c72f4f7a2..6ddc2f4b8af8 100644
--- a/tools/hogli-commands/hogli_commands/product/ast_helpers.py
+++ b/tools/hogli-commands/hogli_commands/product/ast_helpers.py
@@ -47,12 +47,44 @@ def _file_imports_django_models(tree: ast.Module) -> bool:
return False
-def get_model_names(backend_dir: Path) -> list[str]:
- """Return names of Django ORM model subclasses in backend/models.py and/or backend/models/.
+# Base-name suffixes whose subclasses are value/manager helpers, never registered models.
+_NON_MODEL_BASE_SUFFIXES = ("Choices", "Enum", "Manager", "QuerySet")
+
+
+def _base_names(node: ast.ClassDef) -> list[str]:
+ names: list[str] = []
+ for base in node.bases:
+ if isinstance(base, ast.Name):
+ names.append(base.id)
+ elif isinstance(base, ast.Attribute):
+ names.append(base.attr)
+ return names
+
- Only counts classes whose base name ends with 'Model' (e.g. Model, UUIDTModel)
- and only in files that import from django.db, to avoid false positives from
- Pydantic BaseModel or similar.
+def _is_abstract_model(node: ast.ClassDef) -> bool:
+ for item in node.body:
+ if not (isinstance(item, ast.ClassDef) and item.name == "Meta"):
+ continue
+ for stmt in item.body:
+ if (
+ isinstance(stmt, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == "abstract" for t in stmt.targets)
+ and isinstance(stmt.value, ast.Constant)
+ and stmt.value.value is True
+ ):
+ return True
+ return False
+
+
+def get_model_names(backend_dir: Path) -> list[str]:
+ """Return names of Django ORM model classes in backend/models.py and/or backend/models/.
+
+ Counts every concrete module-level class with at least one base, in files that import
+ from django.db. Base-name matching cannot see that TeamScopedRootMixin or a meta-fields
+ mixin ultimately reaches models.Model, so this fails open: overcounting a helper class
+ is harmless (apps.get_model can never resolve it), while missing a model lets a
+ crossing bypass the ratchet. Excluded: abstract models (Meta.abstract = True) and
+ choices/enum/manager/queryset subclasses, which the app registry never returns.
"""
sources: list[Path] = []
models_file = backend_dir / "models.py"
@@ -69,19 +101,18 @@ def get_model_names(backend_dir: Path) -> list[str]:
continue
if not _file_imports_django_models(tree):
continue
- for node in ast.walk(tree):
- if isinstance(node, ast.ClassDef):
- for base in node.bases:
- base_name = (
- base.id
- if isinstance(base, ast.Name)
- else base.attr
- if isinstance(base, ast.Attribute)
- else None
- )
- if base_name and base_name.endswith("Model"):
- names.append(node.name)
- break
+ # Module level only: nested classes (Meta, TextChoices) are never registered models.
+ for node in tree.body:
+ if not isinstance(node, ast.ClassDef):
+ continue
+ bases = _base_names(node)
+ if not bases:
+ continue
+ if any(base.endswith(_NON_MODEL_BASE_SUFFIXES) for base in bases):
+ continue
+ if _is_abstract_model(node):
+ continue
+ names.append(node.name)
return names
diff --git a/tools/hogli-commands/hogli_commands/product/crossings.py b/tools/hogli-commands/hogli_commands/product/crossings.py
index c58150b533ed..5111698f14c7 100644
--- a/tools/hogli-commands/hogli_commands/product/crossings.py
+++ b/tools/hogli-commands/hogli_commands/product/crossings.py
@@ -12,8 +12,15 @@ the other side of that coupling: for each crossing class it resolves the concret
defined in, follows re-export chains so an import from any path counts, and buckets every name-level
use in consumer code by kind. `product:crossings` reports; the repo-invariant ratchet enforces.
+The name-level scan stays on the allowance classes, because an import of any other product model is
+already tach's to refuse. `apps.get_model('label', 'Class')` is the channel tach cannot refuse: it
+resolves through the Django app registry, leaves no import edge, and so reaches any product model
+from anywhere. That scan therefore runs over every model class a product registers, and each foreign
+reference is counted as the disallowed kind `get_model`.
+
Tests are out of scope. A test reaches concrete classes through testing doors on purpose, so counting
-its fixtures would measure the fixture, not the coupling.
+its fixtures would measure the fixture, not the coupling. `apps.get_model` is the escape hatch core
+test fixtures are told to use, and keeping tests out is what leaves that advice intact.
"""
from __future__ import annotations
@@ -27,6 +34,7 @@ from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from pathlib import Path
+from .ast_helpers import ast_parse_safe, get_model_names
from .isolation import MODEL_CROSSINGS, facade_model_crossings
from .paths import PRODUCTS_DIR, REPO_ROOT
@@ -157,9 +165,8 @@ def _model_modules(product: str) -> Iterator[Path]:
def _defining_module(product: str, class_name: str) -> str | None:
"""The dotted module whose top level defines `class_name`, searched across the model surface."""
for path in _model_modules(product):
- try:
- tree = ast.parse(path.read_text(encoding="utf-8", errors="ignore"))
- except (SyntaxError, OSError):
+ tree = ast_parse_safe(path)
+ if tree is None:
continue
if any(isinstance(node, ast.ClassDef) and node.name == class_name for node in tree.body):
return _dotted_module(path)
@@ -203,14 +210,31 @@ def _app_labels() -> dict[str, str]:
return labels
+def product_model_labels(products: Iterable[str] | None = None) -> dict[str, str]:
+ """`product.Class` -> owning product, for every model class a product's app registers.
+
+ Wider than `crossing_classes` on purpose. `apps.get_model('label', 'Class')` reaches a model
+ through the app registry, so neither tach nor import-linter sees the edge and the watched-models
+ allowance never had to name the class. The label scan therefore covers every product model, not
+ only the allowance ones. A product without an `apps.py` registers nothing and is skipped."""
+ registered = set(_app_labels().values())
+ wanted = registered if products is None else registered & set(products)
+ return {
+ f"{product}.{class_name}": product
+ for product in sorted(wanted)
+ for class_name in get_model_names(PRODUCTS_DIR / product / "backend")
+ }
+
+
# ---------------------------------------------------------------------------
# Candidate files
# ---------------------------------------------------------------------------
-def _is_test_module(path: Path) -> bool:
- """Tests reach concrete classes through testing doors, so they are not consumers."""
- if "test" in path.parts or "tests" in path.parts:
+def _is_out_of_scope_module(path: Path) -> bool:
+ """Tests reach concrete classes through testing doors, so they are not consumers. A migration
+ reaches a model through the historical registry, which is the only way a migration can."""
+ if "test" in path.parts or "tests" in path.parts or "migrations" in path.parts:
return True
return path.name.startswith("test_") or path.name.endswith("_test.py") or path.name == "conftest.py"
@@ -513,12 +537,9 @@ def classify_use(node: ast.expr, parents: dict[int, ast.AST]) -> str:
return f"other({type(parent).__name__})"
-def _get_model_uses(tree: ast.Module, product_by_label: dict[str, str], labels: set[str]) -> Counter[str]:
- """`apps.get_model('label', 'Class')`, its `'label.Class'` and keyword forms, which no import reveals.
-
- Django matches the model name case-insensitively, so the comparison does too."""
+def _get_model_uses(tree: ast.Module, product_by_label: dict[str, str], label_by_lower: dict[str, str]) -> Counter[str]:
+ """`apps.get_model('label', 'Class')`, its `'label.Class'` and keyword forms, which no import reveals."""
found: Counter[str] = Counter()
- label_by_lower = {label.lower(): label for label in labels}
for node in ast.walk(tree):
if not isinstance(node, ast.Call) or getattr(node.func, "attr", None) != "get_model":
continue
@@ -559,20 +580,27 @@ def _reads_class_off_module(source: bytes, aliases: dict[str, str], class_names:
def scan_crossing_uses(products: Iterable[str] | None = None) -> list[CrossingUse]:
- """Every use of every crossing class in consumer code, sorted, one entry per kind per module."""
+ """Every use of every crossing class in consumer code, sorted, one entry per kind per module.
+
+ Plus every `apps.get_model` reference to any product model from outside the owning product."""
+ # Consumed twice below; a generator argument would silently empty the second pass.
+ products = list(products) if products is not None else None
classes = crossing_classes(products)
- if not classes:
- return []
owning_dir = {c.label: PRODUCTS_DIR / c.product for c in classes}
+ owning_dir |= {label: PRODUCTS_DIR / product for label, product in product_model_labels(products).items()}
+ if not owning_dir:
+ return []
class_names = {c.class_name for c in classes}
candidates = _candidates()
origins = _origins(candidates, classes)
origin_modules = {export.module for export in origins}
product_by_label = _app_labels()
+ # Django resolves a model name case-insensitively, so the get_model scan matches on the lowered form.
+ label_by_lower = {label.lower(): label for label in owning_dir}
counts: dict[tuple[str, str, str], int] = defaultdict(int)
for candidate in candidates:
- if _is_test_module(candidate.path):
+ if _is_out_of_scope_module(candidate.path):
continue
names = _bound_names(candidate, origins)
aliases = {a.alias: a.module for a in candidate.imports.module_aliases if a.module in origin_modules}
@@ -596,7 +624,7 @@ def scan_crossing_uses(products: Iterable[str] | None = None) -> list[CrossingUs
continue
counts[(label, candidate.dotted, classify_use(node, parents))] += 1
if candidate.mentions_get_model:
- for label, count in _get_model_uses(tree, product_by_label, set(owning_dir)).items():
+ for label, count in _get_model_uses(tree, product_by_label, label_by_lower).items():
if not candidate.path.is_relative_to(owning_dir[label]):
counts[(label, candidate.dotted, "get_model")] += count
@@ -668,10 +696,16 @@ def render_report(uses: list[CrossingUse], class_labels: Iterable[str] = ()) ->
BASELINE_PATH = REPO_ROOT / "products" / "model_crossing_uses_baseline.txt"
BASELINE_HEADER = """\
-# Disallowed uses of watched-models crossing classes in consumer code.
+# 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.
#
+# Two channels land here. Name-level uses of a watched-models crossing class, in any kind the
+# doctrine does not call instance-free. And the kind `get_model`: an `apps.get_model` reference
+# from outside the owning product, which covers every product model, not only the allowance ones.
+# Test modules and migrations are out of scope on both channels: a migration reaches a model
+# through the historical registry, which is the only way a migration can.
+#
# 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.
#
diff --git a/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.py b/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.py
new file mode 100644
index 000000000000..6f5869e3a55e
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from hogli_commands.product.ast_helpers import get_model_names
+
+MODELS_SOURCE = """
+from django.db import models
+from posthog.models.scoping import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
+
+
+class Channel(TeamScopedRootMixin):
+ class ChannelType(models.TextChoices):
+ PUBLIC = "public", "Public"
+
+ name = models.TextField()
+
+
+class SyncConfig(CreatedMetaFields, UpdatedMetaFields):
+ team_id = models.BigIntegerField()
+
+
+class Widget(UUIDModel):
+ pass
+
+
+class AbstractBase(TeamScopedRootMixin, UUIDModel):
+ class Meta:
+ abstract = True
+
+
+class Flavor(models.TextChoices):
+ VANILLA = "vanilla", "Vanilla"
+
+
+class WidgetManager(models.Manager):
+ pass
+
+
+class PlainHelper:
+ pass
+"""
+
+NO_DJANGO_SOURCE = """
+from pydantic import BaseModel
+
+
+class Payload(BaseModel):
+ name: str
+"""
+
+
+class TestGetModelNames:
+ @pytest.mark.parametrize(
+ "name, expected",
+ [
+ ("Channel", True), # indirect base: TeamScopedRootMixin, no 'Model' suffix
+ ("SyncConfig", True), # meta-fields mixins only
+ ("Widget", True), # classic 'Model'-suffix base
+ ("AbstractBase", False), # Meta.abstract = True never comes out of the registry
+ ("Flavor", False), # module-level choices class
+ ("ChannelType", False), # nested choices class
+ ("WidgetManager", False), # manager helper
+ ("PlainHelper", False), # no bases
+ ],
+ )
+ def test_classification(self, tmp_path: Path, name: str, expected: bool) -> None:
+ backend = tmp_path / "backend"
+ backend.mkdir()
+ (backend / "models.py").write_text(MODELS_SOURCE)
+ assert (name in get_model_names(backend)) is expected
+
+ def test_ignores_files_without_django_imports(self, tmp_path: Path) -> None:
+ backend = tmp_path / "backend"
+ backend.mkdir()
+ (backend / "models.py").write_text(NO_DJANGO_SOURCE)
+ assert get_model_names(backend) == []
diff --git a/tools/hogli-commands/hogli_commands/tests/test_crossings.py b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
index 62a4c8748345..eca680a6d1b3 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_crossings.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
@@ -12,6 +12,7 @@ from hogli_commands.product import crossings
from hogli_commands.product.crossings import CrossingClass, classify_use, kind_is_allowed
ALERT = CrossingClass("alerts", "AlertConfiguration", "products.alerts.backend.models.alert")
+LOOKUP = {ALERT.label.lower(): ALERT.label}
def _candidate(source: str, dotted: str = "posthog.api.consumer") -> crossings._Candidate:
@@ -153,12 +154,44 @@ class TestGetModelStrings:
)
def test_every_string_form_is_counted(self, call: str) -> None:
tree = ast.parse(f"m = {call}")
- found = crossings._get_model_uses(tree, {"alerts": "alerts"}, {"alerts.AlertConfiguration"})
+ found = crossings._get_model_uses(tree, {"alerts": "alerts"}, LOOKUP)
assert found == {"alerts.AlertConfiguration": 1}
def test_unlisted_class_is_ignored(self) -> None:
tree = ast.parse("m = apps.get_model('alerts', 'AlertCheck')")
- assert crossings._get_model_uses(tree, {"alerts": "alerts"}, {"alerts.AlertConfiguration"}) == {}
+ assert crossings._get_model_uses(tree, {"alerts": "alerts"}, LOOKUP) == {}
+
+ def test_unknown_app_label_is_ignored(self) -> None:
+ tree = ast.parse("m = apps.get_model('posthog', 'AlertConfiguration')")
+ assert crossings._get_model_uses(tree, {"alerts": "alerts"}, LOOKUP) == {}
+
+
+class TestProductModelLabels:
+ @pytest.mark.parametrize(
+ "label,product",
+ [
+ # The first two are off MODEL_CROSSINGS, and cover the two model-surface shapes the
+ # scan has to walk: a models package, and a flat models.py.
+ ("alerts.AlertConfiguration", "alerts"),
+ ("error_tracking.ErrorTrackingIssue", "error_tracking"),
+ ("product_analytics.Insight", "product_analytics"),
+ ],
+ )
+ def test_model_surface_classes_resolve_to_their_product(self, label: str, product: str) -> None:
+ assert crossings.product_model_labels().get(label) == product
+
+ def test_products_filter_keeps_only_the_named_product(self) -> None:
+ labels = crossings.product_model_labels(["alerts"])
+ assert labels and set(labels.values()) == {"alerts"}
+
+ def test_baseline_never_records_a_products_own_get_model_calls(self) -> None:
+ own = []
+ for line in crossings.read_baseline():
+ crossing, consumer, kind, _ = line.split()
+ owner = crossing.split(".")[0]
+ if kind == "get_model" and consumer.startswith(f"products.{owner}."):
+ own.append(line)
+ assert own == []
class TestRenderReport: