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): check and ratchet how consumers use model-crossing classes (#86646)

Julian Bezbc676dfdadec
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.md
index 5952a5891b9a..6353a57f622a 100644
--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md
+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md
@@ -188,6 +188,28 @@ base moved down to core, its timezone integration test moved into the product,
its Dagster assets gained a `facade/dags.py`, and its filter-preset reads landed
in `facade/api.py` with the viewset deferred.
+## Model classes a consumer already holds
+
+Some products still hand out model classes under the watched-models allowance
+(`MODEL_CROSSINGS`). That allowance only says the class may leave the product; it
+says nothing about what the consumer does with it. Two rules cover that:
+
+- **Default-deny.** A crossing class may appear in consumer code only in a shape
+ the check calls instance-free: an annotation, `X.DoesNotExist`, a nested class
+ attribute (`X.Status`), `X._meta`, a manager chain ending in
+ `values`/`values_list`/`count`/`exists`/`aggregate`, or a chain
+ embedded in `Exists(...)`/`Subquery(...)`. Anything else is disallowed.
+- **Move, don't permit.** Code that queries, serializes or writes a model belongs
+ in that model's product. The remedy for a disallowed use is a move; the facade
+ function is what the move leaves behind, and the consumer keeps orchestration
+ and ids.
+
+`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;
+counts may only go down, and `hogli product:crossings --all --write-baseline`
+records the decrease. See `products/architecture.md` § Wiring couplings.
+
## Guardrails
- Keep facades thin; put business rules behind the facade, in `logic/` by default. Other internal packages (`services/`, `reviewer/`, …) are fine as long as they stay behind the facade.
diff --git a/hogli.yaml b/hogli.yaml
index 1c60b05b6304..db47d7a08043 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -908,6 +908,9 @@ tools:
product:isolate:move:
click: hogli_commands.product.cli:cmd_isolate_move
description: Mechanical isolation moves with repo-wide path rewrites
+ product:crossings:
+ click: hogli_commands.product.cli:cmd_crossings
+ description: Report consumer uses of watched-models crossing classes by kind
product:lint:owners:
click: hogli_commands.product.cli:cmd_lint_owners
description: Validate product.yaml owners against PostHog/posthog GitHub teams
diff --git a/posthog/test/repo_invariants/test_model_crossing_uses.py b/posthog/test/repo_invariants/test_model_crossing_uses.py
new file mode 100644
index 000000000000..56a09e4f2da6
--- /dev/null
+++ b/posthog/test/repo_invariants/test_model_crossing_uses.py
@@ -0,0 +1,37 @@
+"""Two-way ratchet on disallowed uses of watched-models crossing 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.
+
+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.
+
+Regenerate after removing uses:
+
+ bin/hogli product:crossings --all --write-baseline
+"""
+
+from hogli_commands.product.crossings import BASELINE_PATH, disallowed_uses, read_baseline, scan_crossing_uses
+
+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(scan_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 crossing 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 "
+ "§ 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 ee382b35b283..2ab11330ce51 100644
--- a/products/architecture.md
+++ b/products/architecture.md
@@ -125,8 +125,45 @@ That is the same soundness contract wiring locations have; what it does not buy
The list lives in `MODEL_CROSSINGS` (`tools/hogli-commands/hogli_commands/product/isolation.py`) and is keyed `(product, class)`, like the carve-outs above: a class that is not listed is a leak and blocks narrowing, so a product already on the list cannot grow a new crossing without a doctrine change.
It only shrinks.
Adding an entry requires amending this section to name the class and why it cannot yet be a contract.
-The bar is that some consumer needs ORM semantics a contract cannot express — relation traversal, queryset-typed downstream APIs like access-control filtering, row locking, or model behavior.
-A consumer that only reads fields, or that ends in `values_list`, is disqualifying: the remedy there is a facade function returning contracts, not an entry here.
+**The consumer side is default-deny.**
+A crossing class may appear in consumer code only in a shape that `hogli product:crossings` identifies as instance-free.
+These shapes are allowed:
+
+- an annotation, on an argument, a return, or a variable;
+- `X.DoesNotExist`;
+- a nested class attribute, such as `X.Status` or `X.PrivilegeLevel`;
+- `X._meta`;
+- a manager chain that ends in `values()`, `values_list()`, `count()`, `exists()`, or `aggregate()`;
+- a manager chain that `Exists(...)` or `Subquery(...)` embeds.
+
+Every other use is disallowed.
+The check does not ask what the consumer intended.
+If the check does not identify a use as instance-free, change the caller.
+
+**Move the code, do not permit it.**
+Code that queries, serializes, or writes a model belongs in that model's product.
+A consumer that holds such code is misplaced code, not a coupling to document.
+Move the code into the owning product.
+The facade function is what the move leaves behind.
+The consumer keeps the orchestration and the ids.
+
+**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.
+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.
+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.
+
+**What the check cannot see.**
+The check reads uses of the class name.
+It does not read two 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.
+
+Both 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
new file mode 100644
index 000000000000..47cc200e388b
--- /dev/null
+++ b/products/model_crossing_uses_baseline.txt
@@ -0,0 +1,397 @@
+# Disallowed uses of watched-models crossing classes in consumer code.
+# One line per (product.Class, consumer module, kind, count); see products/architecture.md
+# § Wiring couplings for which shapes are allowed.
+#
+# 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
+alerts.AlertConfiguration ee.hogai.context.entity_search.context in-collection 1
+alerts.AlertConfiguration posthog.temporal.ai.anomaly_investigation.workflow instance-many(aget) 1
+alerts.AlertConfiguration posthog.temporal.alerts.activities instance-many(only) 1
+alerts.AlertConfiguration posthog.temporal.alerts.activities instance-single 2
+alerts.AlertConfiguration posthog.temporal.alerts.activities lock 3
+alerts.AlertConfiguration posthog.temporal.alerts.activities other(Attribute:interval_entitlement_error) 1
+alerts.AlertConfiguration products.dashboards.backend.api.dashboard prefetch 1
+alerts.AlertConfiguration products.product_analytics.backend.presentation.insight instance-many(filter) 1
+alerts.AlertConfiguration products.product_analytics.backend.presentation.insight prefetch 1
+alerts.AlertConfiguration products.pulse.backend.generation.persist instance-many(filter) 1
+alerts.AlertConfiguration products.pulse.backend.generation.persist other(BinOp) 1
+alerts.AlertConfiguration products.pulse.backend.sources.resource_health instance-many(order_by) 1
+alerts.AlertConfiguration products.signals.backend.scout_harness.profile.builders instance-many(filter) 1
+alerts.AlertSubscription posthog.models.organization write(delete) 1
+cohorts.Cohort ee.benchmarks.benchmarks instance-single 1
+cohorts.Cohort ee.benchmarks.benchmarks write(create) 1
+cohorts.Cohort ee.hogai.context.entity_search.context in-collection 1
+cohorts.Cohort posthog.admin.admins.cohort_admin passed-as-class(register) 1
+cohorts.Cohort posthog.api.cohort construct 1
+cohorts.Cohort posthog.api.cohort drf-model-serializer 2
+cohorts.Cohort posthog.api.cohort in-collection 2
+cohorts.Cohort posthog.api.cohort instance-many(all) 1
+cohorts.Cohort posthog.api.cohort instance-many(filter) 1
+cohorts.Cohort posthog.api.cohort instance-many(order_by) 1
+cohorts.Cohort posthog.api.cohort instance-many(to_dict) 1
+cohorts.Cohort posthog.api.cohort instance-single 4
+cohorts.Cohort posthog.api.cohort passed-as-class(cast) 4
+cohorts.Cohort posthog.api.cohort write(create) 1
+cohorts.Cohort posthog.api.person instance-many(filter) 1
+cohorts.Cohort posthog.api.search in-collection 1
+cohorts.Cohort posthog.cdp.filters instance-single 1
+cohorts.Cohort posthog.dags.backfill_internal_test_users_cohort construct 1
+cohorts.Cohort posthog.dags.backfill_internal_test_users_cohort other(Attribute:compute_condition_type) 1
+cohorts.Cohort posthog.dags.backfill_internal_test_users_cohort write(bulk_create) 1
+cohorts.Cohort posthog.hogql.functions.cohort instance-single 1
+cohorts.Cohort posthog.hogql.property instance-single 1
+cohorts.Cohort posthog.hogql_queries.hogql_cohort_query instance-single 2
+cohorts.Cohort posthog.hogql_queries.insights.funnels.base instance-many(filter) 2
+cohorts.Cohort posthog.hogql_queries.insights.funnels.utils instance-many(name) 1
+cohorts.Cohort posthog.hogql_queries.insights.trends.trends_query_runner instance-many(name) 2
+cohorts.Cohort posthog.management.commands.calculate_cohort instance-single 1
+cohorts.Cohort posthog.management.commands.resave_cohorts instance-many(order_by) 1
+cohorts.Cohort posthog.management.commands.resave_cohorts other(Attribute:compute_condition_type) 1
+cohorts.Cohort posthog.management.commands.survey_cohort_bytecode_stl instance-many(filter) 1
+cohorts.Cohort posthog.middleware instance-many(filter) 1
+cohorts.Cohort posthog.models.file_system.unfiled_file_saver in-collection 1
+cohorts.Cohort posthog.models.filters.mixins.simplify instance-single 1
+cohorts.Cohort posthog.models.property.util instance-single 2
+cohorts.Cohort posthog.models.resource_transfer.visitors.cohort other(Return) 1
+cohorts.Cohort posthog.models.resource_transfer.visitors.cohort passed-as-class(build_edges_for_ids) 1
+cohorts.Cohort posthog.models.resource_transfer.visitors.experiment passed-as-class(build_edges_for_ids) 1
+cohorts.Cohort posthog.models.resource_transfer.visitors.experiment_holdout passed-as-class(build_edges_for_ids) 1
+cohorts.Cohort posthog.models.resource_transfer.visitors.experiment_saved_metric passed-as-class(build_edges_for_ids) 1
+cohorts.Cohort posthog.models.resource_transfer.visitors.feature_flag passed-as-class(build_edges_for_ids) 1
+cohorts.Cohort posthog.models.resource_transfer.visitors.insight passed-as-class(build_edges_for_ids) 1
+cohorts.Cohort posthog.models.resource_transfer.visitors.survey passed-as-class(build_edges_for_ids) 1
+cohorts.Cohort posthog.queries.person_query instance-single 1
+cohorts.Cohort posthog.session_recordings.queries.sub_queries.cohort_subquery instance-single 1
+cohorts.Cohort posthog.tasks.calculate_cohort instance-many(exclude) 3
+cohorts.Cohort posthog.tasks.calculate_cohort instance-many(filter) 1
+cohorts.Cohort posthog.tasks.calculate_cohort instance-single 6
+cohorts.Cohort posthog.tasks.calculate_cohort write(update) 1
+cohorts.Cohort products.actions.backend.api.action instance-many(extra) 1
+cohorts.Cohort products.cdp.backend.tasks.hog_functions instance-single 1
+cohorts.Cohort products.demo.backend.logic.matrix.manager instance-many(filter) 1
+cohorts.Cohort products.demo.backend.logic.products.hedgebox.matrix write(create) 1
+cohorts.Cohort products.demo.backend.logic.products.spikegpt.matrix write(create) 1
+cohorts.Cohort products.error_tracking.backend.logic.issue_mutations instance-single 1
+cohorts.Cohort products.experiments.backend.admin.experiment_admin instance-many(filter) 1
+cohorts.Cohort products.experiments.backend.experiment_service instance-many(filter) 1
+cohorts.Cohort products.experiments.backend.experiment_service write(create) 1
+cohorts.Cohort products.feature_flags.backend.api.feature_flag instance-many(filter) 1
+cohorts.Cohort products.feature_flags.backend.api.feature_flag instance-single 1
+cohorts.Cohort products.feature_flags.backend.api.feature_flag prefetch 1
+cohorts.Cohort products.feature_flags.backend.api.organization_feature_flag instance-single 2
+cohorts.Cohort products.feature_flags.backend.flag_version_sync instance-many(filter) 1
+cohorts.Cohort products.feature_flags.backend.flag_version_sync instance-many(manager) 1
+cohorts.Cohort products.feature_flags.backend.flag_version_sync other(keyword) 2
+cohorts.Cohort products.feature_flags.backend.flags_cache instance-many(filter) 1
+cohorts.Cohort products.feature_flags.backend.flags_cache other(keyword) 2
+cohorts.Cohort products.feature_flags.backend.local_evaluation instance-many(select_related) 1
+cohorts.Cohort products.feature_flags.backend.local_evaluation other(keyword) 2
+cohorts.Cohort products.feature_flags.backend.models.feature_flag instance-single 1
+cohorts.Cohort products.replay_vision.backend.impact write(create) 1
+cohorts.Cohort products.signals.backend.scout_harness.profile.builders instance-many(filter) 1
+cohorts.Cohort products.workflows.backend.api.hog_flow instance-single 1
+dashboards.Dashboard ee.api.dashboard_collaborator instance-single 2
+dashboards.Dashboard ee.api.dashboard_collaborator passed-as-class(cast) 1
+dashboards.Dashboard ee.api.subscription instance-many(manager) 2
+dashboards.Dashboard ee.api.subscription instance-single 1
+dashboards.Dashboard ee.hogai.context.entity_search.context in-collection 1
+dashboards.Dashboard ee.hogai.eval.ci.max_tools.eval_upsert_dashboard instance-many(filter) 1
+dashboards.Dashboard ee.hogai.eval.ci.max_tools.eval_upsert_dashboard write(acreate) 1
+dashboards.Dashboard ee.hogai.tools.read_data.tool instance-many(aget) 1
+dashboards.Dashboard ee.hogai.tools.upsert_dashboard.tool instance-many(aget) 1
+dashboards.Dashboard ee.hogai.tools.upsert_dashboard.tool write(create) 1
+dashboards.Dashboard posthog.api.search in-collection 1
+dashboards.Dashboard posthog.api.search instance-many(none) 1
+dashboards.Dashboard posthog.api.sharing instance-single 1
+dashboards.Dashboard posthog.api.sharing passed-as-class(cast) 1
+dashboards.Dashboard posthog.api.sharing_publish_gate isinstance 1
+dashboards.Dashboard posthog.api.welcome instance-many(filter) 1
+dashboards.Dashboard posthog.helpers.dashboard_templates write(create) 2
+dashboards.Dashboard posthog.middleware instance-many(filter) 1
+dashboards.Dashboard posthog.models.activity_logging.activity_log isinstance 1
+dashboards.Dashboard posthog.models.file_system.unfiled_file_saver in-collection 1
+dashboards.Dashboard posthog.models.product_intent.product_intent instance-many(filter) 1
+dashboards.Dashboard posthog.models.resource_transfer.visitors.dashboard other(Return) 1
+dashboards.Dashboard posthog.models.team.team write(create) 1
+dashboards.Dashboard posthog.rbac.migrations.rbac_dashboard_migration instance-many(filter) 1
+dashboards.Dashboard posthog.tasks.usage_report instance-many(order_by) 4
+dashboards.Dashboard posthog.temporal.usage_report.queries instance-many(order_by) 4
+dashboards.Dashboard posthog.user_permissions instance-many(filter) 2
+dashboards.Dashboard products.demo.backend.logic.legacy.app_data_generator write(create) 1
+dashboards.Dashboard products.demo.backend.logic.legacy.insight_variables_data_generator write(create) 1
+dashboards.Dashboard products.demo.backend.logic.legacy.revenue_data_generator write(create) 1
+dashboards.Dashboard products.demo.backend.logic.legacy.web_data_generator write(create) 1
+dashboards.Dashboard products.demo.backend.logic.products.hedgebox.matrix write(create) 3
+dashboards.Dashboard products.feature_flags.backend.api.feature_flag drf-field-queryset 1
+dashboards.Dashboard products.feature_flags.backend.api.feature_flag instance-single 1
+dashboards.Dashboard products.feature_flags.backend.api.feature_flag write(create) 1
+dashboards.Dashboard products.feature_flags.backend.management.commands.delete_feature_flag_usage_insights instance-many(filter) 1
+dashboards.Dashboard products.posthog_ai.eval_harness.data_setup write(create) 1
+dashboards.Dashboard products.product_analytics.backend.presentation.insight drf-field-queryset 1
+dashboards.Dashboard products.product_analytics.backend.presentation.insight instance-many(filter) 3
+dashboards.Dashboard products.pulse.backend.api.brief instance-many(filter) 1
+dashboards.Dashboard products.pulse.backend.generation.persist in-collection 1
+dashboards.Dashboard products.pulse.backend.generation.persist other(BinOp) 1
+dashboards.Dashboard products.pulse.backend.sources.anchored_dashboards instance-many(filter) 2
+dashboards.Dashboard products.reminders.backend.constants in-collection 1
+dashboards.Dashboard products.signals.backend.scout_harness.profile.builders instance-many(order_by) 1
+dashboards.Dashboard products.slack_app.backend.slack_link_unfurl instance-single 1
+dashboards.DashboardTile ee.api.subscription instance-many(manager) 2
+dashboards.DashboardTile ee.hogai.eval.ci.max_tools.eval_upsert_dashboard write(acreate) 1
+dashboards.DashboardTile ee.hogai.tools.upsert_dashboard.tool construct 1
+dashboards.DashboardTile ee.hogai.tools.upsert_dashboard.tool instance-many(select_related) 2
+dashboards.DashboardTile ee.hogai.tools.upsert_dashboard.tool other(Attribute:sort_tiles_by_layout) 1
+dashboards.DashboardTile ee.hogai.tools.upsert_dashboard.tool write(bulk_create) 1
+dashboards.DashboardTile ee.hogai.tools.upsert_dashboard.tool write(create) 1
+dashboards.DashboardTile ee.hogai.tools.upsert_dashboard.tool write(update) 2
+dashboards.DashboardTile posthog.caching.calculate_results isinstance 1
+dashboards.DashboardTile posthog.helpers.dashboard_templates write(create) 5
+dashboards.DashboardTile posthog.models.activity_logging.activity_log isinstance 1
+dashboards.DashboardTile posthog.models.resource_transfer.visitors.dashboard_tile other(Return) 1
+dashboards.DashboardTile products.demo.backend.logic.legacy.app_data_generator write(create) 1
+dashboards.DashboardTile products.demo.backend.logic.legacy.insight_variables_data_generator write(create) 5
+dashboards.DashboardTile products.demo.backend.logic.legacy.revenue_data_generator write(create) 1
+dashboards.DashboardTile products.demo.backend.logic.legacy.web_data_generator write(create) 1
+dashboards.DashboardTile products.demo.backend.logic.products.hedgebox.matrix write(create) 10
+dashboards.DashboardTile products.exports.backend.tasks.image_exporter instance-single 1
+dashboards.DashboardTile products.feature_flags.backend.management.commands.delete_feature_flag_usage_insights instance-many(filter) 1
+dashboards.DashboardTile products.feature_flags.backend.management.commands.delete_feature_flag_usage_insights write(update) 1
+dashboards.DashboardTile products.posthog_ai.eval_harness.data_setup write(create) 3
+dashboards.DashboardTile products.product_analytics.backend.admin write(update) 1
+dashboards.DashboardTile products.product_analytics.backend.migrations.0004_delete_revenue_analytics_insights get_model 1
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight drf-model-serializer 1
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight instance-many(all) 1
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight instance-many(exclude) 1
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight instance-many(filter) 2
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight instance-many(select_related) 1
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight instance-single 1
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight other(Attribute:dashboard_queryset) 1
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight prefetch 2
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight write(create) 1
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight write(get_or_create) 1
+dashboards.DashboardTile products.product_analytics.backend.presentation.insight write(update) 4
+dashboards.Text posthog.helpers.dashboard_templates write(create) 1
+dashboards.Text posthog.models.resource_transfer.visitors.text other(Return) 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
+product_analytics.Insight ee.hogai.artifacts.types in-collection 1
+product_analytics.Insight ee.hogai.chat_agent.insights.nodes instance-many(order_by) 1
+product_analytics.Insight ee.hogai.context.entity_search.context in-collection 1
+product_analytics.Insight ee.hogai.context.entity_search.context instance-many(order_by) 1
+product_analytics.Insight ee.hogai.eval.ci.max_tools.eval_upsert_dashboard write(acreate) 1
+product_analytics.Insight ee.hogai.tools.upsert_dashboard.tool construct 1
+product_analytics.Insight posthog.api.cohort instance-many(order_by) 1
+product_analytics.Insight posthog.api.search in-collection 1
+product_analytics.Insight posthog.api.sharing instance-many(filter) 1
+product_analytics.Insight posthog.api.sharing instance-single 1
+product_analytics.Insight posthog.api.sharing_publish_gate isinstance 1
+product_analytics.Insight posthog.caching.calculate_results isinstance 1
+product_analytics.Insight posthog.caching.warming instance-single 1
+product_analytics.Insight posthog.helpers.dashboard_templates write(create) 2
+product_analytics.Insight posthog.management.commands.backfill_insights_query_metadata instance-many(filter) 1
+product_analytics.Insight posthog.management.commands.backfill_insights_query_metadata write(bulk_update) 1
+product_analytics.Insight posthog.management.commands.migrate_retention_show_mean instance-many(filter) 1
+product_analytics.Insight posthog.middleware instance-many(filter) 1
+product_analytics.Insight posthog.models.file_system.unfiled_file_saver in-collection 1
+product_analytics.Insight posthog.models.product_intent.product_intent instance-many(filter) 2
+product_analytics.Insight posthog.models.resource_transfer.visitors.insight other(Return) 1
+product_analytics.Insight posthog.models.sharing_configuration passed-as-class(cast) 1
+product_analytics.Insight posthog.temporal.product_analytics.upgrade_queries_activities instance-many(filter) 1
+product_analytics.Insight products.actions.backend.api.action instance-many(extra) 1
+product_analytics.Insight products.alerts.backend.max_tools instance-many(filter) 1
+product_analytics.Insight products.alerts.backend.max_tools passed-as-class(cast) 1
+product_analytics.Insight products.alerts.backend.max_tools write(create) 1
+product_analytics.Insight products.alerts.backend.presentation.views.alert drf-field-queryset 2
+product_analytics.Insight products.alerts.backend.presentation.views.alert instance-many(filter) 1
+product_analytics.Insight products.annotations.backend.api.annotation drf-field-queryset 1
+product_analytics.Insight products.dashboards.backend.api.dashboard drf-model-serializer 1
+product_analytics.Insight products.dashboards.backend.api.dashboard instance-many(distinct) 1
+product_analytics.Insight products.dashboards.backend.api.dashboard instance-many(select_related) 1
+product_analytics.Insight products.dashboards.backend.api.dashboard passed-as-class(cast) 1
+product_analytics.Insight products.dashboards.backend.api.dashboard write(bulk_update) 1
+product_analytics.Insight products.dashboards.backend.api.dashboard write(update) 1
+product_analytics.Insight products.data_catalog.backend.logic.drift instance-many(filter) 1
+product_analytics.Insight products.data_catalog.backend.logic.drift instance-many(manager) 2
+product_analytics.Insight products.data_catalog.evals.seeders write(create) 3
+product_analytics.Insight products.data_catalog.evals.seeders write(update) 1
+product_analytics.Insight products.demo.backend.logic.legacy.app_data_generator write(create) 1
+product_analytics.Insight products.demo.backend.logic.legacy.insight_variables_data_generator write(create) 5
+product_analytics.Insight products.demo.backend.logic.legacy.revenue_data_generator write(create) 1
+product_analytics.Insight products.demo.backend.logic.legacy.web_data_generator write(create) 1
+product_analytics.Insight products.demo.backend.logic.products.hedgebox.matrix instance-many(filter) 1
+product_analytics.Insight products.demo.backend.logic.products.hedgebox.matrix write(create) 13
+product_analytics.Insight products.exports.backend.api.exports instance-single 1
+product_analytics.Insight products.exports.backend.facade.api instance-single 1
+product_analytics.Insight products.exports.backend.temporal.subscriptions.snapshot_activities instance-many(only) 1
+product_analytics.Insight products.feature_flags.backend.management.commands.delete_feature_flag_usage_insights instance-many(filter) 2
+product_analytics.Insight products.feature_flags.backend.management.commands.delete_feature_flag_usage_insights write(update) 1
+product_analytics.Insight products.posthog_ai.eval_harness.data_setup write(create) 4
+product_analytics.Insight products.posthog_ai.eval_harness.seeders.insight construct 1
+product_analytics.Insight products.posthog_ai.eval_harness.seeders.insight write(bulk_create) 1
+product_analytics.Insight products.posthog_ai.eval_harness.seeders.insight write(create) 1
+product_analytics.Insight products.pulse.backend.api.brief instance-many(filter) 1
+product_analytics.Insight products.pulse.backend.generation.persist instance-many(filter) 1
+product_analytics.Insight products.pulse.backend.generation.persist other(BinOp) 1
+product_analytics.Insight products.pulse.backend.sources.anchored_dashboards instance-many(distinct) 1
+product_analytics.Insight products.pulse.backend.sources.anchored_dashboards instance-many(none) 1
+product_analytics.Insight products.pulse.backend.sources.anchored_insights instance-many(distinct) 1
+product_analytics.Insight products.pulse.backend.sources.anchored_insights instance-many(none) 1
+product_analytics.Insight products.pulse.backend.sources.resource_health instance-many(filter) 2
+product_analytics.Insight products.reminders.backend.constants in-collection 1
+product_analytics.Insight products.slack_app.backend.slack_link_unfurl instance-single 1
+product_analytics.Insight products.surveys.backend.api.survey instance-single 1
+product_analytics.InsightVariable ee.hogai.chat_agent.sql.mixins instance-many(filter) 1
+product_analytics.InsightVariable posthog.api.sharing instance-many(all) 1
+product_analytics.InsightVariable posthog.api.sharing instance-many(filter) 1
+product_analytics.InsightVariable posthog.hogql.autocomplete instance-many(order_by) 2
+product_analytics.InsightVariable posthog.hogql.variables instance-many(all) 1
+product_analytics.InsightVariable products.dashboards.backend.api.dashboard instance-many(all) 1
+product_analytics.InsightVariable products.demo.backend.logic.legacy.insight_variables_data_generator write(create) 4
+product_analytics.InsightVariable products.endpoints.backend.logic.validation instance-many(filter) 2
+product_analytics.InsightVariable products.exports.backend.tasks.image_exporter instance-many(all) 2
+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
+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
+warehouse_sources.DataWarehouseCredential products.posthog_ai.evals.data_warehouse.seeder write(create) 1
+warehouse_sources.DataWarehouseTable ee.hogai.eval.offline.snapshot_loader write(abulk_create) 1
+warehouse_sources.DataWarehouseTable ee.hogai.eval.schema construct 1
+warehouse_sources.DataWarehouseTable ee.hogai.eval.schema in-collection 1
+warehouse_sources.DataWarehouseTable ee.hogai.eval.schema instance-many(iterator) 1
+warehouse_sources.DataWarehouseTable ee.hogai.tools.execute_sql.direct_connection_suggestions instance-many(filter) 1
+warehouse_sources.DataWarehouseTable ee.hogai.tools.read_data.tool instance-many(filter) 1
+warehouse_sources.DataWarehouseTable posthog.hogql.database.database instance-many(order_by) 2
+warehouse_sources.DataWarehouseTable posthog.hogql.direct_connection instance-many(filter) 1
+warehouse_sources.DataWarehouseTable posthog.hogql_queries.access_controlled_resources instance-many(only) 1
+warehouse_sources.DataWarehouseTable posthog.tasks.usage_report instance-many(annotate) 2
+warehouse_sources.DataWarehouseTable posthog.temporal.data_modeling.run_workflow instance-single 2
+warehouse_sources.DataWarehouseTable products.data_catalog.backend.logic.certifications instance-many(filter) 1
+warehouse_sources.DataWarehouseTable products.data_catalog.evals.seeders instance-many(filter) 1
+warehouse_sources.DataWarehouseTable products.data_catalog.evals.seeders write(create) 1
+warehouse_sources.DataWarehouseTable products.data_modeling.backend.logic.node_frequency instance-many(exclude) 1
+warehouse_sources.DataWarehouseTable products.data_modeling.backend.logic.saved_query_dag_sync instance-single 2
+warehouse_sources.DataWarehouseTable products.data_modeling.backend.management.commands.cleanup_orphaned_matview_tables instance-many(filter) 1
+warehouse_sources.DataWarehouseTable products.data_modeling.backend.models.modeling instance-single 4
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_clickhouse write(create) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_motherduck write(create) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_mysql write(create) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_postgres write(create) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_redshift write(create) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_snowflake write(create) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.logic.data_load.create_table instance-single 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.logic.data_load.create_table write(create) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.column_annotation drf-field-queryset 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.column_annotation other(Assign) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.saved_query instance-many(exclude) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.table construct 2
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.table drf-model-serializer 2
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.table instance-many(all) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.table instance-many(filter) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.table write(create) 1
+warehouse_sources.DataWarehouseTable products.demo.backend.logic.products.hedgebox.matrix instance-single 1
+warehouse_sources.DataWarehouseTable products.demo.backend.logic.products.hedgebox.matrix write(create) 1
+warehouse_sources.DataWarehouseTable products.engineering_analytics.backend.management.commands.seed_engineering_analytics instance-single 1
+warehouse_sources.DataWarehouseTable products.engineering_analytics.backend.management.commands.seed_engineering_analytics write(create) 1
+warehouse_sources.DataWarehouseTable products.managed_warehouse.backend.logic.connection write(update) 2
+warehouse_sources.DataWarehouseTable products.managed_warehouse.backend.table_binding instance-many(prefetch_related) 1
+warehouse_sources.DataWarehouseTable products.marketing_analytics.backend.api instance-single 1
+warehouse_sources.DataWarehouseTable products.marketing_analytics.backend.demo.warehouse instance-many(select_related) 1
+warehouse_sources.DataWarehouseTable products.marketing_analytics.backend.demo.warehouse instance-single 1
+warehouse_sources.DataWarehouseTable products.marketing_analytics.backend.hogql_queries.adapters.factory instance-many(prefetch_related) 1
+warehouse_sources.DataWarehouseTable products.marketing_analytics.backend.management.commands.generate_marketing_demo_data instance-single 1
+warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder construct 1
+warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(bulk_create) 1
+warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(create) 1
+warehouse_sources.ExternalDataJob posthog.hogql.database.database prefetch 1
+warehouse_sources.ExternalDataJob posthog.tasks.usage_report instance-many(annotate) 4
+warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.data_load.source_templates instance-single 2
+warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.external_data_source.jobs lock 1
+warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.external_data_source.notifications instance-many(filter) 2
+warehouse_sources.ExternalDataJob products.data_warehouse.backend.presentation.views.data_warehouse instance-many(filter) 2
+warehouse_sources.ExternalDataJob products.marketing_analytics.backend.demo.health write(create) 1
+warehouse_sources.ExternalDataJob products.marketing_analytics.backend.demo.health write(update) 1
+warehouse_sources.ExternalDataJob products.marketing_analytics.backend.services.data_source_health instance-single 2
+warehouse_sources.ExternalDataSchema ee.hogai.tools.execute_sql.direct_connection_suggestions instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema ee.hogai.tools.read_data.tool instance-many(filter) 1
+warehouse_sources.ExternalDataSchema posthog.hogql.database.database in-collection 1
+warehouse_sources.ExternalDataSchema posthog.hogql.database.database instance-many(filter) 2
+warehouse_sources.ExternalDataSchema posthog.tasks.usage_report instance-many(annotate) 1
+warehouse_sources.ExternalDataSchema products.customer_analytics.backend.facade.api get_model 4
+warehouse_sources.ExternalDataSchema products.data_modeling.backend.logic.node_frequency instance-many(exclude) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.clickhouse_helpers instance-many(exclude) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.clickhouse_helpers instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.direct_virtual_tables instance-many(order_by) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.logic.data_load.service instance-many(exclude) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.logic.external_data_source.jobs lock 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.logic.external_data_source.notifications instance-many(distinct) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.logic.external_data_source.notifications instance-many(order_by) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.logic.external_data_source.notifications write(update) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.logic.managed_warehouse_data_status instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.management.commands.backfill_cdc_extraction_schedules instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.management.commands.migrate_sub_5min_sync_frequencies instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.management.commands.repair_qualified_schema_duplicates instance-many(exclude) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.management.commands.update_data_import_schedules instance-many(filter) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.motherduck_helpers instance-many(select_related) 2
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.mysql_helpers instance-many(exclude) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.mysql_helpers instance-many(filter) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.postgres_helpers instance-many(exclude) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.postgres_helpers instance-many(filter) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.postgres_helpers instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.presentation.views.data_warehouse instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.redshift_helpers instance-many(select_related) 2
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.snowflake_helpers instance-many(exclude) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.snowflake_helpers instance-many(filter) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.sql_warehouse_migration instance-many(filter) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.sql_warehouse_migration instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.sync_status in-collection 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.sync_status instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.temporal.health_checks.external_data_failure instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.engineering_analytics.backend.logic.sources instance-many(select_related) 1
+warehouse_sources.ExternalDataSchema products.engineering_analytics.backend.management.commands.seed_engineering_analytics instance-single 1
+warehouse_sources.ExternalDataSchema products.engineering_analytics.backend.management.commands.seed_engineering_analytics write(create) 1
+warehouse_sources.ExternalDataSchema products.managed_warehouse.backend.logic.connection write(get_or_create) 1
+warehouse_sources.ExternalDataSchema products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow instance-single 1
+warehouse_sources.ExternalDataSchema products.managed_warehouse.backend.temporal.ducklake_register_data_imports_workflow instance-single 2
+warehouse_sources.ExternalDataSchema products.marketing_analytics.backend.demo.health write(create) 1
+warehouse_sources.ExternalDataSchema products.marketing_analytics.backend.services.data_source_health instance-many(filter) 1
+warehouse_sources.ExternalDataSchema products.signals.backend.emission.emit_signals instance-many(aget) 1
+warehouse_sources.ExternalDataSchema products.signals.backend.management.commands.emit_signals_from_warehouse instance-single 1
+warehouse_sources.ExternalDataSchema products.signals.backend.views instance-many(select_related) 1
+warehouse_sources.ExternalDataSource ee.hogai.tools.execute_sql.direct_connection_suggestions instance-many(defer) 1
+warehouse_sources.ExternalDataSource posthog.hogql.database.database instance-many(filter) 1
+warehouse_sources.ExternalDataSource posthog.hogql.database.database instance-single 2
+warehouse_sources.ExternalDataSource posthog.hogql.direct_connection instance-single 1
+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
+warehouse_sources.ExternalDataSource products.engineering_analytics.backend.logic.job_logs.coordinator instance-many(select_related) 1
+warehouse_sources.ExternalDataSource products.engineering_analytics.backend.logic.sources instance-many(order_by) 1
+warehouse_sources.ExternalDataSource products.engineering_analytics.backend.management.commands.seed_engineering_analytics instance-single 1
+warehouse_sources.ExternalDataSource products.engineering_analytics.backend.management.commands.seed_engineering_analytics write(create) 1
+warehouse_sources.ExternalDataSource products.managed_warehouse.backend.logic.connection instance-many(exclude) 1
+warehouse_sources.ExternalDataSource products.managed_warehouse.backend.logic.connection instance-many(filter) 1
+warehouse_sources.ExternalDataSource products.managed_warehouse.backend.logic.connection write(create) 1
+warehouse_sources.ExternalDataSource products.marketing_analytics.backend.demo.health write(create) 1
+warehouse_sources.ExternalDataSource products.marketing_analytics.backend.demo.health write(update) 1
+warehouse_sources.ExternalDataSource products.marketing_analytics.backend.hogql_queries.adapters.factory instance-many(filter) 1
+warehouse_sources.ExternalDataSource products.marketing_analytics.backend.management.commands.generate_marketing_demo_data write(create) 1
+warehouse_sources.ExternalDataSource products.marketing_analytics.backend.management.commands.generate_marketing_demo_data write(update) 1
+warehouse_sources.ExternalDataSource products.marketing_analytics.backend.services.data_source_health instance-many(order_by) 1
+warehouse_sources.ExternalDataSource products.posthog_ai.evals.data_warehouse.seeder write(create) 1
+warehouse_sources.ExternalDataSource products.signals.backend.management.commands.reset_signals_self_driving instance-many(filter) 1
+warehouse_sources.WarehouseColumnAnnotation products.data_modeling.backend.logic.enrich_view_semantics instance-many(filter) 1
+warehouse_sources.WarehouseColumnAnnotation products.data_warehouse.backend.presentation.views.column_annotation drf-model-serializer 1
+warehouse_sources.WarehouseColumnAnnotation products.data_warehouse.backend.presentation.views.column_annotation instance-many(unscoped) 1
+warehouse_sources.WarehouseColumnAnnotation products.posthog_ai.evals.data_warehouse.seeder construct 2
+warehouse_sources.WarehouseColumnAnnotation products.posthog_ai.evals.data_warehouse.seeder write(bulk_create) 1
diff --git a/tools/hogli-commands/hogli_commands/product/cli.py b/tools/hogli-commands/hogli_commands/product/cli.py
index b39adde22659..12a4ad5763a1 100644
--- a/tools/hogli-commands/hogli_commands/product/cli.py
+++ b/tools/hogli-commands/hogli_commands/product/cli.py
@@ -180,3 +180,41 @@ def cmd_isolate_move(name: str, views: tuple[str, ...], dry_run: bool) -> None:
click.echo("\n(dry run — nothing changed)")
else:
click.echo("\nNext: review `git status`, then run tach check + lint-imports + hogli product:lint")
+
+
+ name="product:crossings",
+ help="Report how consumer code uses watched-models crossing classes, disallowed shapes first",
+)
[email protected]("name", required=False)
[email protected]("--all", "scan_all", is_flag=True, help="Scan every product that holds crossing entries")
[email protected]("--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")
+def cmd_crossings(name: str | None, scan_all: bool, as_json: bool, write_baseline: bool) -> None:
+ import json as json_module
+ from dataclasses import asdict
+
+ from .crossings import (
+ BASELINE_PATH,
+ crossing_classes,
+ render_report,
+ scan_crossing_uses,
+ write_baseline as write_baseline_file,
+ )
+
+ if not name and not scan_all:
+ raise click.UsageError("Provide a product name or use --all")
+ if write_baseline and not scan_all:
+ raise click.UsageError("--write-baseline regenerates the whole file, so it needs --all")
+
+ products = None if scan_all else [name] if name else None
+ uses = scan_crossing_uses(products)
+ if write_baseline:
+ write_baseline_file(uses)
+ click.echo(f"Baseline written: {BASELINE_PATH}")
+ return
+ if as_json:
+ for use in uses:
+ click.echo(json_module.dumps(asdict(use) | {"allowed": use.is_allowed}))
+ return
+ click.echo(render_report(uses, [c.label for c in crossing_classes(products)]))
diff --git a/tools/hogli-commands/hogli_commands/product/crossings.py b/tools/hogli-commands/hogli_commands/product/crossings.py
new file mode 100644
index 000000000000..c58150b533ed
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/product/crossings.py
@@ -0,0 +1,692 @@
+"""Classify every use of a watched-models crossing class in consumer code, and rank it by kind.
+
+Default-deny: a use is allowed only when this module recognizes it as one of the instance-free shapes
+(annotation, `DoesNotExist`, a nested enum or class attribute, `_meta`, a scalar-terminated manager
+chain, a chain embedded in `Exists`/`Subquery`); every other use is disallowed, including shapes
+nobody has classified yet.
+
+The allowance in `MODEL_CROSSINGS` says which model classes may leave their product at all. It says
+nothing about what a consumer then does with them, so a sanctioned crossing still hides a
+`ModelSerializer`, a soft-delete write, or a row lock sitting in the wrong product. This module reads
+the other side of that coupling: for each crossing class it resolves the concrete module the class is
+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.
+
+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.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import ast
+import textwrap
+from collections import Counter, defaultdict
+from collections.abc import Iterable, Iterator
+from dataclasses import dataclass
+from pathlib import Path
+
+from .isolation import MODEL_CROSSINGS, facade_model_crossings
+from .paths import PRODUCTS_DIR, REPO_ROOT
+
+# Where Python that can consume a product model lives. Everything else at the repo root is
+# frontend, infra, or standalone tooling that never imports Django product models.
+SCANNED_ROOTS: tuple[str, ...] = ("posthog", "ee", "products", "common")
+SKIPPED_DIRS: frozenset[str] = frozenset({"node_modules", ".venv", "venv", "__pycache__", ".git", ".mypy_cache"})
+
+# Model manager attributes a crossing class exposes. A chain rooted at one of these is a queryset.
+MANAGERS: frozenset[str] = frozenset(
+ {
+ "objects",
+ "all_teams",
+ "raw_objects",
+ "objects_including_soft_deleted",
+ "objects_with_deleted",
+ "all_objects",
+ "_default_manager",
+ "_base_manager",
+ }
+)
+
+# Queryset terminals that return scalars, tuples, or dicts — never model instances.
+SCALAR_TERMINALS: frozenset[str] = frozenset({"values", "values_list", "count", "exists", "aggregate"})
+
+# `_meta` attributes that lead back to a manager, so a chain through them is a queryset again.
+META_MANAGERS: frozenset[str] = frozenset({"default_manager", "base_manager"})
+
+# `_meta` attributes that hand the model class back, so the chain after them starts over.
+META_CLASS_ATTRS: frozenset[str] = frozenset({"model", "concrete_model", "proxy_for_model"})
+
+# Queryset terminals that return exactly one model instance.
+SINGLE_TERMINALS: frozenset[str] = frozenset({"get", "first", "last", "earliest", "latest"})
+
+# Queryset methods that write rows.
+WRITE_METHODS: frozenset[str] = frozenset(
+ {
+ "create",
+ "update",
+ "delete",
+ "get_or_create",
+ "update_or_create",
+ "bulk_create",
+ "bulk_update",
+ "acreate",
+ "aupdate",
+ "adelete",
+ "abulk_create",
+ }
+)
+
+# ORM wrappers that embed a queryset as a subquery — the rows never materialize in the consumer.
+SUBQUERY_CALLS: frozenset[str] = frozenset({"Exists", "Subquery"})
+
+ALLOWED_KIND_PREFIXES: tuple[str, ...] = (
+ "annotation",
+ "exception",
+ "nested-class-attr",
+ "_meta",
+ "scalar-chain",
+ "subquery",
+)
+
+
+def kind_is_allowed(kind: str) -> bool:
+ """True for the instance-free shapes the doctrine recognizes. Everything else is disallowed."""
+ return kind.startswith(ALLOWED_KIND_PREFIXES)
+
+
+@dataclass(frozen=True)
+class CrossingClass:
+ """A watched-models crossing class, resolved to the module that defines it."""
+
+ product: str
+ class_name: str
+ defining_module: str # dotted, e.g. "products.alerts.backend.models.alert"
+
+ @property
+ def label(self) -> str:
+ return f"{self.product}.{self.class_name}"
+
+
+@dataclass(frozen=True)
+class CrossingUse:
+ """One kind of use of one crossing class in one consumer module, with how often it appears."""
+
+ crossing: str # CrossingClass.label
+ consumer_module: str # dotted, e.g. "products.product_analytics.backend.presentation.insight"
+ kind: str
+ count: int
+
+ @property
+ def is_allowed(self) -> bool:
+ return kind_is_allowed(self.kind)
+
+ def as_baseline_line(self) -> str:
+ return f"{self.crossing} {self.consumer_module} {self.kind} {self.count}"
+
+
+# ---------------------------------------------------------------------------
+# Resolving crossing classes and the modules that hand them out
+# ---------------------------------------------------------------------------
+
+
+_REPO_PREFIX = f"{REPO_ROOT}{os.sep}"
+
+
+def _dotted_module(path: Path) -> str:
+ """Repo path -> dotted module name ('posthog/models/__init__.py' -> 'posthog.models').
+
+ String work on purpose: `Path.relative_to` is too slow for every file in the repo."""
+ parts = str(path).removeprefix(_REPO_PREFIX).removesuffix(".py").split(os.sep)
+ if parts[-1] == "__init__":
+ parts.pop()
+ return ".".join(parts)
+
+
+def _model_modules(product: str) -> Iterator[Path]:
+ backend = PRODUCTS_DIR / product / "backend"
+ flat = backend / "models.py"
+ if flat.is_file():
+ yield flat
+ package = backend / "models"
+ if package.is_dir():
+ yield from sorted(package.rglob("*.py"))
+
+
+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):
+ continue
+ if any(isinstance(node, ast.ClassDef) and node.name == class_name for node in tree.body):
+ return _dotted_module(path)
+ return None
+
+
+def crossing_classes(products: Iterable[str] | None = None) -> list[CrossingClass]:
+ """Every crossing class of the requested products (all of them when `products` is None).
+
+ `MODEL_CROSSINGS` is the register; a product's facade re-exports are read too, so a class the
+ facade hands out is covered even before the register catches up."""
+ wanted = set(products) if products is not None else {p for p, _ in MODEL_CROSSINGS}
+ names: set[tuple[str, str]] = {(p, c) for p, c in MODEL_CROSSINGS if p in wanted}
+ for product in sorted(wanted):
+ backend_dir = PRODUCTS_DIR / product / "backend"
+ if backend_dir.is_dir():
+ names.update((product, f.class_name) for f in facade_model_crossings(backend_dir, product))
+ resolved = []
+ for product, class_name in sorted(names):
+ module = _defining_module(product, class_name)
+ if module is not None:
+ resolved.append(CrossingClass(product, class_name, module))
+ return resolved
+
+
+def _app_labels() -> dict[str, str]:
+ """Django app label -> product name, read off each product's AppConfig."""
+ labels: dict[str, str] = {}
+ for apps_py in sorted(PRODUCTS_DIR.glob("*/backend/apps.py")):
+ product = apps_py.parents[1].name
+ try:
+ tree = ast.parse(apps_py.read_text(encoding="utf-8", errors="ignore"))
+ except (SyntaxError, OSError):
+ continue
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Assign):
+ continue
+ target = node.targets[0]
+ if isinstance(target, ast.Name) and target.id == "label" and isinstance(node.value, ast.Constant):
+ labels[str(node.value.value)] = product
+ return labels
+
+
+# ---------------------------------------------------------------------------
+# 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:
+ return True
+ return path.name.startswith("test_") or path.name.endswith("_test.py") or path.name == "conftest.py"
+
+
+@dataclass(frozen=True, slots=True)
+class _ImportEdge:
+ """One `from module import exported as bound`."""
+
+ module: str
+ exported: str
+ bound: str
+
+
+@dataclass(frozen=True, slots=True)
+class _ModuleAlias:
+ """A module bound to a local name, by `import a.b as c` or by `from a import b` when `a.b` is a module."""
+
+ alias: str
+ module: str
+
+
+@dataclass(frozen=True)
+class _ImportTable:
+ """Everything a file's import statements bind: names, and modules it may read names off."""
+
+ edges: tuple[_ImportEdge, ...]
+ module_aliases: tuple[_ModuleAlias, ...]
+
+
+@dataclass(frozen=True)
+class _Candidate:
+ """A scanned file with its imports read but its body not yet parsed."""
+
+ path: Path
+ dotted: str
+ imports: _ImportTable
+ mentions_get_model: bool
+
+
+# One import statement, parenthesized or not. Imports are the only thing the first pass reads, and
+# re-parsing just them is an order of magnitude cheaper than building the whole file's AST twice.
+_IMPORT_STATEMENT_RE = re.compile(
+ rb"^[ \t]*(?:from[ \t]+[.\w]+[ \t]+import[ \t]+(?:\([^)]*\)|[^\n]*)|import[ \t]+[\w., \t]*)",
+ re.MULTILINE,
+)
+
+
+def _resolve_import_from(node: ast.ImportFrom, package: str) -> str | None:
+ """The absolute dotted module an ImportFrom reads from, resolving relative levels."""
+ if not node.level:
+ return node.module
+ parts = package.split(".")
+ climb = node.level - 1
+ if climb:
+ parts = parts[:-climb]
+ if not parts:
+ return None
+ base = ".".join(parts)
+ return f"{base}.{node.module}" if node.module else base
+
+
+def _read_imports(source: bytes, package: str) -> _ImportTable:
+ """What a file's import statements bind, read from those statements alone.
+
+ Deferred and `if TYPE_CHECKING` imports come along: the statements are lifted out of their
+ block and re-parsed at top level, which is all the relative level needs to resolve.
+
+ `from a.b import c` binds a module when `a.b.c` is one, so every such name is recorded as a
+ module alias too; the scan keeps only the aliases whose module hands out a crossing class."""
+ lifted = b"\n".join(match.group(0).lstrip() for match in _IMPORT_STATEMENT_RE.finditer(source))
+ try:
+ tree = ast.parse(lifted)
+ except (SyntaxError, ValueError):
+ return _ImportTable((), ())
+ edges: list[_ImportEdge] = []
+ aliases: list[_ModuleAlias] = []
+ for node in tree.body:
+ if isinstance(node, ast.ImportFrom):
+ module = _resolve_import_from(node, package)
+ if module is None:
+ continue
+ for alias in node.names:
+ bound = alias.asname or alias.name
+ edges.append(_ImportEdge(module, alias.name, bound))
+ aliases.append(_ModuleAlias(bound, f"{module}.{alias.name}"))
+ elif isinstance(node, ast.Import):
+ aliases.extend(_ModuleAlias(alias.asname or alias.name, alias.name) for alias in node.names)
+ return _ImportTable(tuple(edges), tuple(aliases))
+
+
+def _candidates() -> list[_Candidate]:
+ """Every scanned .py file, with its imports read.
+
+ Reading imports only is what keeps the full AST pass — and so the repo-invariant test — small:
+ a file is parsed whole only once its imports show it can reach a crossing class."""
+ found = []
+ for root in SCANNED_ROOTS:
+ for path in sorted((REPO_ROOT / root).rglob("*.py")):
+ if SKIPPED_DIRS.intersection(path.parts):
+ continue
+ source = path.read_bytes()
+ dotted = _dotted_module(path)
+ package = dotted if path.name == "__init__.py" else dotted.rsplit(".", 1)[0]
+ found.append(_Candidate(path, dotted, _read_imports(source, package), b"get_model" in source))
+ return found
+
+
+# ---------------------------------------------------------------------------
+# Which local names are bound to a crossing class
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True, slots=True)
+class _Export:
+ """A name as one module hands it out."""
+
+ module: str
+ name: str
+
+
+def _origins(candidates: list[_Candidate], classes: list[CrossingClass]) -> dict[_Export, str]:
+ """Export -> crossing label, for every path an import of the class can take.
+
+ Seeded with the defining module and grown to a fixpoint over re-exports, so `facade/models.py`,
+ a package `__init__`, and a renaming alias all resolve back to the same class."""
+ origins: dict[_Export, str] = {_Export(c.defining_module, c.class_name): c.label for c in classes}
+ while True:
+ grew = False
+ for candidate in candidates:
+ for edge in candidate.imports.edges:
+ label = origins.get(_Export(edge.module, edge.exported))
+ if label is None:
+ continue
+ local = _Export(candidate.dotted, edge.bound)
+ if origins.get(local) != label:
+ origins[local] = label
+ grew = True
+ if not grew:
+ return origins
+
+
+def _bound_names(candidate: _Candidate, origins: dict[_Export, str]) -> dict[str, str]:
+ """Local name -> crossing label, for every crossing class this file imported."""
+ names = {}
+ for edge in candidate.imports.edges:
+ label = origins.get(_Export(edge.module, edge.exported))
+ if label is not None:
+ names[edge.bound] = label
+ return names
+
+
+def _dotted_of(node: ast.expr) -> str | None:
+ if isinstance(node, ast.Name):
+ return node.id
+ if isinstance(node, ast.Attribute):
+ base = _dotted_of(node.value)
+ return f"{base}.{node.attr}" if base else None
+ return None
+
+
+def _class_nodes(
+ tree: ast.Module, names: dict[str, str], module_aliases: dict[str, str], origins: dict[_Export, str]
+) -> list[tuple[ast.expr, str]]:
+ """Every expression node that names a crossing class, paired with its crossing label."""
+ found: list[tuple[ast.expr, str]] = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Name) and node.id in names:
+ found.append((node, names[node.id]))
+ elif isinstance(node, ast.Attribute) and module_aliases:
+ dotted = _dotted_of(node.value)
+ module = module_aliases.get(dotted) if dotted else None
+ label = origins.get(_Export(module, node.attr)) if module else None
+ if label is not None:
+ found.append((node, label))
+ return found
+
+
+# ---------------------------------------------------------------------------
+# Classification
+# ---------------------------------------------------------------------------
+
+
+def _parent_map(tree: ast.Module) -> dict[int, ast.AST]:
+ parents: dict[int, ast.AST] = {}
+ for node in ast.walk(tree):
+ for child in ast.iter_child_nodes(node):
+ parents[id(child)] = node
+ return parents
+
+
+def _chain(node: ast.expr, parents: dict[int, ast.AST]) -> tuple[list[str], ast.AST]:
+ """Attribute/call chain hanging off `node`: its method names, and the outermost node it reaches."""
+ methods: list[str] = []
+ current: ast.AST = node
+ while True:
+ parent = parents.get(id(current))
+ if isinstance(parent, ast.Attribute) and parent.value is current:
+ methods.append(parent.attr)
+ elif isinstance(parent, ast.Call) and parent.func is current:
+ pass
+ else:
+ return methods, current
+ current = parent
+
+
+def _enclosing_call_name(node: ast.AST, parents: dict[int, ast.AST]) -> str | None:
+ """The callee name of the nearest enclosing call, not crossing a def/class boundary."""
+ current = parents.get(id(node))
+ while current is not None:
+ if isinstance(current, ast.Call):
+ func = current.func
+ name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)
+ if name:
+ return str(name)
+ if isinstance(current, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
+ return None
+ current = parents.get(id(current))
+ return None
+
+
+def _in_annotation(node: ast.expr, parents: dict[int, ast.AST]) -> bool:
+ child: ast.AST = node
+ parent = parents.get(id(child))
+ while parent is not None:
+ if isinstance(parent, ast.arg) and parent.annotation is child:
+ return True
+ if isinstance(parent, ast.FunctionDef | ast.AsyncFunctionDef) and parent.returns is child:
+ return True
+ if isinstance(parent, ast.AnnAssign) and parent.annotation is child:
+ return True
+ if not isinstance(parent, ast.Subscript | ast.BinOp | ast.Tuple | ast.Attribute | ast.Constant):
+ return False
+ child = parent
+ parent = parents.get(id(child))
+ return False
+
+
+def _manager_chain_kind(methods: list[str], outer: ast.AST, parents: dict[int, ast.AST]) -> str:
+ """Classify a queryset chain. Row locking and prefetching win over whatever terminates the chain."""
+ enclosing = _enclosing_call_name(outer, parents)
+ terminal = methods[-1] if methods else "manager"
+ if "select_for_update" in methods:
+ return "lock"
+ writes = [m for m in methods if m in WRITE_METHODS]
+ if writes:
+ return f"write({','.join(writes)})"
+ if enclosing == "Prefetch":
+ return "prefetch"
+ if enclosing in SUBQUERY_CALLS:
+ return f"subquery({enclosing})"
+ if terminal in SCALAR_TERMINALS:
+ return f"scalar-chain({terminal})"
+ if enclosing is not None and enclosing.endswith("Field"):
+ return "drf-field-queryset"
+ if terminal in SINGLE_TERMINALS:
+ return "instance-single"
+ return f"instance-many({terminal})"
+
+
+def _attribute_chain_kind(methods: list[str], outer: ast.AST, parents: dict[int, ast.AST]) -> str:
+ """Classify an attribute chain hanging off the class; `methods` is non-empty."""
+ head = methods[0]
+ if head == "DoesNotExist":
+ return "exception"
+ if head == "_meta":
+ if len(methods) == 1:
+ return "_meta"
+ if methods[1] in META_MANAGERS:
+ return _manager_chain_kind(methods[2:], outer, parents)
+ if methods[1] in META_CLASS_ATTRS:
+ return _attribute_chain_kind(methods[2:], outer, parents) if len(methods) > 2 else "_meta"
+ return "_meta" if methods[1] != "managers" else "other(Attribute:_meta.managers)"
+ if head in MANAGERS:
+ return _manager_chain_kind(methods[1:], outer, parents)
+ if head[:1].isupper():
+ return f"nested-class-attr({head})"
+ return f"other(Attribute:{head})"
+
+
+def classify_use(node: ast.expr, parents: dict[int, ast.AST]) -> str:
+ """The kind of one name-level use of a crossing class."""
+ if _in_annotation(node, parents):
+ return "annotation"
+ methods, outer = _chain(node, parents)
+ if methods:
+ return _attribute_chain_kind(methods, outer, parents)
+ parent = parents.get(id(node))
+ if isinstance(parent, ast.Call):
+ if parent.func is node:
+ return "construct"
+ callee = _dotted_of(parent.func) or "?"
+ callee = callee.rsplit(".", 1)[-1]
+ return "isinstance" if callee == "isinstance" else f"passed-as-class({callee})"
+ if isinstance(parent, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "model" for t in parent.targets):
+ return "drf-model-serializer"
+ if isinstance(parent, ast.keyword) and parent.arg == "model":
+ return "drf-model-serializer"
+ if isinstance(parent, ast.Tuple | ast.List | ast.Dict | ast.Set | ast.Subscript):
+ return "in-collection"
+ 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."""
+ 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
+ strings = [a.value for a in node.args if isinstance(a, ast.Constant) and isinstance(a.value, str)]
+ keywords = {
+ k.arg: k.value.value
+ for k in node.keywords
+ if k.arg in ("app_label", "model_name")
+ and isinstance(k.value, ast.Constant)
+ and isinstance(k.value.value, str)
+ }
+ app_label = keywords.get("app_label", strings[0] if strings else None)
+ class_name = keywords.get("model_name", strings[1] if len(strings) > 1 else None)
+ if app_label is not None and class_name is None and "." in app_label:
+ app_label, class_name = app_label.split(".", 1)
+ if app_label is None or class_name is None:
+ continue
+ product = product_by_label.get(app_label)
+ label = label_by_lower.get(f"{product}.{class_name}".lower()) if product is not None else None
+ if label is not None:
+ found[label] += 1
+ return found
+
+
+# ---------------------------------------------------------------------------
+# Scan
+# ---------------------------------------------------------------------------
+
+
+def _reads_class_off_module(source: bytes, aliases: dict[str, str], class_names: set[str]) -> bool:
+ """Whether `alias.ClassName` appears in the text at all, for any module alias and crossing class.
+
+ Most files that alias a module handing out a crossing class never read the class off it, and
+ this check spares them the full parse."""
+ names = b"|".join(sorted(re.escape(n).encode() for n in class_names))
+ locals_ = b"|".join(sorted(re.escape(a).encode() for a in aliases))
+ return re.search(rb"\b(?:" + locals_ + rb")\.(?:" + names + rb")\b", source) is not None
+
+
+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."""
+ classes = crossing_classes(products)
+ if not classes:
+ return []
+ owning_dir = {c.label: PRODUCTS_DIR / c.product for c in classes}
+ 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()
+
+ counts: dict[tuple[str, str, str], int] = defaultdict(int)
+ for candidate in candidates:
+ if _is_test_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}
+ if not names and not aliases and not candidate.mentions_get_model:
+ continue
+ try:
+ source = candidate.path.read_bytes()
+ except OSError:
+ continue
+ if not names and not candidate.mentions_get_model and not _reads_class_off_module(source, aliases, class_names):
+ continue
+ try:
+ tree = ast.parse(source)
+ except (SyntaxError, ValueError):
+ continue
+ class_nodes = _class_nodes(tree, names, aliases, origins)
+ if class_nodes:
+ parents = _parent_map(tree)
+ for node, label in class_nodes:
+ if candidate.path.is_relative_to(owning_dir[label]):
+ 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():
+ if not candidate.path.is_relative_to(owning_dir[label]):
+ counts[(label, candidate.dotted, "get_model")] += count
+
+ return [CrossingUse(label, module, kind, count) for (label, module, kind), count in sorted(counts.items())]
+
+
+def disallowed_uses(uses: Iterable[CrossingUse]) -> list[CrossingUse]:
+ return [use for use in uses if not use.is_allowed]
+
+
+# ---------------------------------------------------------------------------
+# Reporting
+# ---------------------------------------------------------------------------
+
+
+def _render_kind_block(kind: str, entries: list[CrossingUse]) -> list[str]:
+ total = sum(use.count for use in entries)
+ modules = [
+ use.consumer_module if use.count == 1 else f"{use.consumer_module} x{use.count}"
+ for use in sorted(entries, key=lambda u: (-u.count, u.consumer_module))
+ ]
+ wrapped = textwrap.wrap(", ".join(modules), width=112, initial_indent=" " * 6, subsequent_indent=" " * 6)
+ return [f" {kind} {total}", *wrapped]
+
+
+def render_report(uses: list[CrossingUse], class_labels: Iterable[str] = ()) -> str:
+ """Per crossing class: disallowed kinds first, each with its count and the consumer modules.
+
+ A class with no uses at all is still listed — an entry nothing consumes is one the register can
+ drop."""
+ by_crossing: dict[str, list[CrossingUse]] = {label: [] for label in sorted(class_labels)}
+ for use in uses:
+ by_crossing.setdefault(use.crossing, []).append(use)
+ if not by_crossing:
+ return "No crossing classes resolved — nothing to report."
+
+ lines: list[str] = []
+ for crossing, entries in sorted(
+ by_crossing.items(), key=lambda item: (-sum(u.count for u in disallowed_uses(item[1])), item[0])
+ ):
+ bad = disallowed_uses(entries)
+ good = [use for use in entries if use.is_allowed]
+ lines.append(f"\n{crossing} {sum(u.count for u in bad)} disallowed, {sum(u.count for u in good)} allowed")
+ if not entries:
+ lines.append(" no uses in consumer code")
+ elif not bad:
+ lines.append(" no disallowed uses")
+ by_kind: dict[str, list[CrossingUse]] = defaultdict(list)
+ for use in bad:
+ by_kind[use.kind].append(use)
+ for kind, kind_entries in sorted(by_kind.items(), key=lambda item: (-sum(u.count for u in item[1]), item[0])):
+ lines.extend(_render_kind_block(kind, kind_entries))
+ if good:
+ summary: Counter[str] = Counter()
+ for use in good:
+ summary[use.kind] += use.count
+ allowed = ", ".join(f"{kind} {count}" for kind, count in sorted(summary.items()))
+ lines.extend(
+ textwrap.wrap(f"allowed: {allowed}", width=112, initial_indent=" ", subsequent_indent=" " * 6)
+ )
+
+ total_bad = sum(use.count for use in uses if not use.is_allowed)
+ total_good = sum(use.count for use in uses if use.is_allowed)
+ lines.append(f"\nTotal: {total_bad} disallowed, {total_good} allowed, across {len(by_crossing)} crossing classes.")
+ lines.append("Disallowed uses are ratcheted in products/model_crossing_uses_baseline.txt — they may only go down.")
+ return "\n".join(lines)
+
+
+BASELINE_PATH = REPO_ROOT / "products" / "model_crossing_uses_baseline.txt"
+
+BASELINE_HEADER = """\
+# Disallowed uses of watched-models crossing classes in consumer code.
+# One line per (product.Class, consumer module, kind, count); see products/architecture.md
+# § Wiring couplings for which shapes are allowed.
+#
+# 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
+"""
+
+
+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"
+
+
+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 write_baseline(uses: Iterable[CrossingUse], path: Path = BASELINE_PATH) -> None:
+ path.write_text(render_baseline(uses))
diff --git a/tools/hogli-commands/hogli_commands/tests/test_crossings.py b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
new file mode 100644
index 000000000000..62a4c8748345
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
@@ -0,0 +1,170 @@
+"""Tests for the model-crossing use classifier."""
+
+from __future__ import annotations
+
+import ast
+import textwrap
+from pathlib import Path
+
+import pytest
+
+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")
+
+
+def _candidate(source: str, dotted: str = "posthog.api.consumer") -> crossings._Candidate:
+ encoded = textwrap.dedent(source).encode()
+ package = dotted.rsplit(".", 1)[0]
+ imports = crossings._read_imports(encoded, package)
+ return crossings._Candidate(Path(f"{dotted.replace('.', '/')}.py"), dotted, imports, b"get_model" in encoded)
+
+
+def classify(source: str) -> list[str]:
+ candidate = _candidate(source)
+ origins = crossings._origins([candidate], [ALERT])
+ names = crossings._bound_names(candidate, origins)
+ modules = {export.module for export in origins}
+ aliases = {a.alias: a.module for a in candidate.imports.module_aliases if a.module in modules}
+ tree = ast.parse(textwrap.dedent(source))
+ parents = crossings._parent_map(tree)
+ return [classify_use(node, parents) for node, _ in crossings._class_nodes(tree, names, aliases, origins)]
+
+
+IMPORT = "from products.alerts.backend.models.alert import AlertConfiguration\n"
+
+
+class TestClassifyUse:
+ @pytest.mark.parametrize(
+ "body,expected",
+ [
+ # Allowed: nothing here can hand the consumer a model instance.
+ ("def f(a: AlertConfiguration) -> AlertConfiguration: ...", ["annotation", "annotation"]),
+ ("def f() -> list[AlertConfiguration | None]: ...", ["annotation"]),
+ ("x: dict[str, AlertConfiguration] = {}", ["annotation"]),
+ ("try:\n pass\nexcept AlertConfiguration.DoesNotExist:\n pass", ["exception"]),
+ ("s = AlertConfiguration.Status.FIRING", ["nested-class-attr(Status)"]),
+ ("n = AlertConfiguration._meta.db_table", ["_meta"]),
+ ("f = AlertConfiguration._meta.get_field('insight')", ["_meta"]),
+ (
+ "ids = AlertConfiguration.objects.filter(team=t).values_list('id', flat=True)",
+ ["scalar-chain(values_list)"],
+ ),
+ ("n = AlertConfiguration.objects.count()", ["scalar-chain(count)"]),
+ ("q = Exists(AlertConfiguration.objects.filter(insight=OuterRef('pk')))", ["subquery(Exists)"]),
+ # Disallowed: each of these puts a model instance, a write, or a lock in the consumer.
+ ("a = AlertConfiguration.objects.get(pk=1)", ["instance-single"]),
+ ("a = AlertConfiguration._meta.default_manager.get(pk=1)", ["instance-single"]),
+ ("a = AlertConfiguration._meta.model.objects.get(pk=1)", ["instance-single"]),
+ ("a = AlertConfiguration._meta.concrete_model._meta.model.objects.create(team=t)", ["write(create)"]),
+ ("m = AlertConfiguration._meta.model", ["_meta"]),
+ ("s = AlertConfiguration._meta.model.Status.FIRING", ["nested-class-attr(Status)"]),
+ ("m = AlertConfiguration._meta.managers", ["other(Attribute:_meta.managers)"]),
+ ("by_id = AlertConfiguration.objects.in_bulk(ids)", ["instance-many(in_bulk)"]),
+ ("a = AlertConfiguration.objects.filter(team=t).first()", ["instance-single"]),
+ ("qs = AlertConfiguration.objects.filter(team=t)", ["instance-many(filter)"]),
+ ("qs = AlertConfiguration.objects", ["instance-many(manager)"]),
+ ("qs = AlertConfiguration.objects.all().select_related('insight')", ["instance-many(select_related)"]),
+ ("p = Prefetch('alerts', queryset=AlertConfiguration.objects.filter(team=t))", ["prefetch"]),
+ ("f = PrimaryKeyRelatedField(queryset=AlertConfiguration.objects.all())", ["drf-field-queryset"]),
+ ("class Meta:\n model = AlertConfiguration", ["drf-model-serializer"]),
+ ("if isinstance(obj, AlertConfiguration):\n pass", ["isinstance"]),
+ ("a = cast(AlertConfiguration, obj)", ["passed-as-class(cast)"]),
+ ("REGISTRY = (AlertConfiguration, None)", ["in-collection"]),
+ ("a = AlertConfiguration(team=t)", ["construct"]),
+ ("a = AlertConfiguration.objects.create(team=t)", ["write(create)"]),
+ ("AlertConfiguration.objects.filter(team=t).update(enabled=False)", ["write(update)"]),
+ ("a = AlertConfiguration.objects.select_for_update().get(pk=1)", ["lock"]),
+ ("qs = AlertConfiguration.objects.select_for_update().filter(team=t)", ["lock"]),
+ ("p = Prefetch('a', queryset=AlertConfiguration.objects.select_related('insight'))", ["prefetch"]),
+ ("v = AlertConfiguration.compute_condition_type(x)", ["other(Attribute:compute_condition_type)"]),
+ ("x = AlertConfiguration if flag else None", ["other(IfExp)"]),
+ ],
+ )
+ def test_kind(self, body: str, expected: list[str]) -> None:
+ assert classify(IMPORT + textwrap.dedent(body)) == expected
+
+ @pytest.mark.parametrize(
+ "kind,allowed",
+ [
+ ("annotation", True),
+ ("scalar-chain(values_list)", True),
+ ("subquery(Exists)", True),
+ ("instance-single", False),
+ ("prefetch", False),
+ ("write(create)", False),
+ ("other(IfExp)", False),
+ ],
+ )
+ def test_allowed_split(self, kind: str, allowed: bool) -> None:
+ assert kind_is_allowed(kind) is allowed
+
+
+class TestBindingPaths:
+ @pytest.mark.parametrize(
+ "source",
+ [
+ "from products.alerts.backend.models.alert import AlertConfiguration as AC\nqs = AC.objects.filter(t=1)",
+ "if TYPE_CHECKING:\n from products.alerts.backend.models.alert import AlertConfiguration\nqs = AlertConfiguration.objects.filter(t=1)",
+ "def f():\n from products.alerts.backend.models.alert import AlertConfiguration\n return AlertConfiguration.objects.filter(t=1)",
+ "from products.alerts.backend.models.alert import (\n AlertConfiguration,\n Threshold,\n)\nqs = AlertConfiguration.objects.filter(t=1)",
+ "from products.alerts.backend.models import alert\nqs = alert.AlertConfiguration.objects.filter(t=1)",
+ "from products.alerts.backend.models import alert as alert_models\nqs = alert_models.AlertConfiguration.objects.filter(t=1)",
+ "import products.alerts.backend.models.alert\nqs = products.alerts.backend.models.alert.AlertConfiguration.objects.filter(t=1)",
+ "import products.alerts.backend.models.alert as alert_models\nqs = alert_models.AlertConfiguration.objects.filter(t=1)",
+ ],
+ )
+ def test_every_import_shape_binds(self, source: str) -> None:
+ assert classify(source) == ["instance-many(filter)"]
+
+ def test_reexport_chain_resolves_to_the_defining_module(self) -> None:
+ facade = _candidate(
+ "from ..models.alert import AlertConfiguration as AlertConfiguration",
+ "products.alerts.backend.facade.models",
+ )
+ consumer = _candidate(
+ "from products.alerts.backend.facade.models import AlertConfiguration\n"
+ "a = AlertConfiguration.objects.get(pk=1)"
+ )
+ origins = crossings._origins([facade, consumer], [ALERT])
+ assert crossings._bound_names(consumer, origins) == {"AlertConfiguration": "alerts.AlertConfiguration"}
+
+ def test_unrelated_class_of_the_same_name_is_not_bound(self) -> None:
+ candidate = _candidate(
+ "from products.alerts.backend.facade.contracts import AlertConfiguration\nqs = AlertConfiguration(id=1)"
+ )
+ origins = crossings._origins([candidate], [ALERT])
+ assert crossings._bound_names(candidate, origins) == {}
+
+
+class TestGetModelStrings:
+ @pytest.mark.parametrize(
+ "call",
+ [
+ "apps.get_model('alerts', 'AlertConfiguration')",
+ "apps.get_model('alerts.AlertConfiguration')",
+ "apps.get_model('alerts', model_name='AlertConfiguration')",
+ "apps.get_model(app_label='alerts', model_name='AlertConfiguration')",
+ "apps.get_model(model_name='AlertConfiguration', app_label='alerts')",
+ "apps.get_model('alerts', 'alertconfiguration')",
+ "apps.get_model('alerts.ALERTCONFIGURATION')",
+ ],
+ )
+ 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"})
+ 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"}) == {}
+
+
+class TestRenderReport:
+ def test_allowed_counts_sum_across_modules(self) -> None:
+ uses = [
+ crossings.CrossingUse("alerts.AlertConfiguration", "posthog.api.a", "annotation", 1),
+ crossings.CrossingUse("alerts.AlertConfiguration", "posthog.api.b", "annotation", 2),
+ ]
+ assert "allowed: annotation 3" in crossings.render_report(uses)