:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(devex): lint facade signatures for ORM and DRF types (#98215)
Julian Bez37470100fd62
diff --git a/.agents/skills/isolating-product-facade-contracts/SKILL.md b/.agents/skills/isolating-product-facade-contracts/SKILL.mdindex 6c343e317c4e..55702fcd5585 100644--- a/.agents/skills/isolating-product-facade-contracts/SKILL.md+++ b/.agents/skills/isolating-product-facade-contracts/SKILL.md@@ -271,6 +271,11 @@ records the decrease. See `products/architecture.md` § Wiring couplings.- 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.- Transaction boundaries belong in the facade (or logic), not in views.- Never return ORM models across product boundaries.+- `hogli product:lint` reads the facade signatures, in the kinds `facade-returns`,+ `facade-accepts(<parameter>)` and `facade-logic`. The matching lines of+ `products/model_crossing_uses_baseline.txt` record what the facades do today and only shrink, so a+ new finding fails the lint. Regenerate with `bin/hogli product:crossings --all --write-baseline`,+ and the rule is `products/architecture.md` § Facades: The Public Interface.- Declare every relation field that crosses a product boundary with`related_name="+"` — the reverse-accessor ratchet blocks new unsealed ones.- Do not register a signal receiver on another boundary's sender; use the movesdiff --git a/posthog/test/repo_invariants/test_model_crossing_uses.py b/posthog/test/repo_invariants/test_model_crossing_uses.pyindex ce8d86714bc3..7b1a9309f9c7 100644--- a/posthog/test/repo_invariants/test_model_crossing_uses.py+++ b/posthog/test/repo_invariants/test_model_crossing_uses.py@@ -23,6 +23,12 @@ A product may watch one subtree of that location instead of the whole of it, oncsubtree has no line left. The second test below holds that scope: it fails when a line namessomething outside the watched subtree, because the watch would then miss the code the line drives.+`facade-*` lines read the facade signatures, which is the one channel that records what the boundary+promises rather than what a caller does. `facade-returns` and `facade-accepts(<parameter>)` mean a+public facade callable puts a Django, a DRF or an ORM type on its signature; `facade-logic` means a+capability submodule holds bodies instead of re-exports. An import linter sees the same edge either+way, so the shape is frozen here. The rule is `products/architecture.md` § Facades: The Public Interface.+The check is strict equality, not "no worse than": a line that disappears must be deleted from thefile in the same change, so the file can never go stale behind the code.diff --git a/products/architecture.md b/products/architecture.mdindex 7f4502f5d965..d0e3d9a6d7cb 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -173,6 +173,7 @@ Production code may not add one.`drives(...)` lines record the tests outside a product that execute its query runners.They are keyed by the product's `backend/hogql_queries/` location instead of a class, and read from test modules only.A new line is a new outside test that drives product code, and that test belongs in the product.+`facade-*` lines record what a facade signature promises, read from the facade itself rather than from a caller.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.diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 1fcb878ad3fe..e678becb42a1 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -2,7 +2,7 @@# One line per (product.Class, consumer module, kind, count); see products/architecture.md# § Wiring couplings for which shapes are allowed.#-# Four channels land here. Name-level uses of a watched-models crossing class, in any kind the+# Five channels land here. Name-level uses of a watched-models crossing class, in any kind the# doctrine does not call instance-free. 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: a migration reaches a model through the@@ -18,11 +18,19 @@# related_name="+", remove any explicit related_query_name (a query:<name> row means one keeps# filter() traversal alive), and delete the line in the same change; a caller that needs reverse# access gets a facade read function. See products/architecture.md § Cross-product foreign keys.+# And the `facade-*` kinds, read from the facade signatures rather than from a caller: what the+# boundary itself promises. `facade-returns` and `facade-accepts(<parameter>)` mean a public facade+# callable puts a Django, a DRF or an ORM type on its signature; `facade-logic` means a capability+# submodule holds bodies rather than re-exports, and its count is how many are left. The first+# column says what crosses — `<product>.<Class>`, `<library>.<Type>`, or the facade module for a+# `facade-logic` line — and the consumer column holds the symbol or the module that carries it.+# The rule is products/architecture.md § Facades: The Public Interface.## Counts may only go down, and a line that disappears must be deleted here too.## Regenerate after a removal: bin/hogli product:crossings --all --write-baseline-# That command refuses to write when the scan holds a line this file does not. A coupling that+# That command refuses to write when the scan holds a line this file does not, or a count that+# went up. A coupling that# must stand is a hand-edited line here, together with the amendment in products/architecture.md# § Wiring couplings that permits it, because a reviewer can see both.access_control.Role approvals.ApprovalPolicy.bypass_roles reverse-accessor(bypass_policies) 1@@ -32,11 +40,57 @@ actions.Action posthog.TaggedItem.action reverse-accessor(tagged_items) 1actions.Action surveys.Survey.actions reverse-accessor(survey_set) 1approvals.ChangeRequest feature_flags.ScheduledChange.change_request reverse-accessor(scheduled_changes) 1batch_exports.BatchExport cdp.HogFunction.batch_export reverse-accessor(hogfunction_set) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.apply_billing_alert_configuration_lifecycle facade-accepts(alert) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.apply_destination_changes facade-accepts(alert) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.create_destination facade-accepts(alert) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.delete_alert_and_destinations facade-accepts(alert) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.delete_destination facade-accepts(alert) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.destinations_for_alerts facade-accepts(alerts) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.evaluate_and_dispatch_alert facade-accepts(alert) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.initialize_billing_alert_lifecycle facade-accepts(alert) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.preview_alert facade-accepts(alert) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.reschedule_billing_alert_configuration facade-accepts(alert) 1+billing_alerts.BillingAlertConfiguration products.billing_alerts.backend.facade.api.visible_events_for_alert facade-accepts(alert) 1+billing_alerts.BillingAlertEvent products.billing_alerts.backend.facade.api.BillingAlertDispatchResult.__init__ facade-accepts(event) 1+billing_alerts.BillingAlertEvent products.billing_alerts.backend.facade.api.visible_events_for_alert facade-returns 1+canvas.Canvas products.canvas.backend.facade.api.seed_home_canvas facade-accepts(canvas) 1canvas.Canvas products.tasks.backend.logic.services.loop_runs get_model 1cohorts.Cohort experiments.Experiment.exposure_cohort reverse-accessor(experiment_set) 1+context_layer.ContextLayerConfig products.context_layer.backend.facade.api.enable_context_layer facade-returns 1+context_layer.ContextLayerConfig products.context_layer.backend.facade.api.get_config facade-returns 1conversations.Ticket posthog.TaggedItem.ticket reverse-accessor(tagged_items) 1customer_analytics.Account notebooks.ResourceNotebook.account reverse-accessor(notebooks) 1customer_analytics.Account posthog.TaggedItem.account reverse-accessor(tagged_items) 1+customer_analytics.Account products.customer_analytics.backend.facade.api.create_account facade-returns 1+customer_analytics.Account products.customer_analytics.backend.facade.api.update_account facade-accepts(account) 1+customer_analytics.Account products.customer_analytics.backend.facade.api.update_account facade-returns 1+customer_analytics.Account products.customer_analytics.backend.facade.testing.create_account facade-returns 1+customer_analytics.Account products.customer_analytics.backend.facade.testing.create_account_channel_summary facade-accepts(account) 1+customer_analytics.Account products.customer_analytics.backend.facade.testing.create_account_relationship facade-accepts(account) 1+customer_analytics.Account products.customer_analytics.backend.facade.testing.create_custom_property_value facade-accepts(account) 1+customer_analytics.Account products.customer_analytics.backend.facade.testing.create_feature_request_account_link facade-accepts(account) 1+customer_analytics.Account products.customer_analytics.backend.facade.testing.create_meeting facade-accepts(account) 1+customer_analytics.AccountChannelSummary products.customer_analytics.backend.facade.testing.create_account_channel_summary facade-returns 1+customer_analytics.AccountRelationship products.customer_analytics.backend.facade.testing.create_account_relationship facade-returns 1+customer_analytics.AccountRelationshipDefinition products.customer_analytics.backend.facade.testing.create_account_relationship facade-accepts(definition) 1+customer_analytics.AccountRelationshipDefinition products.customer_analytics.backend.facade.testing.create_account_relationship_definition facade-returns 1+customer_analytics.CustomPropertyDefinition products.customer_analytics.backend.facade.testing.create_custom_property_definition facade-returns 1+customer_analytics.CustomPropertyDefinition products.customer_analytics.backend.facade.testing.create_custom_property_value facade-accepts(definition) 1+customer_analytics.CustomPropertyValue products.customer_analytics.backend.facade.testing.create_custom_property_value facade-returns 1+customer_analytics.CustomerTask products.customer_analytics.backend.facade.testing.create_customer_task facade-returns 1+customer_analytics.FeatureRequest products.customer_analytics.backend.facade.testing.create_feature_request facade-returns 1+customer_analytics.FeatureRequest products.customer_analytics.backend.facade.testing.create_feature_request_account_link facade-accepts(feature_request) 1+customer_analytics.FeatureRequest products.customer_analytics.backend.facade.testing.create_feature_request_history facade-accepts(feature_request) 1+customer_analytics.FeatureRequest products.customer_analytics.backend.facade.testing.create_feature_request_product_area_link facade-accepts(feature_request) 1+customer_analytics.FeatureRequestAccountLink products.customer_analytics.backend.facade.testing.create_feature_request_account_link facade-returns 1+customer_analytics.FeatureRequestAccountLink products.customer_analytics.backend.facade.testing.create_feature_request_evidence facade-accepts(account_link) 1+customer_analytics.FeatureRequestEvidence products.customer_analytics.backend.facade.testing.create_feature_request_evidence facade-returns 1+customer_analytics.FeatureRequestHistory products.customer_analytics.backend.facade.testing.create_feature_request_history facade-returns 1+customer_analytics.FeatureRequestProductArea products.customer_analytics.backend.facade.testing.create_feature_request_product_area facade-returns 1+customer_analytics.FeatureRequestProductArea products.customer_analytics.backend.facade.testing.create_feature_request_product_area_link facade-accepts(product_area) 1+customer_analytics.FeatureRequestProductAreaLink products.customer_analytics.backend.facade.testing.create_feature_request_product_area_link facade-returns 1+customer_analytics.Meeting products.customer_analytics.backend.facade.testing.create_meeting facade-returns 1+customer_analytics:backend/facade/hogql.py products.customer_analytics.backend.facade.hogql facade-logic 33customer_analytics:backend/hogql_queries/ posthog.api.test.test_sharing drives(AccountsQuery) 1dashboards.Dashboard ee.DashboardPrivilege.dashboard reverse-accessor(privileges) 1dashboards.Dashboard exports.ExportedAsset.dashboard reverse-accessor(exportedasset_set) 1@@ -45,8 +99,177 @@ dashboards.Dashboard posthog.SharingConfiguration.dashboard reverse-accessor(shadashboards.Dashboard posthog.TaggedItem.dashboard reverse-accessor(tagged_items) 1dashboards.Dashboard posthog.Team.primary_dashboard reverse-accessor(primary_dashboard_teams) 1dashboards.Dashboard product_analytics.Insight.dashboard reverse-accessor(items) 1+dashboards.Dashboard products.dashboards.backend.facade.api.InsightTilePlacement.__init__ facade-accepts(dashboards) 1+dashboards.Dashboard products.dashboards.backend.facade.api.tile_for_render facade-accepts(dashboard) 1+dashboards.Dashboard products.product_analytics.backend.facade.models.generate_insight_filters_hash facade-accepts(dashboard) 1+dashboards.DashboardTile products.dashboards.backend.facade.api.tile_for_insight_on_dashboard facade-returns 1+dashboards.DashboardTile products.dashboards.backend.facade.api.tile_for_render facade-returns 1+data_catalog.Metric products.data_catalog.backend.facade.api.approve_metric facade-accepts(metric) 1+data_catalog.Metric products.data_catalog.backend.facade.api.approve_metric facade-returns 1+data_catalog.Metric products.data_catalog.backend.facade.api.bulk_approve_metrics facade-accepts(metrics) 1+data_catalog.Metric products.data_catalog.backend.facade.api.bulk_approve_metrics facade-returns 1+data_catalog.Metric products.data_catalog.backend.facade.api.bulk_soft_delete_metrics facade-accepts(metrics) 1+data_catalog.Metric products.data_catalog.backend.facade.api.bulk_soft_delete_metrics facade-returns 1+data_catalog.Metric products.data_catalog.backend.facade.api.compute_drift facade-accepts(metrics) 1+data_catalog.Metric products.data_catalog.backend.facade.api.metrics_for_team facade-returns 1+data_catalog.Metric products.data_catalog.backend.facade.api.metrics_visible_to_user facade-returns 1+data_catalog.Metric products.data_catalog.backend.facade.api.refresh_metric_from_insight facade-accepts(metric) 1+data_catalog.Metric products.data_catalog.backend.facade.api.refresh_metric_from_insight facade-returns 1+data_catalog.Metric products.data_catalog.backend.facade.api.run_metric facade-accepts(metric) 1+data_catalog.Metric products.data_catalog.backend.facade.api.soft_delete_metric facade-accepts(metric) 1+data_catalog.Metric products.data_catalog.backend.facade.api.update_metric facade-accepts(metric) 1+data_catalog.Metric products.data_catalog.backend.facade.api.update_metric facade-returns 1+data_catalog.Metric products.data_catalog.backend.facade.api.upsert_metric facade-returns 1+data_catalog.RelationshipProposal products.data_catalog.backend.facade.api.accept_proposal facade-accepts(proposal) 1+data_catalog.RelationshipProposal products.data_catalog.backend.facade.api.accept_proposal facade-returns 1+data_catalog.RelationshipProposal products.data_catalog.backend.facade.api.propose_relationship facade-returns 1+data_catalog.RelationshipProposal products.data_catalog.backend.facade.api.reject_proposal facade-accepts(proposal) 1+data_catalog.RelationshipProposal products.data_catalog.backend.facade.api.reject_proposal facade-returns 1+data_catalog.RelationshipProposal products.data_catalog.backend.facade.api.relationships_for_team facade-returns 1+data_catalog.TableCertification products.data_catalog.backend.facade.api.certification_target_name facade-accepts(cert) 1+data_catalog.TableCertification products.data_catalog.backend.facade.api.certifications_for_team facade-returns 1+data_catalog.TableCertification products.data_catalog.backend.facade.api.certify facade-accepts(cert) 1+data_catalog.TableCertification products.data_catalog.backend.facade.api.certify facade-returns 1+data_catalog.TableCertification products.data_catalog.backend.facade.api.deprecate facade-accepts(cert) 1+data_catalog.TableCertification products.data_catalog.backend.facade.api.deprecate facade-returns 1+data_catalog.TableCertification products.data_catalog.backend.facade.api.propose_certification facade-returns 1+data_catalog.TableCertification products.data_catalog.backend.facade.api.revoke_certification facade-accepts(cert) 1+data_modeling.DAG products.data_modeling.backend.facade.api.sync_saved_query_to_dag facade-accepts(dag) 1+data_modeling.DataModelingJob products.data_modeling.backend.facade.api.latest_saved_query_materialization_job facade-returns 1data_modeling.DataWarehouseSavedQuery products.customer_analytics.backend.facade.api get_model 5+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.apply_saved_query_frequency_anchor facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.apply_saved_query_frequency_target facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.check_saved_query_frequency_target facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.compute_enrichment_hash facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.delete_node_from_dag facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.enrichment_gates_pass facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.is_saved_query_on_v2_schedule facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.latest_saved_query_materialization_job facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.materialize_saved_query facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.promote_view_nodes_to_matview facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.saved_query_materialized_at facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.suspension_state_for_saved_query facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.sync_saved_query_to_dag facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.unsuspend_saved_query facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.data_modeling.backend.facade.api.update_node_type facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.endpoints.backend.facade.temporal.prepare_executable_query facade-accepts(saved_query) 1+data_modeling.DataWarehouseSavedQuery products.warehouse_sources.backend.facade.hogql.get_view_or_table_by_name facade-returns 1+data_modeling.Node products.data_modeling.backend.facade.api.clear_node_suspension facade-accepts(node) 1+data_modeling.Node products.data_modeling.backend.facade.api.get_declared_target facade-accepts(node) 1+data_modeling.Node products.data_modeling.backend.facade.api.is_node_suspended facade-accepts(node) 1+data_modeling.Node products.data_modeling.backend.facade.api.mark_node_suspended facade-accepts(node) 1+data_modeling.Node products.data_modeling.backend.facade.api.set_declared_target facade-accepts(node) 1+data_modeling.Node products.data_modeling.backend.facade.api.start_node_materialization facade-accepts(node) 1+data_modeling.Node products.data_modeling.backend.facade.api.suspension_reset_at facade-accepts(node) 1+data_modeling.Node products.data_modeling.backend.facade.api.suspension_state facade-accepts(node) 1+data_modeling.Node products.data_modeling.backend.facade.api.sync_saved_query_to_dag facade-returns 1+data_modeling.Node products.data_modeling.backend.facade.api.unsuspend_nodes facade-accepts(nodes) 1+data_modeling.Node products.data_modeling.backend.facade.api.unsuspend_nodes facade-accepts(only_if) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.checks_for_subject facade-returns 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.edit_check facade-accepts(authorize) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.edit_check facade-accepts(check) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.edit_check facade-returns 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.live_subject_checks facade-accepts(checks) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.live_subject_checks facade-returns 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.readable_check_subjects facade-accepts(queryset) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.readable_check_subjects facade-returns 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.record_check_run facade-accepts(quality_check) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.soft_delete_check facade-accepts(check) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.subject_locations facade-accepts(checks) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.upsert_check facade-returns 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.visible_check_queryset facade-accepts(queryset) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.visible_check_queryset facade-returns 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.visible_checks facade-accepts(checks) 1+data_quality.DataQualityCheck products.data_quality.backend.facade.api.visible_checks facade-returns 1+data_quality.DataQualityCheckRun products.data_quality.backend.facade.api.record_check_run facade-returns 1+data_quality.DataQualitySuiteRun products.data_quality.backend.facade.api.empty_check_suite facade-returns 1+data_quality.DataQualitySuiteRun products.data_quality.backend.facade.api.record_check_run facade-accepts(suite_run) 1+data_quality.DataQualitySuiteRun products.data_quality.backend.facade.api.start_check_suite facade-returns 1+data_quality.TeamDataQualityConfig products.data_quality.backend.facade.api.get_gate_config facade-returns 1+data_quality.TeamDataQualityConfig products.data_quality.backend.facade.api.set_gate_materialization_on_checks facade-returns 1+data_warehouse.ManagedWarehouseBackfillPartition products.data_warehouse.backend.facade.backfill_status.stale_running_partitions facade-returns 1+django.Exists products.dashboards.backend.facade.api.insight_has_listed_tile facade-returns 1+django.HttpRequest products.demo.backend.facade.api.demo_route facade-accepts(request) 1+django.HttpRequest products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane facade-accepts(request) 1+django.HttpRequest products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane_status facade-accepts(request) 1+django.HttpRequest products.stamphog.backend.facade.webhooks.stamphog_github_webhook facade-accepts(request) 1+django.HttpResponse products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane facade-returns 1+django.HttpResponse products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane_status facade-returns 1+django.HttpResponse products.stamphog.backend.facade.webhooks.stamphog_github_webhook facade-returns 1+django.HttpResponse products.tasks.backend.facade.webhooks.handle_pull_request_event facade-returns 1+django.HttpResponse products.tasks.backend.facade.webhooks.handle_pull_request_review_event facade-returns 1+django.HttpResponseBase products.exports.backend.facade.api.get_export_asset_content_response facade-returns 1+django.JsonResponse products.notebooks.backend.facade.sql_v2.notebook_sql_v2_callback facade-returns 1+django.JsonResponse products.tasks.backend.facade.agent_proxy.agent_proxy_callback facade-returns 1+django.Model products.access_control.backend.facade.object_names.DisplayModel.__init__ facade-accepts(model) 1+django.Model products.access_control.backend.facade.object_names.model_has_field facade-accepts(model) 1+django.Model products.access_control.backend.facade.object_names.resources_with_object_access_controls facade-returns 1+django.Model products.access_control.backend.facade.resolution_preview.object_models facade-returns 1+django.Model products.access_control.backend.facade.subject_access_control.SubjectAccessControl.inherited_access_for_object facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.UserAccessControl.access_level_for_object facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.UserAccessControl.check_access_level_for_object facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.UserAccessControl.check_can_modify_access_levels_for_object facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.UserAccessControl.get_access_source_for_object facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.UserAccessControl.get_user_access_level facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.UserAccessControl.preload_object_access_controls facade-accepts(objects) 1+django.Model products.access_control.backend.facade.user_access_control.UserAccessControl.resolve_most_specific_object_access facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.UserAccessControl.specific_access_level_for_object facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.fallback_parent_object facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.fallback_parent_object facade-returns 1+django.Model products.access_control.backend.facade.user_access_control.fallback_parent_object_id facade-accepts(obj) 1+django.Model products.access_control.backend.facade.user_access_control.get_field_access_control_map facade-accepts(model_class) 1+django.Model products.access_control.backend.facade.user_access_control.model_to_resource facade-accepts(model) 1+django.Prefetch products.dashboards.backend.facade.api.tile_ids_prefetch facade-returns 1+django.Prefetch products.dashboards.backend.facade.api.tile_permissions_prefetch facade-returns 1+django.Prefetch products.warehouse_sources.backend.facade.models.latest_completed_job_prefetch facade-returns 1+django.Q products.data_quality.backend.facade.api.suites_backing_unreadable_runs_q facade-returns 1+django.Q products.data_quality.backend.facade.api.unreadable_suites_q facade-returns 1+django.Q products.tasks.backend.facade.api.general_channel_q facade-returns 1+django.Q products.tasks.backend.facade.api.get_latest_pr_url_by_task facade-accepts(conditions) 1+django.Q products.tasks.backend.facade.api.get_merged_pr_task_ids facade-accepts(conditions) 1+django.Q products.tasks.backend.facade.api.get_pull_requests_for_tasks facade-accepts(conditions) 1+django.Q products.tasks.backend.facade.api.latest_task_run_pr_merged_subquery facade-accepts(conditions) 1+django.Q products.tasks.backend.facade.api.latest_task_run_pr_url_subquery facade-accepts(conditions) 1+django.Q products.tasks.backend.facade.api.personal_channel_q facade-returns 1+django.Q products.tasks.backend.facade.api.task_ids_with_pr_url_subquery facade-accepts(conditions) 1+django.Q products.tasks.backend.facade.api.visible_channels_q facade-returns 1+django.Q products.tasks.backend.facade.api.visible_tasks_q facade-returns 1+django.QuerySet products.access_control.backend.facade.user_access_control.UserAccessControl.filter_and_annotate_file_system_queryset facade-accepts(queryset) 1+django.QuerySet products.access_control.backend.facade.user_access_control.UserAccessControl.filter_and_annotate_file_system_queryset facade-returns 1+django.QuerySet products.access_control.backend.facade.user_access_control.UserAccessControl.filter_queryset_by_access_level facade-accepts(queryset) 1+django.QuerySet products.access_control.backend.facade.user_access_control.UserAccessControl.filter_queryset_by_access_level facade-returns 1+django.QuerySet products.access_control.backend.facade.user_access_control.visible_teams_for_user facade-returns 1+django.QuerySet products.billing_alerts.backend.facade.api.visible_events_for_alert facade-returns 1+django.QuerySet products.dashboards.backend.facade.api.insight_ids_on_dashboard facade-returns 1+django.QuerySet products.data_catalog.backend.facade.api.certifications_for_team facade-returns 1+django.QuerySet products.data_catalog.backend.facade.api.metrics_for_team facade-returns 1+django.QuerySet products.data_catalog.backend.facade.api.metrics_visible_to_user facade-returns 1+django.QuerySet products.data_catalog.backend.facade.api.relationships_for_team facade-returns 1+django.QuerySet products.data_quality.backend.facade.activity.model_activity facade-accepts(queryset) 1+django.QuerySet products.data_quality.backend.facade.activity.model_activity facade-returns 1+django.QuerySet products.data_quality.backend.facade.api.checks_for_subject facade-returns 1+django.QuerySet products.data_quality.backend.facade.api.live_subject_checks facade-accepts(checks) 1+django.QuerySet products.data_quality.backend.facade.api.live_subject_checks facade-returns 1+django.QuerySet products.data_quality.backend.facade.api.readable_check_subjects facade-accepts(queryset) 1+django.QuerySet products.data_quality.backend.facade.api.readable_check_subjects facade-returns 1+django.QuerySet products.data_quality.backend.facade.api.visible_check_queryset facade-accepts(queryset) 1+django.QuerySet products.data_quality.backend.facade.api.visible_check_queryset facade-returns 1+django.QuerySet products.error_tracking.backend.facade.api.query_new_error_issues facade-returns 1+django.QuerySet products.legal_documents.backend.facade.api.annotate_signed_baa facade-accepts(queryset) 1+django.QuerySet products.legal_documents.backend.facade.api.annotate_signed_baa facade-returns 1+django.QuerySet products.product_analytics.backend.facade.api.with_last_viewed_at facade-accepts(insights) 1+django.QuerySet products.product_analytics.backend.facade.api.with_last_viewed_at facade-returns 1+django.QuerySet products.product_analytics.backend.facade.models.resolve_insight_by_id_or_short_id facade-accepts(queryset) 1+django.QuerySet products.stamphog.backend.facade.api.LazyDTOList.__init__ facade-accepts(queryset) 1+django.QuerySet products.tasks.backend.facade.api.task_ids_with_pr_url_subquery facade-returns 1+django.QuerySet products.tasks.backend.facade.loops.sandbox_environment_queryset facade-returns 1+django.Subquery products.tasks.backend.facade.api.latest_task_run_pr_merged_subquery facade-returns 1+django.Subquery products.tasks.backend.facade.api.latest_task_run_pr_url_subquery facade-returns 1endpoints.Endpoint posthog.TaggedItem.endpoint reverse-accessor(tagged_items) 1+endpoints.Endpoint products.endpoints.backend.facade.api.generate_openapi_spec facade-accepts(endpoint) 1+endpoints.Endpoint products.endpoints.backend.facade.api.validate_update_request facade-accepts(endpoint) 1+endpoints.EndpointVersion products.endpoints.backend.facade.api.build_materialization_info facade-accepts(version) 1+endpoints.EndpointVersion products.endpoints.backend.facade.api.generate_openapi_spec facade-accepts(version) 1error_tracking.ErrorTrackingIssue products.demo.backend.logic.products.hedgebox.matrix get_model 1error_tracking.ErrorTrackingIssue products.posthog_ai.evals.error_tracking.seeders get_model 1error_tracking.ErrorTrackingIssue products.reminders.backend.constants get_model 1@@ -56,6 +279,7 @@ error_tracking.ErrorTrackingIssueFingerprintV2 posthog.models.team.util get_modeerror_tracking.ErrorTrackingIssueFingerprintV2 products.demo.backend.logic.products.hedgebox.matrix get_model 1error_tracking.ErrorTrackingIssueFingerprintV2 products.posthog_ai.evals.error_tracking.seeders get_model 1error_tracking.ErrorTrackingStackFrame products.demo.backend.logic.products.hedgebox.matrix get_model 1+error_tracking:backend/facade/queries.py products.error_tracking.backend.facade.queries facade-logic 1error_tracking:backend/hogql_queries/ products.posthog_ai.eval_harness.test.test_eval_seeders drives(ErrorTrackingQueryRunner) 1error_tracking:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_insight_query drives(ErrorTrackingQuery) 1event_definitions.EventDefinition ee.EnterpriseEventDefinition.eventdefinition_ptr reverse-accessor(enterpriseeventdefinition) 1@@ -65,6 +289,7 @@ event_definitions.PropertyDefinition access_control.PropertyAccessControl.properevent_definitions.PropertyDefinition ee.EnterprisePropertyDefinition.propertydefinition_ptr reverse-accessor(enterprisepropertydefinition) 1event_definitions.PropertyDefinition posthog.MaterializedColumnSlot.property_definition reverse-accessor(materialized_column_slots) 1event_definitions.PropertyDefinition posthog.TaggedItem.property_definition reverse-accessor(tagged_items) 1+experiments.Experiment products.experiments.backend.facade.replay.resolve_in_session_exposure_semantics facade-accepts(experiment) 1experiments.ExperimentSavedMetric posthog.TaggedItem.experiment_saved_metric reverse-accessor(tagged_items) 1experiments:backend/hogql_queries/ ee.clickhouse.views.test.test_experiment_saved_metrics drives(ExperimentTrendsQuery) 2experiments:backend/hogql_queries/ posthog.session_recordings.queries.test.listing_recordings.test_session_recordings_list_by_experiment_exposure drives(ExposureQueryBuilder) 1@@ -74,18 +299,50 @@ experiments:backend/hogql_queries/ posthog.temporal.experiments.test_cache_warmiexperiments:backend/hogql_queries/ posthog.temporal.experiments.test_cache_warming drives(get_experiment_stats_method) 2experiments:backend/hogql_queries/ products.actions.backend.api.test.test_action drives(ExperimentTrendsQuery) 3exports.ExportedAsset posthog.ObjectMediaPreview.exported_asset reverse-accessor(object_previews) 1+exports.ExportedAsset products.exports.backend.facade.api.create_export_asset_async facade-returns 1+exports.ExportedAsset products.exports.backend.facade.api.get_export_asset facade-returns 1+exports.ExportedAsset products.exports.backend.facade.api.get_export_asset_content_response facade-accepts(asset) 1+exports.ExportedAsset products.exports.backend.facade.api.render_png_export facade-returns 1+exports.ExportedAsset products.exports.backend.facade.api.save_export_asset_content_from_file facade-accepts(asset) 1+exports.ExportedAsset products.exports.backend.facade.exporters.get_export_format_handler facade-returns 1+exports.ExportedAsset products.exports.backend.facade.exporters.register_export_format_handler facade-accepts(handler) 1feature_flags.FeatureFlag access_control.FeatureFlagRoleAccess.feature_flag reverse-accessor(access) 1feature_flags.FeatureFlag early_access_features.EarlyAccessFeature.feature_flag reverse-accessor(features) 1feature_flags.FeatureFlag experiments.Experiment.feature_flag reverse-accessor(experiment_set) 1feature_flags.FeatureFlag posthog.TaggedItem.feature_flag reverse-accessor(tagged_items) 1feature_flags.FeatureFlag product_tours.ProductTour.internal_targeting_flag reverse-accessor(product_tours_internal_targeting_flag) 1feature_flags.FeatureFlag product_tours.ProductTour.linked_flag reverse-accessor(product_tours_linked_flag) 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.archive_flag facade-accepts(flag) 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.archive_flag facade-returns 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.create_flag facade-returns 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.set_flag_active facade-accepts(flag) 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.set_flag_active facade-returns 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.ship_variant facade-accepts(flag) 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.ship_variant facade-returns 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.unarchive_flag facade-accepts(flag) 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.unarchive_flag facade-returns 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.update_flag facade-accepts(flag) 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.update_flag facade-returns 1+feature_flags.FeatureFlag products.feature_flags.backend.facade.api.user_can_edit_flag facade-accepts(flag) 1feature_flags.FeatureFlag surveys.Survey.internal_response_sampling_flag reverse-accessor(surveys_internal_response_sampling_flag) 1feature_flags.FeatureFlag surveys.Survey.internal_targeting_flag reverse-accessor(surveys_internal_targeting_flag) 1feature_flags.FeatureFlag surveys.Survey.linked_flag reverse-accessor(surveys_linked_flag) 1feature_flags.FeatureFlag surveys.Survey.targeting_flag reverse-accessor(surveys_targeting_flag) 1+mcp_store.MCPServerInstallation products.mcp_store.backend.facade.api.member_installation_for_host facade-returns 1metrics:backend/hogql_queries/ posthog.tasks.alerts.test.test_metrics_alerts drives(MetricsQuery) 1notebooks.Notebook posthog.SharingConfiguration.notebook reverse-accessor(sharing_configurations) 1+notebooks.Notebook products.notebooks.backend.facade.widgets.cancel_widget_generation facade-accepts(notebook) 1+notebooks.Notebook products.notebooks.backend.facade.widgets.get_widget_status facade-accepts(notebook) 1+notebooks.Notebook products.notebooks.backend.facade.widgets.infer_widget_inputs facade-accepts(notebook) 1+notebooks.Notebook products.notebooks.backend.facade.widgets.inspect_widget_inputs facade-accepts(notebook) 1+notebooks.Notebook products.notebooks.backend.facade.widgets.list_widget_versions facade-accepts(notebook) 1+notebooks.Notebook products.notebooks.backend.facade.widgets.read_widget_frame facade-accepts(notebook) 1+notebooks.Notebook products.notebooks.backend.facade.widgets.read_widget_source facade-accepts(notebook) 1+notebooks.Notebook products.notebooks.backend.facade.widgets.revert_widget_version facade-accepts(notebook) 1+notebooks.Notebook products.notebooks.backend.facade.widgets.start_widget_generation facade-accepts(notebook) 1+notebooks.NotebookNodeRun products.notebooks.backend.facade.widgets.inspect_widget_inputs facade-accepts(authorize_run) 1+notebooks.NotebookNodeRun products.notebooks.backend.facade.widgets.read_widget_frame facade-accepts(authorize_run) 1+notifications.NotificationEvent products.notifications.backend.facade.api.create_notification facade-returns 1posthog.Comment conversations.EmailThreadMessage.comment reverse-accessor(email_thread_message) 1posthog.CoreEvent marketing_analytics.MarketingAnalyticsGoalMapping.core_event reverse-accessor(marketing_goal_mappings) 1posthog.Integration slack_app.SlackSettings.default_integration reverse-accessor(slack_settings_as_default) 1@@ -336,6 +593,9 @@ product_analytics.Insight products.dashboards.backend.api.dashboard instance-manproduct_analytics.Insight products.dashboards.backend.api.dashboard passed-as-class(cast) 1product_analytics.Insight products.dashboards.backend.api.dashboard write(bulk_update) 1product_analytics.Insight products.dashboards.backend.api.dashboard write(update) 1+product_analytics.Insight products.dashboards.backend.facade.api.InsightTilePlacement.create_tiles facade-accepts(insight) 1+product_analytics.Insight products.dashboards.backend.facade.api.tile_for_render facade-accepts(insight) 1+product_analytics.Insight products.dashboards.backend.facade.api.update_insight_dashboard_membership facade-accepts(insight) 1product_analytics.Insight products.data_catalog.backend.logic.drift instance-many(filter) 1product_analytics.Insight products.data_catalog.backend.logic.drift instance-many(manager) 2product_analytics.Insight products.data_catalog.evals.seeders write(create) 3@@ -367,6 +627,8 @@ product_analytics.Insight products.reminders.backend.constants in-collection 1product_analytics.Insight products.slack_app.backend.slack_link_unfurl instance-single 1product_analytics.Insight products.surveys.backend.api.survey instance-single 1product_analytics.Insight surveys.Survey.linked_insight reverse-accessor(surveys_linked_insight) 1+product_analytics:backend/facade/models.py products.product_analytics.backend.facade.models facade-logic 1+product_analytics:backend/facade/queries.py products.product_analytics.backend.facade.queries facade-logic 1product_analytics:backend/hogql_queries/ ee.clickhouse.views.test.test_experiment_saved_metrics drives(TrendsQuery) 2product_analytics:backend/hogql_queries/ posthog.api.test.dashboards.test_dashboard drives(TrendsQuery) 6product_analytics:backend/hogql_queries/ posthog.api.test.test_alert_15_minute_interval drives(TrendsQuery) 1@@ -418,14 +680,92 @@ product_analytics:backend/hogql_queries/ products.web_analytics.backend.hogql_quproduct_analytics:backend/hogql_queries/ products.web_analytics.backend.hogql_queries.test.test_web_vitals_timeseries_lazy_precompute drives(TrendsQuery) 1product_analytics:backend/hogql_queries/ products.web_analytics.backend.hogql_queries.test.test_web_vitals_timeseries_lazy_precompute drives(TrendsQueryRunner) 1replay_vision.ReplayScanner posthog.TaggedItem.replay_scanner reverse-accessor(tagged_items) 1+rest_framework.Request products.dashboards.backend.facade.access.dashboard_access_method facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.accept_proposal facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.approve_metric facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.bulk_approve_metrics facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.bulk_soft_delete_metrics facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.certify facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.deprecate facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.propose_certification facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.propose_relationship facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.refresh_metric_from_insight facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.reject_proposal facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.revoke_certification facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.run_metric facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.soft_delete_metric facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.update_metric facade-accepts(request) 1+rest_framework.Request products.data_catalog.backend.facade.api.upsert_metric facade-accepts(request) 1+rest_framework.Request products.endpoints.backend.facade.api.generate_openapi_spec facade-accepts(request) 1+rest_framework.Request products.tasks.backend.facade.access.code_access_required_response facade-accepts(request) 1+rest_framework.Request products.tasks.backend.facade.client_provenance.get_task_client_provenance facade-accepts(request) 1+rest_framework.Request products.tasks.backend.facade.client_provenance.is_sandbox_oauth_request facade-accepts(request) 1+rest_framework.Response products.tasks.backend.facade.access.code_access_required_response facade-returns 1+rest_framework.Response products.tasks.backend.facade.access.compute_quota_limit_response facade-returns 1+rest_framework.Response products.tasks.backend.facade.access.usage_limit_response facade-returns 1signals.SignalReport tasks.Task.signal_report reverse-accessor(task) 1+stamphog:backend/facade/tasks.py products.stamphog.backend.facade.tasks facade-logic 1surveys.Survey product_tours.ProductTour.linked_surveys reverse-accessor(product_tours) 1surveys.Survey products.early_access_features.backend.management.commands.migrate_enrollments_to_waitlist_surveys get_model 1+tasks.Channel products.tasks.backend.facade.api.create_task_without_run facade-accepts(channel) 1+tasks.SandboxEnvironment products.tasks.backend.facade.loops.sandbox_environment_queryset facade-returns 1tasks.Task signals.SignalReportTask.task reverse-accessor(signal_report_tasks) 1tasks.Task slack_app.SlackThreadTaskMapping.task reverse-accessor(slack_thread_mappings) 1tasks.TaskRun products.review_hog.backend.receivers get_model 1+tasks.TaskRun products.tasks.backend.facade.api.post_artifact_thread_update facade-accepts(run) 1+tasks.TaskRun products.tasks.backend.facade.api.post_commits_pushed_thread_update facade-accepts(run) 1+tasks.TaskRun products.tasks.backend.facade.api.post_pr_created_thread_update facade-accepts(run) 1+tasks.TaskRun products.tasks.backend.facade.api.project_awaiting_input_activity facade-accepts(task_run) 1+tasks.TaskRun products.tasks.backend.facade.api.project_completed_activity facade-accepts(task_run) 1+tasks.TaskRun products.tasks.backend.facade.api.task_ids_with_pr_url_subquery facade-returns 1+tasks.TaskRun products.tasks.backend.facade.metrics.origin_product_label facade-accepts(task_run) 1tasks.TaskRun signals.SignalScoutRun.task_run reverse-accessor(signal_scout_run) 1tasks.TaskRun slack_app.SlackThreadTaskMapping.task_run reverse-accessor(slack_thread_mappings) 1+tasks.TaskThreadMessage products.tasks.backend.facade.api.project_thread_message_activity facade-accepts(message) 1+tasks:backend/facade/repo_selection.py products.tasks.backend.facade.repo_selection facade-logic 2+tasks:backend/facade/tasks.py products.tasks.backend.facade.tasks facade-logic 4+typing.Any products.billing_alerts.backend.facade.api.apply_destination_changes facade-accepts(request) 1+typing.Any products.billing_alerts.backend.facade.api.create_destination facade-accepts(request) 1+typing.Any products.data_modeling.backend.facade.api.deserialize_watermark facade-returns 1+typing.Any products.data_modeling.backend.facade.api.window_start facade-returns 1+typing.Any products.data_warehouse.backend.facade.api.reproject_direct_mysql_table facade-returns 1+typing.Any products.data_warehouse.backend.facade.api.reproject_direct_postgres_table facade-returns 1+typing.Any products.data_warehouse.backend.facade.api.reproject_direct_redshift_table facade-returns 1+typing.Any products.data_warehouse.backend.facade.api.reproject_direct_snowflake_table facade-returns 1+typing.Any products.error_tracking.backend.facade.api.auto_select_project_for_user facade-accepts(user) 1+typing.Any products.error_tracking.backend.facade.api.build_team_digest_data facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.api.get_crash_free_sessions facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.api.get_daily_exception_counts facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.api.get_exception_summary_for_team facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.api.get_new_issues_for_team facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.api.get_source_maps_recommendation_for_team facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.api.get_top_issues_for_team facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.issues.assign_issue facade-accepts(user) 1+typing.Any products.error_tracking.backend.facade.issues.bulk_update_issues facade-accepts(user) 1+typing.Any products.error_tracking.backend.facade.issues.update_issue facade-accepts(user) 1+typing.Any products.error_tracking.backend.facade.symbol_sets.bulk_check_upload facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.symbol_sets.bulk_finish_upload facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.symbol_sets.bulk_start_upload facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.symbol_sets.create_deprecated_symbol_set facade-accepts(team) 1+typing.Any products.error_tracking.backend.facade.symbol_sets.start_deprecated_upload facade-accepts(team) 1+typing.Any products.feature_flags.backend.facade.api.archive_flag facade-accepts(request) 1+typing.Any products.feature_flags.backend.facade.api.archive_flag facade-accepts(user) 1+typing.Any products.feature_flags.backend.facade.api.create_flag facade-accepts(request) 1+typing.Any products.feature_flags.backend.facade.api.create_flag facade-accepts(user) 1+typing.Any products.feature_flags.backend.facade.api.serialize_flags facade-returns 1+typing.Any products.feature_flags.backend.facade.api.set_flag_active facade-accepts(request) 1+typing.Any products.feature_flags.backend.facade.api.set_flag_active facade-accepts(user) 1+typing.Any products.feature_flags.backend.facade.api.ship_variant facade-accepts(request) 1+typing.Any products.feature_flags.backend.facade.api.ship_variant facade-accepts(user) 1+typing.Any products.feature_flags.backend.facade.api.unarchive_flag facade-accepts(request) 1+typing.Any products.feature_flags.backend.facade.api.unarchive_flag facade-accepts(user) 1+typing.Any products.feature_flags.backend.facade.api.update_flag facade-accepts(request) 1+typing.Any products.feature_flags.backend.facade.api.update_flag facade-accepts(user) 1+typing.Any products.feature_flags.backend.facade.api.user_can_edit_flag facade-accepts(user) 1+typing.Any products.notebooks.backend.facade.content.filter_notebook_content_for_sharing facade-returns 1+typing.Any products.signals.backend.facade.api.create_scout_for_source facade-accepts(request) 1+typing.Any products.signals.backend.facade.api.create_scout_for_source facade-accepts(user) 1+typing.Any products.tasks.backend.facade.agents.extract_json_from_text facade-returns 1user_interviews.IntervieweeContext posthog.SharingConfiguration.interviewee_context reverse-accessor(sharing_configurations) 1warehouse_sources.DataWarehouseCredential posthog.hogql.database.database instance-many(filter) 1warehouse_sources.DataWarehouseCredential products.data_warehouse.backend.presentation.views.table drf-model-serializer 1@@ -454,6 +794,19 @@ warehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_mysqwarehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_postgres write(create) 1warehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_redshift write(create) 1warehouse_sources.DataWarehouseTable products.data_warehouse.backend.direct_snowflake write(create) 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.hide_direct_mysql_table facade-accepts(table) 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.hide_direct_postgres_table facade-accepts(table) 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.hide_direct_redshift_table facade-accepts(table) 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.hide_direct_snowflake_table facade-accepts(table) 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.upsert_direct_mysql_table facade-accepts(existing_table) 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.upsert_direct_mysql_table facade-returns 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.upsert_direct_postgres_table facade-accepts(existing_table) 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.upsert_direct_postgres_table facade-returns 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.upsert_direct_redshift_table facade-accepts(existing_table) 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.upsert_direct_redshift_table facade-returns 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.upsert_direct_snowflake_table facade-accepts(existing_table) 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.api.upsert_direct_snowflake_table facade-returns 1+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.facade.hogql.get_warehouse_sync_warnings facade-accepts(warehouse_table) 1warehouse_sources.DataWarehouseTable products.data_warehouse.backend.logic.data_load.create_table instance-single 1warehouse_sources.DataWarehouseTable products.data_warehouse.backend.logic.data_load.create_table write(create) 1warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.column_annotation drf-field-queryset 1@@ -478,6 +831,7 @@ warehouse_sources.DataWarehouseTable products.marketing_analytics.backend.managewarehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder construct 1warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(bulk_create) 1warehouse_sources.DataWarehouseTable products.posthog_ai.evals.data_warehouse.seeder write(create) 1+warehouse_sources.ExternalDataJob products.data_warehouse.backend.facade.api.update_external_job_status facade-returns 1warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.data_load.source_templates instance-single 2warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.external_data_source.jobs lock 1warehouse_sources.ExternalDataJob products.data_warehouse.backend.logic.external_data_source.notifications instance-many(filter) 2@@ -495,6 +849,13 @@ warehouse_sources.ExternalDataSchema products.data_modeling.backend.logic.node_fwarehouse_sources.ExternalDataSchema products.data_warehouse.backend.clickhouse_helpers instance-many(exclude) 1warehouse_sources.ExternalDataSchema products.data_warehouse.backend.clickhouse_helpers instance-many(select_related) 1warehouse_sources.ExternalDataSchema products.data_warehouse.backend.direct_virtual_tables instance-many(order_by) 1+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.facade.api.bulk_create_external_data_job_schedules facade-accepts(schemas) 1+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.facade.api.get_or_create_webhook_hog_function facade-accepts(eligible_schemas) 1+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.facade.api.sync_external_data_job_workflow facade-accepts(external_data_schema) 1+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.facade.api.sync_external_data_job_workflow facade-returns 1+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.facade.api.trigger_external_data_workflow facade-accepts(external_data_schema) 1+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.facade.direct_query.build_direct_table_for_schema facade-accepts(schema) 1+warehouse_sources.ExternalDataSchema products.data_warehouse.backend.facade.direct_query.eligible_direct_query_schemas facade-returns 1warehouse_sources.ExternalDataSchema products.data_warehouse.backend.logic.data_load.service instance-many(exclude) 1warehouse_sources.ExternalDataSchema products.data_warehouse.backend.logic.external_data_source.jobs lock 1warehouse_sources.ExternalDataSchema products.data_warehouse.backend.logic.external_data_source.notifications instance-many(distinct) 1@@ -523,6 +884,7 @@ warehouse_sources.ExternalDataSchema products.data_warehouse.backend.temporal.hewarehouse_sources.ExternalDataSchema products.engineering_analytics.backend.logic.sources instance-many(select_related) 1warehouse_sources.ExternalDataSchema products.engineering_analytics.backend.management.commands.seed_engineering_analytics instance-single 1warehouse_sources.ExternalDataSchema products.engineering_analytics.backend.management.commands.seed_engineering_analytics write(create) 1+warehouse_sources.ExternalDataSchema products.managed_warehouse.backend.facade.api.duckgres_data_imports_table_name facade-accepts(schema) 1warehouse_sources.ExternalDataSchema products.managed_warehouse.backend.logic.connection write(get_or_create) 1warehouse_sources.ExternalDataSchema products.managed_warehouse.backend.temporal.ducklake_copy_data_imports_workflow instance-single 1warehouse_sources.ExternalDataSchema products.managed_warehouse.backend.temporal.ducklake_register_data_imports_workflow instance-single 2@@ -536,6 +898,26 @@ warehouse_sources.ExternalDataSource ee.hogai.tools.execute_sql.direct_connectiowarehouse_sources.ExternalDataSource posthog.hogql.database.database instance-many(filter) 1warehouse_sources.ExternalDataSource posthog.hogql.database.database instance-single 2warehouse_sources.ExternalDataSource posthog.hogql.direct_connection instance-single 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.apply_on_refresh facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.apply_on_schema_clear facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.reconcile_mysql_schemas facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.reconcile_postgres_schemas facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.reconcile_redshift_schemas facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.reconcile_refresh_name_substitutions facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.reconcile_snowflake_schemas facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.reproject_direct_mysql_table facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.reproject_direct_postgres_table facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.reproject_direct_redshift_table facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.reproject_direct_snowflake_table facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.source_namespace_is_blank facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.sync_cdc_extraction_schedule facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.sync_discover_schemas_schedule facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.trigger_external_data_source_workflow facade-accepts(external_data_source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.upsert_direct_mysql_table facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.upsert_direct_postgres_table facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.upsert_direct_redshift_table facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.api.upsert_direct_snowflake_table facade-accepts(source) 1+warehouse_sources.ExternalDataSource products.data_warehouse.backend.facade.direct_query.build_direct_table_for_schema facade-accepts(source) 1warehouse_sources.ExternalDataSource products.data_warehouse.backend.logic.managed_warehouse_data_status instance-many(filter) 1warehouse_sources.ExternalDataSource products.data_warehouse.backend.management.commands.backfill_discovery_schedules instance-many(exclude) 1warehouse_sources.ExternalDataSource products.data_warehouse.backend.management.commands.repair_qualified_schema_duplicates instance-many(filter) 1@@ -563,6 +945,12 @@ warehouse_sources.WarehouseColumnAnnotation products.data_warehouse.backend.preswarehouse_sources.WarehouseColumnAnnotation products.data_warehouse.backend.presentation.views.column_annotation instance-many(unscoped) 1warehouse_sources.WarehouseColumnAnnotation products.posthog_ai.evals.data_warehouse.seeder construct 2warehouse_sources.WarehouseColumnAnnotation products.posthog_ai.evals.data_warehouse.seeder write(bulk_create) 1+web_analytics.ContentAutopilotProposal products.web_analytics.backend.facade.content_autopilot.edit_proposal facade-returns 1+web_analytics.ContentAutopilotProposal products.web_analytics.backend.facade.content_autopilot.regenerate_proposal facade-returns 1+web_analytics.ContentAutopilotProposal products.web_analytics.backend.facade.content_autopilot.reject_proposal facade-returns 1+web_analytics.ContentAutopilotRun products.web_analytics.backend.facade.content_autopilot.cancel_run facade-returns 1+web_analytics.ContentAutopilotRun products.web_analytics.backend.facade.content_autopilot.start_run facade-returns 1+web_analytics.ContentAutopilotSiteProfile products.web_analytics.backend.facade.content_autopilot.delete_profile facade-returns 1web_analytics:backend/hogql_queries/ ee.clickhouse.views.test.test_experiment_saved_metrics drives(TrendsQuery) 2web_analytics:backend/hogql_queries/ posthog.api.test.dashboards.test_dashboard drives(TrendsQuery) 6web_analytics:backend/hogql_queries/ posthog.api.test.test_alert_15_minute_interval drives(TrendsQuery) 1diff --git a/tools/hogli-commands/hogli_commands/product/ast_helpers.py b/tools/hogli-commands/hogli_commands/product/ast_helpers.pyindex 0d04125be378..4f37643351de 100644--- a/tools/hogli-commands/hogli_commands/product/ast_helpers.py+++ b/tools/hogli-commands/hogli_commands/product/ast_helpers.py@@ -5,6 +5,8 @@ from __future__ import annotationsimport reimport astimport warnings+from collections.abc import Iterator, Sequence+from dataclasses import dataclassfrom pathlib import Path# Common suffixes/prefixes that contract dataclasses may use instead of mirroring the model name exactly.@@ -35,17 +37,27 @@ def get_imported_module_names(tree: ast.Module) -> set[str]:return imported-def _file_imports_django_models(tree: ast.Module) -> bool:- """Check whether a file imports from django.db.models (or django.db)."""- for node in ast.walk(tree):- if isinstance(node, ast.ImportFrom) and node.module:- if node.module.startswith("django.db"):- return True- elif isinstance(node, ast.Import):- if any(alias.name.startswith("django.db") for alias in node.names):- return True- return False-+# The bases a Django model reaches. `Model` is django.db.models.Model under both the bare and the+# `models.Model` spelling, because _base_names keeps the attribute and drops the module. The rest are+# the abstract bases posthog/models/utils.py and posthog/models/scoping/ export, every one of which+# subclasses models.Model itself. A base outside this list still counts once it resolves through+# another class of the product's own model modules, which is how a product's own abstract base and a+# proxy model are reached.+_DJANGO_MODEL_BASES: frozenset[str] = frozenset(+ {+ "BytecodeModelMixin",+ "CreatedMetaFields",+ "DeletedMetaFields",+ "Model",+ "ProductTeamModel",+ "RootTeamMixin",+ "TeamScopedRootMixin",+ "UpdatedMetaFields",+ "UUIDModel",+ "UUIDTClassicModel",+ "UUIDTModel",+ }+)# Base-name suffixes whose subclasses are value/manager helpers, never registered models._NON_MODEL_BASE_SUFFIXES = ("Choices", "Enum", "Manager", "QuerySet")@@ -76,32 +88,41 @@ def _is_abstract_model(node: ast.ClassDef) -> bool: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/.+@dataclass(frozen=True)+class _ModelCandidate:+ """One module-level class in a model module, with what decides whether it is a model.- 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.- """+ An abstract class stays a candidate because it is how its subclasses reach a Django base, but+ the registry never returns it, so it never becomes a name of its own."""++ name: str+ bases: tuple[str, ...]+ is_abstract: bool+++def _model_source_files(backend_dir: Path) -> list[Path]:+ """The product's model modules: backend/models.py, backend/models/, or both."""sources: list[Path] = []models_file = backend_dir / "models.py"models_dir = backend_dir / "models"if models_file.exists():sources.append(models_file)if models_dir.is_dir():- sources.extend(models_dir.rglob("*.py"))+ sources.extend(sorted(models_dir.rglob("*.py")))+ return sources- names: list[str] = []- for path in sources:++def _model_candidates(backend_dir: Path) -> list[_ModelCandidate]:+ """Every module-level class in the model modules that could be a registered model.++ Nested classes (Meta, TextChoices) are never registered, and neither are the+ choices/enum/manager/queryset subclasses, so both are out here.+ """+ candidates: list[_ModelCandidate] = []+ for path in _model_source_files(backend_dir):tree = ast_parse_safe(path)if not tree:continue- if not _file_imports_django_models(tree):- continue- # Module level only: nested classes (Meta, TextChoices) are never registered models.for node in tree.body:if not isinstance(node, ast.ClassDef):continue@@ -110,13 +131,39 @@ def get_model_names(backend_dir: Path) -> list[str]:continueif any(base.endswith(_NON_MODEL_BASE_SUFFIXES) for base in bases):continue- if _is_abstract_model(node):+ candidates.append(_ModelCandidate(node.name, tuple(bases), _is_abstract_model(node)))+ return candidates+++def get_model_names(backend_dir: Path) -> list[str]:+ """Return names of Django ORM model classes in backend/models.py and/or backend/models/.++ A class counts when one of its bases is a Django model base (_DJANGO_MODEL_BASES) or another+ class of these modules that already counts. The resolution repeats to a fixpoint, so it reaches+ a subclass of the product's own abstract base, and a proxy model, which sits in another module+ and names nothing but its concrete model as a base.++ Bases decide, and not the imports of the file, because a model module also holds classes that+ are not tables: the pydantic models a JSON field is validated against, the TypedDicts a query+ returns, and the errors the module raises. Excluded: abstract models (Meta.abstract = True) and+ choices/enum/manager/queryset subclasses, which the app registry never returns.+ """+ candidates = _model_candidates(backend_dir)+ reaches_model_base: set[str] = set()+ pending = True+ while pending:+ pending = False+ for candidate in candidates:+ if candidate.name in reaches_model_base:continue- names.append(node.name)- return names+ if not any(base in _DJANGO_MODEL_BASES or base in reaches_model_base for base in candidate.bases):+ continue+ reaches_model_base.add(candidate.name)+ pending = True+ return [c.name for c in candidates if c.name in reaches_model_base and not c.is_abstract]-def _decorator_name(node: ast.expr) -> str | None:+def decorator_name(node: ast.expr) -> str | None:"""The bare name of a decorator, with any call and any module prefix stripped."""target = node.func if isinstance(node, ast.Call) else nodeif isinstance(target, ast.Name):@@ -136,7 +183,7 @@ def _keyword_is(node: ast.expr, name: str, value: bool) -> bool:def _is_frozen_dataclass_decorator(node: ast.expr) -> bool:"""True for @dataclass(frozen=True) and for the house decorator, which is frozen by default."""- name = _decorator_name(node)+ name = decorator_name(node)if name == "dataclass":return _keyword_is(node, "frozen", True)if name == "frozen":@@ -198,20 +245,57 @@ def module_dunder_all(tree: ast.Module) -> set[str] | None:return None-def module_level_import_froms(tree: ast.Module) -> list[tuple[int, str | None, list[tuple[str, str | None]]]]:- """Every module-level `from ... import ...` as (level, module, [(name, asname)]).+# What a module-level assignment may bind that can name a type. A call, a dict or a literal binds a+# value, and expanding one where an annotation names it would read data as a type.+_TYPE_ALIAS_VALUES: tuple[type[ast.expr], ...] = (ast.Name, ast.Attribute, ast.Subscript, ast.BinOp)+++def _is_type_alias_annotation(node: ast.expr) -> bool:+ """True for the `TypeAlias` annotation, under both the bare and the `typing.TypeAlias` spelling."""+ return (isinstance(node, ast.Name) and node.id == "TypeAlias") or (+ isinstance(node, ast.Attribute) and node.attr == "TypeAlias"+ )+++def module_type_aliases(tree: ast.Module) -> dict[str, ast.expr]:+ """Module-level type aliases: {the name a module binds -> the expression it stands for}.- asname is None when no alias is given; `import Foo as Foo` yields ("Foo", "Foo") so callers- can tell the explicit self-alias re-export idiom apart from a plain import. Skips imports- nested in functions/classes (not module bindings) and inside `if TYPE_CHECKING:` blocks- (type-only, nothing crosses at runtime)."""- results: list[tuple[int, str | None, list[tuple[str, str | None]]]] = []+ All three spellings count: a plain `Handler = Callable[[Thing], None]`, the explicit+ `Handler: TypeAlias = ...`, and the PEP 695 statement `type Handler = ...`. An annotated+ assignment with any other annotation binds an ordinary module variable+ (`_handlers: dict[str, Handler] = {}`), which is data and not a type."""+ aliases: dict[str, ast.expr] = {}for node in ast.iter_child_nodes(tree):- if _is_type_checking_guard(node):+ if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):+ bound = node.targets[0].id+ elif (+ isinstance(node, ast.AnnAssign)+ and isinstance(node.target, ast.Name)+ and _is_type_alias_annotation(node.annotation)+ ):+ bound = node.target.id+ elif isinstance(node, ast.TypeAlias) and isinstance(node.name, ast.Name):+ bound = node.name.id+ else:continue- if isinstance(node, ast.ImportFrom):- results.append((node.level, node.module, [(alias.name, alias.asname) for alias in node.names]))- return results+ if isinstance(node.value, _TYPE_ALIAS_VALUES):+ aliases[bound] = node.value+ return aliases+++def module_level_import_nodes(tree: ast.Module, *, type_checking: bool = False) -> list[ast.Import | ast.ImportFrom]:+ """Every module-level import statement, in source order.++ An import nested in a function or a class binds no module name, so it is skipped. An import in+ an `if TYPE_CHECKING:` block binds no runtime object either, but it still names the type a+ signature promises, so `type_checking=True` includes it."""+ nodes: list[ast.Import | ast.ImportFrom] = []+ for node in ast.iter_child_nodes(tree):+ if isinstance(node, (ast.Import, ast.ImportFrom)):+ nodes.append(node)+ elif type_checking and isinstance(node, ast.If) and _is_type_checking_guard(node):+ nodes.extend(child for child in node.body if isinstance(child, (ast.Import, ast.ImportFrom)))+ return nodesdef lazy_reexport_map(tree: ast.Module) -> dict[str, str]:@@ -249,20 +333,55 @@ def lazy_reexport_map(tree: ast.Module) -> dict[str, str]:return mapping+def lazy_reexport_prefixes(tree: ast.Module) -> list[str]:+ """Module-level string constants a lazy map prepends to its values (`_B = "products.x.backend."`).++ A lazy map stores its source modules relative to some package, and the prefix constant is how+ the module says which. Every module-level string that ends in a dot is a candidate, so a caller+ tries each and keeps the one that names a real module."""+ return [+ node.value.value+ for node in ast.iter_child_nodes(tree)+ if isinstance(node, ast.Assign)+ and isinstance(node.value, ast.Constant)+ and isinstance(node.value.value, str)+ and node.value.value.endswith(".")+ ]+++def iter_public_callables(+ tree: ast.Module, *, include_init: bool = False+) -> Iterator[tuple[str, ast.FunctionDef | ast.AsyncFunctionDef]]:+ """(owning class, node) for every public callable a module defines at its top level or in a+ class body. The owning class is "" for a plain function, so a caller can spell a method as+ `Mapper.to_contract`. Nested definitions are not part of any call surface, so they are out.++ `include_init` adds `__init__` on a public class. A constructor takes what the caller hands the+ class, so it is part of the call surface, while every other underscore name is a helper."""+ for node in ast.iter_child_nodes(tree):+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and not node.name.startswith("_"):+ yield "", node+ elif isinstance(node, ast.ClassDef):+ for child in ast.iter_child_nodes(node):+ if not isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):+ continue+ if not child.name.startswith("_") or (include_init and child.name == "__init__"):+ yield node.name, child++def get_public_function_names(file_path: Path) -> list[str]:"""Return names of public top-level and class-level functions/methods (not nested)."""tree = ast_parse_safe(file_path)if not tree:return []- names: list[str] = []- for node in ast.iter_child_nodes(tree):- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and not node.name.startswith("_"):- names.append(node.name)- elif isinstance(node, ast.ClassDef):- for child in ast.iter_child_nodes(node):- if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)) and not child.name.startswith("_"):- names.append(child.name)- return names+ return [node.name for _, node in iter_public_callables(tree)]+++def module_has_prefix(module: str, prefixes: Sequence[str]) -> bool:+ """True when a dotted module name is one of `prefixes` or sits under one.++ Anchored on the dot, so `django.dbrouter` does not read as `django.db`."""+ return any(module == p or module.startswith(p + ".") for p in prefixes)def imports_any(file_path: Path, prefixes: list[str]) -> bool:@@ -272,10 +391,10 @@ def imports_any(file_path: Path, prefixes: list[str]) -> bool:return Falsefor node in ast.walk(tree):if isinstance(node, ast.ImportFrom) and node.module:- if any(node.module == p or node.module.startswith(p + ".") for p in prefixes):+ if module_has_prefix(node.module, prefixes):return Trueelif isinstance(node, ast.Import):- if any(alias.name == p or alias.name.startswith(p + ".") for alias in node.names for p in prefixes):+ if any(module_has_prefix(alias.name, prefixes) for alias in node.names):return Truereturn Falsediff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex cd0bdfe7e5fd..c6a508dcc11d 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -17,10 +17,13 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom .ast_helpers import module_import_targets-from .crossings import driven_wiring_locations+from .crossings import driven_wiring_locations, facade_shape_use, recorded_facade_shape_rowsfrom .isolation import (+ GARAGE_PREFIXES,+ FacadeShapeFinding,IsolationStatus,compute_isolation_status,+ facade_shape_findings,has_legacy_interface_leaks,has_routes_module,has_tach_interface,@@ -895,8 +898,8 @@ class IsolationChainCheck(ProductCheck):driven = [g for g in status.unwatched_garages if g in status.driven_wiring_locations]evidence = (f" Tests outside the product still execute what lives in {', '.join(driven)}: see the "- f"`{ctx.name}:` drives lines in products/model_crossing_uses_baseline.txt, and move those "- "tests into the product to drop the input."+ f"`{ctx.name}:` lines with a `drives(...)` kind in products/model_crossing_uses_baseline.txt, "+ "and move those tests into the product to drop the input."if drivenelse "")@@ -961,6 +964,74 @@ class IsolationChainCheck(ProductCheck):return result+_CROSSING_LEDGER = "products/model_crossing_uses_baseline.txt"++# The remedy the lint prints per finding kind. Each one is the move that removes the row, not advice+# to think about the row. The rule is products/architecture.md § Facades: The Public Interface.+_FACADE_SHAPE_REMEDIES: dict[str, str] = {+ "returns": "return a frozen contract from facade/contracts.py instead of the ORM object",+ "accepts": "take ids and contracts, so the caller never holds a Django or a DRF object "+ "(an `Any` row on team, request or user hides one behind the annotation)",+ "logic": f"move each body to the wiring location that owns it ({', '.join(GARAGE_PREFIXES)}) "+ "and leave the re-export in the facade",+}+++def _facade_shape_issue(finding: FacadeShapeFinding) -> str:+ """The lint line for one finding: where it is, what it is, and the move that removes it."""+ if finding.kind == "logic":+ what = f"holds {finding.count} definition(s) with a body: {', '.join(finding.bodies)}"+ else:+ symbol = f"{finding.symbol}({finding.parameter})" if finding.parameter else finding.symbol+ what = f"{finding.kind} {finding.source}.{finding.type_name} at {symbol}"+ return (+ f"facade/{finding.facade_module} {what} — {_FACADE_SHAPE_REMEDIES[finding.kind]}. "+ "The ledger only shrinks, so this is not a row to add"+ )+++class FacadeShapeCheck(ProductCheck):+ """Read what the facade accepts and returns, not only what it imports.++ tach and import-linter work on the import graph, so a facade that imports its model module to+ build contracts and one that returns the model from a public function look identical to them.+ A model or a QuerySet on the boundary gives the caller managers, save()/delete(), and FK+ descriptors that query on attribute access, so the caller reaches the whole database through a+ function the doctrine says returns data. A DRF or a Django HTTP type means the facade knows the+ transport, which belongs in presentation/.++ Runs in both lint modes. A lenient product with a facade folder is exactly where the drawer+ forms: the folder is public by location while nothing holds its shape.++ The findings are ratcheted as the `facade-*` kinds of the model-crossing ledger, next to the+ other couplings the import graph cannot see. Only the unrecorded direction blocks here: a row+ whose finding is gone is caught by the repo-invariant test, which compares the whole file+ against a fresh scan.+ """++ label = "facade shape"++ def should_run(self, ctx: CheckContext) -> bool:+ return super().should_run(ctx) and (ctx.backend_dir / "facade").is_dir()++ def run(self, ctx: CheckContext) -> CheckResult:+ findings = facade_shape_findings(ctx.backend_dir, ctx.name)+ recorded = recorded_facade_shape_rows(ctx.name)+ unrecorded = [f for f in findings if facade_shape_use(f).as_baseline_line() not in recorded]++ result = CheckResult(file=f"products/{ctx.name}/backend/facade")+ result.issues.extend(_facade_shape_issue(f) for f in unrecorded)++ if result.issues:+ result.lines = [f"✗ {len(result.issues)} issue(s)"] + [f" → {i}" for i in result.issues]+ elif recorded:+ result.warnings.append(f"facade shape debt: {len(recorded)} row(s) in {_CROSSING_LEDGER}")+ result.lines = [f"⚠ facade shape debt: {len(recorded)} rows"]+ else:+ result.lines = ["✓ ok"]+ return result++class ProductYamlCheck(ProductCheck):"""Validates product.yaml exists, parses, and has correct field types."""@@ -1182,5 +1253,6 @@ CHECKS: list[ProductCheck] = [FileFolderConflictsCheck(),TachCheck(),IsolationChainCheck(),+ FacadeShapeCheck(),OrphanedTestFilesCheck(),]diff --git a/tools/hogli-commands/hogli_commands/product/crossings.py b/tools/hogli-commands/hogli_commands/product/crossings.pyindex 1d098099b323..9dc829078b82 100644--- a/tools/hogli-commands/hogli_commands/product/crossings.py+++ b/tools/hogli-commands/hogli_commands/product/crossings.py@@ -38,6 +38,13 @@ The fourth channel does not read source at all. A relation field that crosses awithout `related_name="+"` adds a reverse accessor to the target class — no import, no name-leveluse, only the model registry can see it. reverse_accessors.py walks the graph; each edge is countedas the disallowed kind `reverse-accessor(<name>)`.++The fifth channel reads the other end of the boundary: what a facade signature promises. An import+linter sees the same edge whether a facade imports a model module to build contracts or to return+the model, so publicness has to come from the shape of the API and not from the location of the+file. isolation.py reads the signatures; each finding lands as one of the disallowed kinds+`facade-returns`, `facade-accepts(<parameter>)` and `facade-logic`. The rule is+products/architecture.md § Facades: The Public Interface."""from __future__ import annotations@@ -53,9 +60,15 @@ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequencefrom dataclasses import dataclassfrom pathlib import Path-from .ast_helpers import ast_parse_safe, get_model_names, lazy_reexport_map-from .isolation import COMPUTED_WIRING_LOCATIONS, MODEL_CROSSINGS, facade_model_crossings-from .paths import PRODUCTS_DIR, REPO_ROOT+from .ast_helpers import ast_parse_safe, get_model_names, lazy_reexport_map, lazy_reexport_prefixes+from .isolation import (+ COMPUTED_WIRING_LOCATIONS,+ MODEL_CROSSINGS,+ FacadeShapeFinding,+ facade_model_crossings,+ facade_shape_findings,+)+from .paths import PRODUCTS_DIR, REPO_ROOT, backend_product_dirsfrom .reverse_accessors import reverse_accessor_edge_lines# Where Python that can consume a product model lives. Everything else at the repo root is@@ -142,7 +155,9 @@ class CrossingUse:"""One kind of use of one crossing class in one consumer module, with how often it appears.`reverse-accessor(...)` rows overload `consumer_module` with the relation declaration- (`app.Model.field`) — a path into the model graph, not an importable module."""+ (`app.Model.field`) — a path into the model graph, not an importable module. A `facade-returns`+ or `facade-accepts` row overloads it with the facade symbol that carries the type+ (`...facade.api.read`)."""crossing: str # CrossingClass.labelconsumer_module: str # dotted, e.g. "products.product_analytics.backend.presentation.insight"@@ -858,14 +873,7 @@ def _lazy_reexports(tree: ast.Module, product: str, exists: Callable[[str], boolLazy maps store their values relative to some package: absolute, relative to the product'sbackend package, or relative to a module-level prefix constant (`_B = "products....hogql_queries."`).The first candidate that names a real module wins."""- prefixes = [- node.value.value- for node in tree.body- if isinstance(node, ast.Assign)- and isinstance(node.value, ast.Constant)- and isinstance(node.value.value, str)- and node.value.value.endswith(".")- ]+ prefixes = lazy_reexport_prefixes(tree)resolved: dict[str, str] = {}for name, value in lazy_reexport_map(tree).items():candidates = [value, *(prefix + value for prefix in prefixes), f"products.{product}.backend.{value}"]@@ -1408,13 +1416,32 @@ def driven_wiring_locations(product: str, path: Path | None = None) -> frozenset"""The computed wiring locations of `product` that a test outside the product drives.Read from the crossings baseline. The baseline is the evidence the lint reads: the repo-invariant- test keeps it equal to a fresh scan, so a location with no line here has no outside driver."""+ test keeps it equal to a fresh scan, so a location with no line here has no outside driver. The+ kind has to be read too, because a `facade-logic` line is keyed by a location as well."""prefix = f"{product}:"- return frozenset(- line.split(" ", 1)[0].removeprefix(prefix)- for line in _baseline_lines(path or BASELINE_PATH)- if line.startswith(prefix)- )+ locations: set[str] = set()+ for line in _baseline_lines(path or BASELINE_PATH):+ if not line.startswith(prefix):+ continue+ crossing, _, kind, _ = line.split(" ")+ if kind.startswith("drives("):+ locations.add(crossing.removeprefix(prefix))+ return frozenset(locations)+++def recorded_facade_shape_rows(product: str, path: Path | None = None) -> frozenset[str]:+ """The `facade-*` baseline lines standing for one product's facade.++ Read from the baseline for the same reason as the wiring locations above: the repo-invariant+ test keeps the file equal to a fresh scan."""+ prefix = f"products.{product}.backend.facade."+ rows: set[str] = set()+ for line in _baseline_lines(path or BASELINE_PATH):+ if " facade-" not in line:+ continue+ if line.split(" ")[1].startswith(prefix):+ rows.add(line)+ return frozenset(rows)@functools.lru_cache(maxsize=4)@@ -1619,9 +1646,48 @@ def reverse_accessor_uses(products: Iterable[str] | None = None) -> list[Crossinreturn uses+# ---------------------------------------------------------------------------+# Facade shapes — the fifth channel, read from the facade signatures+# ---------------------------------------------------------------------------+++def facade_shape_use(finding: FacadeShapeFinding) -> CrossingUse:+ """One facade shape finding as a baseline row.++ The crossing slot names what crosses: the qualified type for a signature row, and the facade+ module for a `logic` row, which is keyed by a location the way `drives(...)` is. The consumer+ slot holds the facade symbol that carries the type, or the module itself for a `logic` row whose+ count is the number of bodies left in it. The parameter of an `accepts` row rides in the kind,+ the way the other detail-carrying kinds do.+ """+ if finding.kind == "logic":+ crossing = wiring_location_label(finding.product, f"backend/facade/{finding.facade_module}")+ consumer = finding.dotted_module+ else:+ crossing = f"{finding.source}.{finding.type_name}"+ consumer = f"{finding.dotted_module}.{finding.symbol}"+ kind = f"facade-{finding.kind}({finding.parameter})" if finding.parameter else f"facade-{finding.kind}"+ return CrossingUse(crossing, consumer, kind, finding.count)+++def facade_shape_uses(products: Iterable[str] | None = None) -> list[CrossingUse]:+ """What every product facade puts on its boundary, as CrossingUse rows.++ A finding belongs to the facade that carries it, so a product filter selects the facades to+ read — the same one-sided scoping the reverse accessors use.+ """+ wanted = set(products) if products is not None else None+ return [+ facade_shape_use(finding)+ for product_dir in backend_product_dirs()+ if wanted is None or product_dir.name in wanted+ for finding in facade_shape_findings(product_dir / "backend", product_dir.name)+ ]++def all_crossing_uses(products: Iterable[str] | None = None) -> list[CrossingUse]:- """Every channel: the three AST scans plus the model-graph reverse accessors."""- return scan_crossing_uses(products) + reverse_accessor_uses(products)+ """Every channel: the three AST scans, the model-graph reverse accessors, and the facade shapes."""+ return scan_crossing_uses(products) + reverse_accessor_uses(products) + facade_shape_uses(products)# ---------------------------------------------------------------------------@@ -1695,9 +1761,11 @@ NEW_LINE_INSTRUCTION = ('related_name="+" (a query:<name> row means an explicit related_query_name keeps filter() '"traversal alive); seal it, remove the explicit query name, and give callers a facade read ""function. A 'drives(...)' line is a test outside the product that executes one of its query "- "runners; move that test into the product. A coupling that must stand is a doctrine amendment: "- "hand-edit the line in, and record why in products/architecture.md § Wiring couplings. "- "Regenerating the baseline cannot add a line."+ "runners; move that test into the product. A 'facade-...' line is a facade that puts a Django, a "+ "DRF or an ORM type on its own boundary, or a capability submodule that holds bodies; the "+ "lint prints the move that clears each kind. A coupling that "+ "must stand is a doctrine amendment: hand-edit the line in, and record why in "+ "products/architecture.md § Wiring couplings. Regenerating the baseline cannot add a line.")BASELINE_HEADER = f"""\@@ -1705,7 +1773,7 @@ BASELINE_HEADER = f"""\# One line per (product.Class, consumer module, kind, count); see products/architecture.md# § Wiring couplings for which shapes are allowed.#-# Four channels land here. Name-level uses of a watched-models crossing class, in any kind the+# Five channels land here. Name-level uses of a watched-models crossing class, in any kind the# doctrine does not call instance-free. 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: a migration reaches a model through the@@ -1721,6 +1789,13 @@ BASELINE_HEADER = f"""\# related_name="+", remove any explicit related_query_name (a query:<name> row means one keeps# filter() traversal alive), and delete the line in the same change; a caller that needs reverse# access gets a facade read function. See products/architecture.md § Cross-product foreign keys.+# And the `facade-*` kinds, read from the facade signatures rather than from a caller: what the+# boundary itself promises. `facade-returns` and `facade-accepts(<parameter>)` mean a public facade+# callable puts a Django, a DRF or an ORM type on its signature; `facade-logic` means a capability+# submodule holds bodies rather than re-exports, and its count is how many are left. The first+# column says what crosses — `<product>.<Class>`, `<library>.<Type>`, or the facade module for a+# `facade-logic` line — and the consumer column holds the symbol or the module that carries it.+# The rule is products/architecture.md § Facades: The Public Interface.## Counts may only go down, and a line that disappears must be deleted here too.#diff --git a/tools/hogli-commands/hogli_commands/product/import_resolution.py b/tools/hogli-commands/hogli_commands/product/import_resolution.pynew file mode 100644index 000000000000..013ad6a9116b--- /dev/null+++ b/tools/hogli-commands/hogli_commands/product/import_resolution.py@@ -0,0 +1,211 @@+"""Where an imported name lives.++Every facade scan asks one question of an import: which module the alias comes from, whether it+names a submodule or a symbol, and which file holds it when the module is the product's own. One+answer here keeps the scans from disagreeing about the same import.+"""++from __future__ import annotations++import re+import ast+import functools+from collections.abc import Iterator, Sequence+from dataclasses import dataclass+from pathlib import Path++from .ast_helpers import module_level_import_nodes++# An absolute import into any product's backend package, with the module inside it. The tail is+# optional so that the backend package itself resolves: `from products.x.backend import tasks`+# reads that directory.+PRODUCT_BACKEND_RE = re.compile(r"^products\.([A-Za-z0-9_]+)\.backend(?:\.(.+))?$")+++def product_backend_root(backend_dir: Path) -> str:+ """The product's own backend package as a dotted prefix, e.g. 'products.metrics.backend'."""+ return f"products.{backend_dir.parent.name}.backend"+++def module_package_parts(source_path: str) -> list[str]:+ """The package a module belongs to, as backend-relative parts, for resolving relative imports.++ 'backend/facade/queries.py' -> ['facade'] (its container); 'backend/logic/matrix/' (a package,+ trailing slash) -> ['logic', 'matrix'] (a package's relative imports are rooted at itself)."""+ trimmed = source_path.removeprefix("backend/")+ if trimmed.endswith("/"):+ return [p for p in trimmed.strip("/").split("/") if p]+ return trimmed.rsplit("/", 1)[0].split("/") if "/" in trimmed else []+++def resolve_relative(package_parts: Sequence[str], level: int, module: str | None) -> str | None:+ """A relative import from a package -> its module path relative to backend, or None if it climbs+ above backend/ (nothing there is product-internal to this backend). level 1 is the package+ itself, level 2 its parent, etc."""+ climb = level - 1+ if climb > len(package_parts):+ return None+ remaining = list(package_parts[: len(package_parts) - climb])+ if module:+ remaining = remaining + module.split(".")+ return "/".join(remaining)+++def resolve_absolute_module(module: str, backend_dir: Path) -> str | None:+ """An absolute import -> its module path relative to backend_dir, or None if it's not this+ product's backend (third-party, core, or another product all return None)."""+ root = product_backend_root(backend_dir)+ if module == root:+ return ""+ if module.startswith(root + "."):+ return module[len(root) + 1 :].replace(".", "/")+ return None+++def backend_rel_path(module_rel: str, backend_dir: Path) -> str | None:+ """A module path relative to backend_dir -> a backend-relative on-disk path, or None.++ Resolves to the file that actually holds definitions: 'models' -> 'backend/models.py' if that+ file exists, else 'backend/models/' for a package. The trailing slash on a package lets the+ result be prefix-tested against GARAGE_PREFIXES the same way an input glob is."""+ if module_rel == "":+ return "backend/"+ file_path = backend_dir / f"{module_rel}.py"+ if file_path.is_file():+ return f"backend/{module_rel}.py"+ dir_path = backend_dir / module_rel+ if dir_path.is_dir():+ return f"backend/{module_rel}/"+ return None+++def source_file(source_path: str, backend_dir: Path) -> Path:+ """The on-disk file for a backend-relative module path (a package resolves to its __init__.py)."""+ if source_path.endswith("/"):+ return backend_dir.parent / source_path.rstrip("/") / "__init__.py"+ return backend_dir.parent / source_path+++def _submodule_names(directory: Path) -> frozenset[str]:+ """The submodule names a package directory holds, read once per directory.++ The listing is read rather than the path asked for, because a case-insensitive filesystem+ answers `Account.py` with `account.py` and would turn every model class into a module alias.+ One run of a scan never writes to the tree it reads, so the listing is memoized for the process.+ """+ if not directory.is_dir():+ return frozenset()+ names = set()+ for entry in directory.iterdir():+ if entry.is_dir():+ names.add(entry.name)+ elif entry.name.endswith(".py"):+ names.add(entry.name.removesuffix(".py"))+ return frozenset(names)+++def _package_directory(package: str, backend_dir: Path) -> Path | None:+ """The directory a `from <package> import ...` reads, for a package that is on disk here.++ That is any product's backend, the scanned one included. A library package is not in this tree,+ so it has no directory."""+ match = PRODUCT_BACKEND_RE.match(package)+ if match is None:+ return None+ product, backend_module = match.groups()+ products_dir = backend_dir.parent.parent+ return products_dir / product / "backend" / (backend_module or "").replace(".", "/")+++def _package_module(level: int, module: str | None, package_parts: Sequence[str], backend_dir: Path) -> str | None:+ """The dotted module an import reads, with a relative one resolved to its absolute spelling.++ None when a relative import climbs above the product's backend, where nothing is+ product-internal to this backend."""+ if level == 0:+ return module or ""+ module_rel = resolve_relative(package_parts, level, module)+ if module_rel is None:+ return None+ root = product_backend_root(backend_dir)+ return f"{root}.{module_rel.replace('/', '.')}" if module_rel else root+++def _binds_submodule(package: str, name: str, backend_dir: Path) -> bool:+ """True when a `from <package> import <name>` binds a submodule rather than a symbol.++ A package in this tree is decided by its directory listing. A library package is not here, so+ the PEP 8 spelling decides instead: `from rest_framework import request` binds a module and+ `from rest_framework.request import Request` binds a type."""+ directory = _package_directory(package, backend_dir)+ if directory is None:+ return name[:1].islower()+ return name in _submodule_names(directory)+++def _alias_source_path(package: str, name: str, binds_submodule: bool, backend_dir: Path) -> str | None:+ """The backend-relative path of what an alias names, for the scanned product's backend only.++ Another product's module and a library both resolve to None, so a scan that follows a name+ stops at the product boundary."""+ module_rel = resolve_absolute_module(package, backend_dir)+ if module_rel is None:+ return None+ if binds_submodule:+ module_rel = f"{module_rel}/{name}" if module_rel else name+ return backend_rel_path(module_rel, backend_dir)+++@dataclass(frozen=True)+class ImportedName:+ """One alias of one module-level `from ... import ...`, resolved to where it lives."""++ original: str # the name at the source+ asname: str | None # the alias as written; `import Foo as Foo` is the explicit re-export idiom+ package: str # the dotted module the import reads, e.g. "django.db" or "products.x.backend.logic"+ binds_submodule: bool # the alias names a module of that package rather than a symbol+ source_path: str | None # backend-relative path of what the alias names, this backend only++ @property+ def bound(self) -> str:+ """The name the importing module binds, which is what a consumer imports from it."""+ return self.asname or self.original++ @property+ def submodule(self) -> str:+ """The dotted module the alias names if it names a submodule, spelled whether it does or not.++ `from django.db import models` names a package that is not on disk here, so a caller that+ must decide module-ness from the dotted name alone reads this instead of binds_submodule."""+ return f"{self.package}.{self.original}"+++def iter_imported_names(+ node: ast.ImportFrom, package_parts: Sequence[str], backend_dir: Path+) -> Iterator[ImportedName]:+ """Every name one `from ... import ...` binds, resolved to the module that holds it.++ A relative import that climbs above the product's backend binds nothing any scan here reads, so+ it yields nothing at all."""+ package = _package_module(node.level, node.module, package_parts, backend_dir)+ if package is None:+ return+ for alias in node.names:+ binds_submodule = _binds_submodule(package, alias.name, backend_dir)+ yield ImportedName(+ original=alias.name,+ asname=alias.asname,+ package=package,+ binds_submodule=binds_submodule,+ source_path=_alias_source_path(package, alias.name, binds_submodule, backend_dir),+ )+++def iter_module_imported_names(+ tree: ast.Module, package_parts: Sequence[str], backend_dir: Path+) -> Iterator[ImportedName]:+ """Every name the module-level `from ... import ...` statements of a module bind."""+ for node in module_level_import_nodes(tree):+ if isinstance(node, ast.ImportFrom):+ yield from iter_imported_names(node, package_parts, backend_dir)diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex e5938cb230a0..8a30b0c13c02 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -24,19 +24,34 @@ import astimport jsonimport tomllibimport functools-from collections.abc import Iterator+from collections.abc import Iterator, Sequencefrom dataclasses import dataclassfrom pathlib import Pathfrom .ast_helpers import (ast_parse_safe,+ decorator_name,get_imported_module_names,+ get_model_names,has_any_function_defs,+ iter_public_callables,lazy_reexport_map,+ lazy_reexport_prefixes,module_dunder_all,- module_level_import_froms,+ module_has_prefix,+ module_level_import_nodes,+ module_type_aliases,tree_has_top_level_functions,)+from .import_resolution import (+ PRODUCT_BACKEND_RE,+ backend_rel_path,+ iter_imported_names,+ iter_module_imported_names,+ module_package_parts,+ resolve_absolute_module,+ source_file,+)from .paths import REPO_ROOT, TACH_TOML, get_tach_block# ---------------------------------------------------------------------------@@ -551,70 +566,6 @@ class FacadeClassImport:source_path: str # backend-relative, e.g. "backend/metrics_query_runner.py"-def _product_backend_root(backend_dir: Path) -> str:- """The product's own backend package as a dotted prefix, e.g. 'products.metrics.backend'."""- return f"products.{backend_dir.parent.name}.backend"---def _module_package_parts(source_path: str) -> list[str]:- """The package a module belongs to, as backend-relative parts, for resolving relative imports.-- 'backend/facade/queries.py' -> ['facade'] (its container); 'backend/logic/matrix/' (a package,- trailing slash) -> ['logic', 'matrix'] (a package's relative imports are rooted at itself)."""- trimmed = source_path.removeprefix("backend/")- if trimmed.endswith("/"):- return [p for p in trimmed.strip("/").split("/") if p]- return trimmed.rsplit("/", 1)[0].split("/") if "/" in trimmed else []---def _resolve_relative(package_parts: list[str], level: int, module: str | None) -> str | None:- """A relative import from a package -> its module path relative to backend, or None if it climbs- above backend/ (nothing there is product-internal to this backend). level 1 is the package- itself, level 2 its parent, etc."""- climb = level - 1- if climb > len(package_parts):- return None- remaining = package_parts[: len(package_parts) - climb]- if module:- remaining = remaining + module.split(".")- return "/".join(remaining)---def _resolve_absolute_module(module: str, backend_dir: Path) -> str | None:- """An absolute import -> its module path relative to backend_dir, or None if it's not this- product's backend (third-party, core, or another product all return None)."""- root = _product_backend_root(backend_dir)- if module == root:- return ""- if module.startswith(root + "."):- return module[len(root) + 1 :].replace(".", "/")- return None---def _backend_rel_path(module_rel: str, backend_dir: Path) -> str | None:- """A module path relative to backend_dir -> a backend-relative on-disk path, or None.-- Resolves to the file that actually holds definitions: 'models' -> 'backend/models.py' if that- file exists, else 'backend/models/' for a package. The trailing slash on a package lets the- result be prefix-tested against GARAGE_PREFIXES the same way an input glob is."""- if module_rel == "":- return "backend/"- file_path = backend_dir / f"{module_rel}.py"- if file_path.is_file():- return f"backend/{module_rel}.py"- dir_path = backend_dir / module_rel- if dir_path.is_dir():- return f"backend/{module_rel}/"- return None---def _source_file(source_path: str, backend_dir: Path) -> Path:- """The on-disk file for a backend-relative module path (a package resolves to its __init__.py)."""- if source_path.endswith("/"):- return backend_dir.parent / source_path.rstrip("/") / "__init__.py"- return backend_dir.parent / source_path--def _name_is_class(source_path: str,name: str,@@ -624,15 +575,18 @@ def _name_is_class() -> bool:"""True if `name` resolves to a class in the module at source_path.- Follows relative re-exports one hop by default, so a class defined in a submodule and surfaced- through the package __init__ (the common `from .thing import Thing` shape) still counts. Never- leaves this product's backend — an absolute or third-party re-export ends the chain.+ Follows a relative re-export one hop by default, so a class defined in a submodule and surfaced+ through the package __init__ (the common `from .thing import Thing` shape) still counts. An+ absolute re-export ends the chain: it commonly reaches back into facade/contracts.py, where the+ class already sits at its sanctioned home, and following it would report the module that passes+ the contract through as the leak. A name from another product or a library resolves to no path+ and ends the chain too.`cache` memoizes parses per source file for the duration of one facade traversal, so amulti-name import doesn't re-parse the same module once per alias."""if cache is None:cache = {}- file_path = _source_file(source_path, backend_dir)+ file_path = source_file(source_path, backend_dir)if file_path not in cache:cache[file_path] = ast_parse_safe(file_path)tree = cache[file_path]@@ -642,29 +596,32 @@ def _name_is_class(return Trueif hops <= 0:return False- package_parts = _module_package_parts(source_path)- for level, module, aliases in module_level_import_froms(tree):- if level == 0:+ package_parts = module_package_parts(source_path)+ for node in module_level_import_nodes(tree):+ if not isinstance(node, ast.ImportFrom) or node.level == 0:continue- for orig, asname in aliases:- if (asname or orig) != name:- continue- module_rel = _resolve_relative(package_parts, level, module)- if module_rel is None:+ for imported in iter_imported_names(node, package_parts, backend_dir):+ if imported.bound != name or imported.source_path is None:continue- nested = _backend_rel_path(module_rel, backend_dir)- if nested is not None and _name_is_class(nested, orig, backend_dir, hops - 1, cache):+ if _name_is_class(imported.source_path, imported.original, backend_dir, hops - 1, cache):return Truereturn False-def _resolve_dotted_source(dotted: str, backend_dir: Path) -> str | None:- """A lazy-map source value ('logic.crud' or 'products.x.backend.logic.crud') -> backend path."""- module_rel = _resolve_absolute_module(dotted, backend_dir)- if module_rel is None:- # Lazy maps commonly store the value relative to the product's backend package.- module_rel = dotted.replace(".", "/")- return _backend_rel_path(module_rel, backend_dir)+def _resolve_dotted_source(dotted: str, backend_dir: Path, prefixes: Sequence[str] = ()) -> str | None:+ """A lazy-map source value ('logic.crud' or 'products.x.backend.logic.crud') -> backend path.++ A map may also store its values relative to a module-level prefix constant, so every prefix the+ module defines is tried after the bare value. The first candidate that names a real module wins."""+ for candidate in (dotted, *(prefix + dotted for prefix in prefixes)):+ module_rel = resolve_absolute_module(candidate, backend_dir)+ if module_rel is None:+ # Lazy maps commonly store the value relative to the product's backend package.+ module_rel = candidate.replace(".", "/")+ source_path = backend_rel_path(module_rel, backend_dir)+ if source_path is not None:+ return source_path+ return Nonedef _is_facade_or_garage(source_path: str) -> bool:@@ -675,58 +632,78 @@ def _is_test_module(filename: str) -> bool:return filename.startswith("test_") or filename.endswith("_test.py")-def _iter_facade_class_reexports(backend_dir: Path) -> Iterator[FacadeClassImport]:- """Every product-internal class a facade module hands out, from a module that is neither facade nor wiring location —- carve-outs included (callers filter). Three shapes are read:+def _iter_facade_modules(backend_dir: Path) -> Iterator[Path]:+ """Every facade module the facade checks read, in name order.++ Flat by design: facade/ holds no packages, and both callers key a finding on the file name. Test+ modules that happen to sit here are pytest files, not part of the surface."""+ facade_dir = backend_dir / "facade"+ if not facade_dir.is_dir():+ return+ for path in sorted(facade_dir.glob("*.py")):+ if not _is_test_module(path.name):+ yield path+++@dataclass(frozen=True)+class _HandedOutName:+ """A product-internal name one facade module hands out, and the module that defines it."""++ bound: str # the name the facade hands out, which is what a consumer imports+ original: str # the name at the source+ source_path: str # backend-relative, e.g. "backend/logic/crud.py"- - a pure re-export module (no top-level function definitions) hands out every class it imports.++def _iter_handed_out_names(tree: ast.Module, backend_dir: Path) -> Iterator[_HandedOutName]:+ """Every product-internal name one facade module hands out, wiring locations included (callers+ filter). Three shapes are read:++ - a pure re-export module (no top-level function definitions) hands out every name it imports.- a data-capability module (api.py and its split-out siblings, which hold functions that- convert models to contracts) legitimately imports internal classes for its own use, so only+ convert models to contracts) legitimately imports internal names for its own use, so onlydeliberate re-exports count as handed out: names in its literal `__all__`, plus namesimported with the explicit self-alias idiom (`from ..x import Foo as Foo` — the shape thatalso suppresses ruff's F401, so it would otherwise be invisible to every lint).- - a PEP 562 `_LAZY`/`_MODULES` map hands out every class it maps, read regardless of shape.+ - a PEP 562 `_LAZY`/`_MODULES` map hands out every name it maps, read regardless of shape.++ An alias may name a submodule rather than a symbol (`from .. import tasks`), and then the+ module it hands out is that submodule, which is what decides whether a facade module is wiring."""- facade_dir = backend_dir / "facade"- if not facade_dir.is_dir():- return+ is_pure_reexport = not tree_has_top_level_functions(tree)+ allowed = None if is_pure_reexport else module_dunder_all(tree)+ for imported in iter_module_imported_names(tree, ("facade",), backend_dir):+ if imported.source_path is None:+ continue+ handed_out = (+ is_pure_reexport+ or (allowed is not None and imported.bound in allowed)+ or imported.asname == imported.original+ )+ if handed_out:+ yield _HandedOutName(imported.bound, imported.original, imported.source_path)+ prefixes = lazy_reexport_prefixes(tree)+ for name, dotted in lazy_reexport_map(tree).items():+ source_path = _resolve_dotted_source(dotted, backend_dir, prefixes)+ if source_path is not None:+ yield _HandedOutName(name, name, source_path)+++def _iter_facade_class_reexports(backend_dir: Path) -> Iterator[FacadeClassImport]:+ """Every product-internal class a facade module hands out, from a module that is neither facade+ nor wiring location — carve-outs included (callers filter)."""parse_cache: dict[Path, ast.Module | None] = {}- for module_file in sorted(facade_dir.glob("*.py")):- # contracts/enums are the sanctioned homes for data types; test modules that happen to sit- # in facade/ are pytest files, not re-export surface. Neither is a wiring re-export.- if module_file.name in ("contracts.py", "enums.py") or _is_test_module(module_file.name):+ for module_file in _iter_facade_modules(backend_dir):+ # contracts/enums are the sanctioned homes for data types, so neither is a wiring re-export.+ if module_file.name in ("contracts.py", "enums.py"):continuetree = ast_parse_safe(module_file)if tree is None:continue- # A pure re-export module hands out everything it imports; a data-capability module only- # its deliberate re-exports (__all__ membership or the Foo-as-Foo self-alias).- is_pure_reexport = not tree_has_top_level_functions(tree)- allowed = None if is_pure_reexport else module_dunder_all(tree)- for level, module, aliases in module_level_import_froms(tree):- module_rel = (- _resolve_relative(["facade"], level, module)- if level > 0- else _resolve_absolute_module(module or "", backend_dir)- )- if module_rel is None:+ for handed in _iter_handed_out_names(tree, backend_dir):+ if _is_facade_or_garage(handed.source_path):continue- source_path = _backend_rel_path(module_rel, backend_dir)- if source_path is None or _is_facade_or_garage(source_path):- continue- for orig, asname in aliases:- bound = asname or orig- handed_out = is_pure_reexport or (allowed is not None and bound in allowed) or asname == orig- if not handed_out:- continue- if _name_is_class(source_path, orig, backend_dir, cache=parse_cache):- yield FacadeClassImport(module_file.name, orig, source_path)- for name, dotted in lazy_reexport_map(tree).items():- source_path = _resolve_dotted_source(dotted, backend_dir)- if source_path is None or _is_facade_or_garage(source_path):- continue- if _name_is_class(source_path, name, backend_dir, cache=parse_cache):- yield FacadeClassImport(module_file.name, name, source_path)+ if _name_is_class(handed.source_path, handed.original, backend_dir, cache=parse_cache):+ yield FacadeClassImport(module_file.name, handed.original, handed.source_path)@dataclass(frozen=True)@@ -854,6 +831,713 @@ def unwatched_model_surface(product_dir: Path) -> set[str]:return uncovered+# ---------------------------------------------------------------------------+# Facade shape — what the boundary accepts, returns, and defines+# ---------------------------------------------------------------------------+#+# tach and import-linter read import edges only. They see that a facade imports a model module, but+# not that a facade function returns the model, takes a DRF request, or hides a Django object behind+# `Any`. The rules below read the signatures themselves, so publicness comes from the shape of the+# API and not from the location of the file. The rule is+# products/architecture.md § Facades: The Public Interface; checks.py holds the move that clears each kind.++# Capability submodules re-export wiring and hold no logic of their own. A task body or a workflow+# definition here sits in the one package core imports, so the product cannot change it without+# changing what core runs. The implementation belongs in the wiring location, which the+# contract-check inputs watch.+#+# The names the doctrine spells out. A product may call the same wiring anything, so the stem list+# is a floor and _is_capability_module decides the rest from what a module hands out.+CAPABILITY_SUBMODULES: frozenset[str] = frozenset(+ {"dags", "hogql", "max_tools", "models", "queries", "tasks", "temporal"}+)++# Facade stems that are never capability submodules whatever they hand out. `api*.py` holds the+# data capabilities, so a body there is the designed shape; contracts and enums are the sanctioned+# homes for data types; products/architecture.md sanctions a facade/testing.py fixture helper.+_NON_CAPABILITY_FACADE_STEMS: frozenset[str] = frozenset({"contracts", "enums", "testing"})++# Parameters that name the tenant or the actor a call is for. `Any` on one of these hides a Django+# or a DRF object behind an annotation no check can read, which is how a leak survives review.+_UNTYPED_SUBJECT_PARAMS: frozenset[str] = frozenset({"request", "team", "user"})++# Libraries whose types must stay off a facade signature, and the name a ledger row gives each one.+# Core models are absent on purpose: every product may depend on core, so a core model in a facade+# signature adds no coupling the repo does not already have. typing_extensions exports the same+# names as typing and reports under the same source, so the spelling a module picks cannot decide+# whether its `Any` counts.+_LIBRARY_SOURCES: tuple[tuple[tuple[str, ...], str], ...] = (+ (("django.db.models", "django.http"), "django"),+ (("rest_framework",), "rest_framework"),+ (("typing", "typing_extensions"), "typing"),+)+_LIBRARY_NAMES: frozenset[str] = frozenset(source for _, source in _LIBRARY_SOURCES)++# Typing special forms whose subscript arguments are not all types: `Literal` holds values, and+# `Annotated` holds one type followed by metadata. Both modules that export them are named, so an+# import binds the name; a spelling nothing bound falls back to the bare name.+_LITERAL = "Literal"+_ANNOTATED = "Annotated"+_SPECIAL_FORMS: frozenset[str] = frozenset({_LITERAL, _ANNOTATED})+_SPECIAL_FORM_MODULES: frozenset[str] = frozenset({"typing", "typing_extensions"})++# The model surface as dotted module names, so an import path is tested against the same definition+# of "where a product's models live" that the input-coverage checks use.+_MODEL_SURFACE_MODULES: tuple[str, ...] = tuple(+ sorted({p.removeprefix("backend/").rstrip("/").removesuffix(".py") for p in MODEL_SURFACE_PREFIXES})+)+_PRODUCT_BACKEND_RE = re.compile(r"^products\.([A-Za-z0-9_]+)\.backend\.(.+)$")++# Dunder hooks of the PEP 562 lazy re-export map. Their body is the re-export mechanism itself.+_REEXPORT_DUNDERS: frozenset[str] = frozenset({"__getattr__", "__dir__"})+++@dataclass(frozen=True)+class _ForbiddenType:+ """A type a facade module binds a name to, and must not put on the boundary."""++ source: str # django | rest_framework | typing | the product that owns the model+ type_name: str # the name at the source, so an alias still reports the real type+++# `Any` is the one name typing contributes: it is how a Django or a DRF object crosses a signature+# without naming itself.+_ANY = _ForbiddenType("typing", "Any")+++@dataclass(frozen=True)+class FacadeShapeFinding:+ """One place a facade breaks the contract-only boundary.++ A `returns` or an `accepts` finding sits on one symbol and names one type. A `logic` finding+ stands for a whole capability submodule and lists the bodies it still holds, so the ledger's+ count column says how much is left to move.+ """++ product: str+ facade_module: str # facade-relative, e.g. "destinations.py"+ dotted_module: str # e.g. "products.data_pipelines.backend.facade.destinations"+ kind: str # returns | accepts | logic+ # The type the signature names, with the source that defines it: the owning product for a+ # product model, else the library. Both empty for `logic`, which is keyed by the module.+ source: str = ""+ type_name: str = ""+ symbol: str = "" # the function or the method the type sits on, e.g. "Mapper.to_contract"+ parameter: str = "" # the parameter an `accepts` finding names+ bodies: tuple[str, ...] = () # the definitions a `logic` finding counts++ @property+ def count(self) -> int:+ """A `logic` row counts the bodies its module holds; every other kind is one place."""+ return len(self.bodies) if self.kind == "logic" else 1+++class _ModelNames:+ """The Django model class names of each product, parsed once per sweep.++ A models module also holds enums, choices and managers, so a name imported from one is an ORM+ object only when it is a registered model. Products resolve as siblings of the product under+ scan, so the sweep reads the tree it was pointed at.+ """++ def __init__(self, backend_dir: Path) -> None:+ self._products_dir = backend_dir.parent.parent+ self._names: dict[str, frozenset[str]] = {}++ def for_product(self, product: str) -> frozenset[str]:+ if product not in self._names:+ self._names[product] = frozenset(get_model_names(self._products_dir / product / "backend"))+ return self._names[product]+++@dataclass(frozen=True)+class _FacadeImportEnv:+ """What one facade module's imports and type aliases bind, as far as the shape rules care."""++ types: dict[str, _ForbiddenType] # local name -> the forbidden type it binds+ modules: dict[str, str] # local module alias -> source, for a `models.QuerySet` annotation+ special_forms: dict[str, str] # local name -> the typing special form it binds+ aliases: dict[str, ast.expr] # local name -> the expression a module-level type alias stands for+ model_names: _ModelNames+++def _reaches_model_surface(backend_module: str) -> bool:+ """True when a backend-relative dotted module is part of a product's model surface.++ The owner's facade.models shim counts: it re-exports the same classes, so it cannot be the+ spelling that gets a model past the check."""+ return module_has_prefix(backend_module.removeprefix("facade."), _MODEL_SURFACE_MODULES)+++def _product_model_owner(module: str) -> str | None:+ """The product whose model surface an absolute import reaches, else None.++ The backend package itself carries no module, and holds no model of its own."""+ match = PRODUCT_BACKEND_RE.match(module)+ if match is None:+ return None+ product, backend_module = match.groups()+ return product if _reaches_model_surface(backend_module or "") else None+++def _import_source(module: str) -> str | None:+ """Where the names of an absolute import come from, or None when nothing there is off limits:+ the library for a Django, a DRF or a typing import, else the product whose model surface it+ reaches."""+ for prefixes, source in _LIBRARY_SOURCES:+ if module_has_prefix(module, prefixes):+ return source+ return _product_model_owner(module)+++def _forbidden(source: str, name: str, model_names: _ModelNames) -> _ForbiddenType | None:+ """The forbidden type a name from `source` stands for, or None when that name is not one.++ typing contributes `Any` alone. A models module also holds enums, choices and managers, which a+ contract may carry, so only a registered model counts there."""+ if source == _ANY.source:+ return _ANY if name == _ANY.type_name else None+ if source in _LIBRARY_NAMES:+ return _ForbiddenType(source, name)+ return _ForbiddenType(source, name) if name in model_names.for_product(source) else None+++def _facade_import_env(+ tree: ast.Module,+ model_names: _ModelNames,+ backend_dir: Path,+ package_parts: Sequence[str] = ("facade",),+) -> _FacadeImportEnv:+ types: dict[str, _ForbiddenType] = {}+ modules: dict[str, str] = {}+ special_forms: dict[str, str] = {}+ for node in module_level_import_nodes(tree, type_checking=True):+ if isinstance(node, ast.Import):+ for alias in node.names:+ source = _import_source(alias.name)+ if source is not None:+ modules[alias.asname or alias.name.split(".")[0]] = source+ continue+ if node.level == 0 and (node.module or "") in _SPECIAL_FORM_MODULES:+ for alias in node.names:+ if alias.name in _SPECIAL_FORMS:+ special_forms[alias.asname or alias.name] = alias.name+ for imported in iter_imported_names(node, package_parts, backend_dir):+ source = _import_source(imported.package)+ if source is None:+ # `from django.db import models` and `from . import models` both bind the namespace+ # and not a type, so the annotation spells `models.QuerySet`. Neither package is off+ # limits itself, so the submodule the alias names decides.+ submodule_source = _import_source(imported.submodule)+ if submodule_source is not None:+ modules[imported.bound] = submodule_source+ continue+ if imported.binds_submodule:+ modules[imported.bound] = source+ continue+ forbidden = _forbidden(source, imported.original, model_names)+ if forbidden is not None:+ types[imported.bound] = forbidden+ return _FacadeImportEnv(+ types=types,+ modules=modules,+ special_forms=special_forms,+ aliases=module_type_aliases(tree),+ model_names=model_names,+ )+++@dataclass(frozen=True)+class _TypeRef:+ """One type an annotation names: the name bound at module level, and the type it names.++ `QuerySet[Thing]` gives (QuerySet, QuerySet) and (Thing, Thing); `models.QuerySet` gives+ (models, QuerySet)."""++ root: str+ named: str+++def _special_form(env: _FacadeImportEnv, node: ast.expr) -> str | None:+ """The typing special form the head of a subscript names, or None.++ Read from the import that bound the name, so `Literal as L` still resolves. A name nothing+ module-level bound falls back to the spelling, which covers the `typing.Literal` attribute form+ and a name bound somewhere this scan does not read."""+ if isinstance(node, ast.Name):+ bound = env.special_forms.get(node.id)+ if bound is not None:+ return bound+ return node.id if node.id in _SPECIAL_FORMS else None+ if isinstance(node, ast.Attribute):+ return node.attr if node.attr in _SPECIAL_FORMS else None+ return None+++def _first_argument(node: ast.expr) -> ast.expr:+ """The first argument of a subscript, which is the whole slice when there is only one."""+ if isinstance(node, ast.Tuple) and node.elts:+ return node.elts[0]+ return node+++def _annotation_refs(+ env: _FacadeImportEnv, node: ast.expr | None, expanding: frozenset[str] = frozenset()+) -> list[_TypeRef]:+ """Every type an annotation names.++ A quoted annotation is parsed and read the same way, which is how a TYPE_CHECKING import still+ counts. One that does not parse is skipped, because this is a ratchet and not a proof.++ A name a module-level type alias binds is read as the expression it stands for, so the spelling+ a facade picks for a type cannot decide whether it counts. `expanding` holds the aliases already+ open, because an alias may name another one and a pair may name each other.+ """+ if node is None:+ return []+ if isinstance(node, ast.Name):+ alias = env.aliases.get(node.id)+ if alias is not None and node.id not in expanding:+ return _annotation_refs(env, alias, expanding | {node.id})+ return [_TypeRef(node.id, node.id)]+ if isinstance(node, ast.Attribute):+ root: ast.expr = node+ while isinstance(root, ast.Attribute):+ root = root.value+ return [_TypeRef(root.id, node.attr)] if isinstance(root, ast.Name) else []+ if isinstance(node, ast.Constant):+ if not isinstance(node.value, str):+ return []+ try:+ parsed = ast.parse(node.value, mode="eval")+ except SyntaxError:+ return []+ return _annotation_refs(env, parsed.body, expanding)+ if isinstance(node, ast.Subscript):+ form = _special_form(env, node.value)+ if form == _LITERAL:+ # The arguments of a Literal are values. A string among them is data, so parsing it as+ # a forward reference reports a type that never crosses.+ return _annotation_refs(env, node.value, expanding)+ if form == _ANNOTATED:+ # Annotated is one type followed by metadata, and only the type is on the boundary.+ return _annotation_refs(env, node.value, expanding) + _annotation_refs(+ env, _first_argument(node.slice), expanding+ )+ return _annotation_refs(env, node.value, expanding) + _annotation_refs(env, node.slice, expanding)+ if isinstance(node, ast.BinOp):+ return _annotation_refs(env, node.left, expanding) + _annotation_refs(env, node.right, expanding)+ if isinstance(node, (ast.Tuple, ast.List)):+ return [ref for element in node.elts for ref in _annotation_refs(env, element, expanding)]+ return []+++def _named_type(env: _FacadeImportEnv, root: str, named: str) -> _ForbiddenType | None:+ """The forbidden type one annotation reference stands for, or None."""+ bound = env.types.get(root)+ if bound is not None:+ # `Thing.Status` is a nested class attribute, which carries no instance of the outer class,+ # so only the bare name puts the type on the boundary.+ return bound if named == root else None+ source = env.modules.get(root)+ if source is None or named == root:+ return None+ return _forbidden(source, named, env.model_names)+++def _forbidden_types_in(env: _FacadeImportEnv, annotation: ast.expr | None) -> list[_ForbiddenType]:+ """Every forbidden type one annotation names, first occurrence kept.++ Keyed by source and name together: two types can share a name across products, and collapsing+ them would let a sanctioned one hide an unsanctioned one behind it."""+ found: dict[tuple[str, str], _ForbiddenType] = {}+ for ref in _annotation_refs(env, annotation):+ forbidden = _named_type(env, ref.root, ref.named)+ if forbidden is not None:+ found.setdefault((forbidden.source, forbidden.type_name), forbidden)+ return list(found.values())+++def _annotation_is_any(env: _FacadeImportEnv, annotation: ast.expr | None) -> bool:+ """True when the whole annotation is `Any`. `dict[str, Any]` is not: the data stays data."""+ refs = _annotation_refs(env, annotation)+ return len(refs) == 1 and _named_type(env, refs[0].root, refs[0].named) == _ANY+++def _is_sanctioned(product: str, forbidden: _ForbiddenType) -> bool:+ """A class the doctrine already lets this product's facade hand out.++ The allowance covers the product's own class, so the source must be the product too: another+ product's same-named model is a crossing nobody sanctioned."""+ if forbidden.source != product:+ return False+ key = (product, forbidden.type_name)+ return key in CARVE_OUTS or key in MODEL_CROSSINGS+++def _iter_accepts_findings(+ env: _FacadeImportEnv,+ product: str,+ facade_module: str,+ dotted_module: str,+ symbol: str,+ parameter: str,+ annotation: ast.expr | None,+) -> Iterator[FacadeShapeFinding]:+ """One `accepts` finding per forbidden type on one parameter.++ `Any` only counts on the tenant and actor names, because an `Any` payload says nothing about a+ Django object."""+ for forbidden in _forbidden_types_in(env, annotation):+ if _is_sanctioned(product, forbidden):+ continue+ if forbidden == _ANY and parameter not in _UNTYPED_SUBJECT_PARAMS:+ continue+ yield FacadeShapeFinding(+ product=product,+ facade_module=facade_module,+ dotted_module=dotted_module,+ kind="accepts",+ source=forbidden.source,+ type_name=forbidden.type_name,+ symbol=symbol,+ parameter=parameter,+ )+++def _iter_signature_findings(+ node: ast.FunctionDef | ast.AsyncFunctionDef,+ env: _FacadeImportEnv,+ product: str,+ facade_module: str,+ dotted_module: str,+ symbol: str,+) -> Iterator[FacadeShapeFinding]:+ """One finding per forbidden type in one signature.++ A bare `-> Any` is a finding of its own: it promises nothing, which is the evasion the whole+ check exists to close."""+ for forbidden in _forbidden_types_in(env, node.returns):+ if _is_sanctioned(product, forbidden):+ continue+ if forbidden == _ANY and not _annotation_is_any(env, node.returns):+ continue+ yield FacadeShapeFinding(+ product=product,+ facade_module=facade_module,+ dotted_module=dotted_module,+ kind="returns",+ source=forbidden.source,+ type_name=forbidden.type_name,+ symbol=symbol,+ )+ args = node.args+ for arg in [*args.posonlyargs, *args.args, *args.kwonlyargs, args.vararg, args.kwarg]:+ if arg is None or arg.arg in ("self", "cls"):+ continue+ yield from _iter_accepts_findings(env, product, facade_module, dotted_module, symbol, arg.arg, arg.annotation)+++# Decorators that generate a constructor out of the annotated class-level fields: the stdlib one+# under every spelling (`@dataclass`, `@dataclass(...)`, `@dataclasses.dataclass`) and the house+# `@frozen` of posthog.dataclasses.+_DATACLASS_DECORATORS: frozenset[str] = frozenset({"dataclass", "frozen"})+++def _has_generated_constructor(node: ast.ClassDef) -> bool:+ return any(decorator_name(decorator) in _DATACLASS_DECORATORS for decorator in node.decorator_list)+++def _annotation_head(node: ast.expr) -> str:+ """The bare name at the head of an annotation, with any module prefix dropped."""+ if isinstance(node, ast.Name):+ return node.id+ if isinstance(node, ast.Attribute):+ return node.attr+ return ""+++def _is_class_var(annotation: ast.expr) -> bool:+ """True for `ClassVar[...]`, which is shared state rather than a field, so it takes no keyword."""+ return isinstance(annotation, ast.Subscript) and _annotation_head(annotation.value) == "ClassVar"+++def _iter_dataclass_field_findings(+ tree: ast.Module, env: _FacadeImportEnv, product: str, facade_module: str, dotted_module: str+) -> Iterator[FacadeShapeFinding]:+ """Signature findings for the constructors a dataclass decorator generates.++ A field is a keyword of the generated `__init__`, so a model on one is a model the caller hands+ the class, exactly like an annotated parameter of a written constructor. Such a row names+ `<Class>.__init__` and carries the field as its parameter. facade/contracts.py is read like every+ other facade module, because a frozen contract is precisely what must never carry a model."""+ for node in ast.iter_child_nodes(tree):+ if not isinstance(node, ast.ClassDef) or node.name.startswith("_"):+ continue+ if not _has_generated_constructor(node):+ continue+ for statement in node.body:+ if not isinstance(statement, ast.AnnAssign) or not isinstance(statement.target, ast.Name):+ continue+ if _is_class_var(statement.annotation):+ continue+ yield from _iter_accepts_findings(+ env,+ product,+ facade_module,+ dotted_module,+ f"{node.name}.__init__",+ statement.target.id,+ statement.annotation,+ )+++def _iter_module_signature_findings(+ tree: ast.Module, env: _FacadeImportEnv, product: str, facade_module: str, dotted_module: str+) -> Iterator[FacadeShapeFinding]:+ """Signature findings for the module's public call surface: its module-level functions, the+ public methods, constructor included, of the public classes it defines, and the constructors a+ dataclass decorator generates. A leading underscore marks a helper the facade keeps to itself,+ and converting a model to a contract is exactly what such a helper is for."""+ for owner, node in iter_public_callables(tree, include_init=True):+ if owner.startswith("_"):+ continue+ symbol = f"{owner}.{node.name}" if owner else node.name+ yield from _iter_signature_findings(node, env, product, facade_module, dotted_module, symbol)+ yield from _iter_dataclass_field_findings(tree, env, product, facade_module, dotted_module)+++def _top_level_function(tree: ast.Module, name: str) -> ast.FunctionDef | ast.AsyncFunctionDef | None:+ for node in ast.iter_child_nodes(tree):+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name:+ return node+ return None+++def _cached_parse(cache: dict[str, ast.Module | None], source_path: str, backend_dir: Path) -> ast.Module | None:+ if source_path not in cache:+ cache[source_path] = ast_parse_safe(source_file(source_path, backend_dir))+ return cache[source_path]+++@dataclass(frozen=True)+class _ImportHop:+ """Where a module-level import says a name it binds comes from."""++ source_path: str # backend-relative, e.g. "backend/logic/crud.py"+ name: str # the name at that source, which an alias may rename+++def _import_hop(tree: ast.Module, source_path: str, name: str, backend_dir: Path) -> _ImportHop | None:+ """The module-level import that binds `name` in this module, resolved to the module it names.++ None when nothing binds it, or when what binds it is outside this product's backend: a chain+ that leaves the product ends there, the same way the class walk ends."""+ for imported in iter_module_imported_names(tree, module_package_parts(source_path), backend_dir):+ if imported.bound == name and imported.source_path is not None:+ return _ImportHop(imported.source_path, imported.original)+ return None+++@dataclass(frozen=True)+class _ResolvedFunction:+ """A function a facade hands out, with the module that finally defines it."""++ node: ast.FunctionDef | ast.AsyncFunctionDef+ source_path: str # backend-relative, e.g. "backend/logic/crud.py"+++# How many re-export hops a name may take before the walk gives up. A package __init__ that surfaces+# a submodule is one hop, and a chain longer than a handful is a structure problem of its own.+_REEXPORT_HOPS = 5+++def _resolve_function(+ source_path: str,+ name: str,+ backend_dir: Path,+ parse_cache: dict[str, ast.Module | None],+ hops: int = _REEXPORT_HOPS,+) -> _ResolvedFunction | None:+ """The function a name resolves to, following the re-exports of this product's own modules.++ A facade reaches its logic through a package (`from ..logic import fn`), and that package+ __init__ commonly surfaces the function from a submodule rather than defining it. Without the+ hop the real signature is never read, so the spelling would decide whether a type counts."""+ tree = _cached_parse(parse_cache, source_path, backend_dir)+ if tree is None:+ return None+ node = _top_level_function(tree, name)+ if node is not None:+ return _ResolvedFunction(node, source_path)+ if hops <= 0:+ return None+ hop = _import_hop(tree, source_path, name, backend_dir)+ if hop is None:+ return None+ return _resolve_function(hop.source_path, hop.name, backend_dir, parse_cache, hops - 1)+++def _iter_reexport_signature_findings(+ tree: ast.Module,+ backend_dir: Path,+ product: str,+ facade_module: str,+ dotted_module: str,+ model_names: _ModelNames,+) -> Iterator[FacadeShapeFinding]:+ """Signature findings for the functions a facade hands out that another module defines.++ A re-export is part of the facade's own call surface: a consumer imports the name from the+ facade and another module answers, whether the facade spells that as an import it re-exports or+ as a PEP 562 lazy map. So the defining function is read under the facade name, and neither+ spelling can be what gets a type past the check. The chain is followed through the product's own+ modules, because a package __init__ commonly re-exports the function rather than defining it.+ Annotations are resolved in the defining module's own namespace, which is where they were+ written.++ A class is a re-export the wiring doctrine reads instead (facade_class_imports), and a name the+ facade module defines itself is already read by the module scan. A source outside this product's+ backend never resolves to a path, so nothing crosses in from core or a library.+ """+ defined_here = {+ node.name+ for node in ast.iter_child_nodes(tree)+ if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))+ }+ parse_cache: dict[str, ast.Module | None] = {}+ env_cache: dict[str, _FacadeImportEnv] = {}+ handed_out = set(_iter_handed_out_names(tree, backend_dir))+ for handed in sorted(handed_out, key=lambda h: (h.bound, h.original, h.source_path)):+ # A real definition wins over a re-export, and the module scan already read it.+ if handed.bound.startswith("_") or handed.bound in defined_here:+ continue+ # A sibling facade module is scanned under its own name, so reading it again here would+ # record the same signature twice.+ if handed.source_path.startswith(_FACADE_PREFIX):+ continue+ resolved = _resolve_function(handed.source_path, handed.original, backend_dir, parse_cache)+ if resolved is None or resolved.source_path.startswith(_FACADE_PREFIX):+ continue+ source_tree = _cached_parse(parse_cache, resolved.source_path, backend_dir)+ if source_tree is None:+ continue+ if resolved.source_path not in env_cache:+ env_cache[resolved.source_path] = _facade_import_env(+ source_tree, model_names, backend_dir, module_package_parts(resolved.source_path)+ )+ yield from _iter_signature_findings(+ resolved.node, env_cache[resolved.source_path], product, facade_module, dotted_module, handed.bound+ )+++def _has_wiring_decorator(node: ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef) -> bool:+ """True when a definition carries wiring core registers: a Celery task or a Temporal+ definition. Temporal is spelled `<module>.defn`, so its receiver is read too: a bare `defn` is+ some other decorator."""+ for decorator in node.decorator_list:+ if decorator_name(decorator) == "shared_task":+ return True+ target = decorator.func if isinstance(decorator, ast.Call) else decorator+ if isinstance(target, ast.Attribute) and target.attr == "defn" and isinstance(target.value, ast.Name):+ return True+ return False+++def _is_passthrough_body(node: ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef) -> bool:+ """True when the body holds only a docstring, `pass`, or `...`, which is a stub and not logic."""+ body = list(node.body)+ if (+ body+ and isinstance(body[0], ast.Expr)+ and isinstance(body[0].value, ast.Constant)+ and isinstance(body[0].value.value, str)+ ):+ body = body[1:]+ return all(+ isinstance(stmt, ast.Pass)+ or (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant) and stmt.value.value is Ellipsis)+ for stmt in body+ )+++def _capability_finding(+ tree: ast.Module, product: str, facade_module: str, dotted_module: str+) -> FacadeShapeFinding | None:+ """The one `logic` finding for a capability submodule, naming every definition it holds beyond a+ re-export. One finding per module, so the count says how much is left to move."""+ bodies: list[str] = []+ for node in ast.iter_child_nodes(tree):+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):+ continue+ if node.name in _REEXPORT_DUNDERS:+ continue+ if _has_wiring_decorator(node) or not _is_passthrough_body(node):+ bodies.append(node.name)+ if not bodies:+ return None+ return FacadeShapeFinding(+ product=product,+ facade_module=facade_module,+ dotted_module=dotted_module,+ kind="logic",+ bodies=tuple(bodies),+ )+++def _is_capability_module(tree: ast.Module, filename: str, backend_dir: Path) -> bool:+ """True when a facade module is a capability submodule: one whose job is to hand out wiring or+ model classes.++ Read from what the module hands out rather than from its name, because a product may call the+ same wiring anything (`workflow_tasks.py`, `tools.py`) and a filename allowlist then misses it.+ The doctrine stems stay a floor, so such a module keeps the rule before it hands anything out."""+ stem = filename.removesuffix(".py")+ if stem in CAPABILITY_SUBMODULES:+ return True+ if stem.startswith("api") or stem in _NON_CAPABILITY_FACADE_STEMS:+ return False+ wiring = (*GARAGE_PREFIXES, *MODEL_SURFACE_PREFIXES)+ return any(handed.source_path.startswith(wiring) for handed in _iter_handed_out_names(tree, backend_dir))+++def _facade_module_dotted(product: str, filename: str) -> str:+ """`products.<product>.backend.facade.<module>` for one facade file. A package __init__ names+ the package itself, the same rule the crossings scan uses for a repo path."""+ parts = ["products", product, "backend", "facade"]+ stem = filename.removesuffix(".py")+ if stem != "__init__":+ parts.append(stem)+ return ".".join(parts)+++def facade_shape_findings(backend_dir: Path, name: str) -> list[FacadeShapeFinding]:+ """Every place this product's facade puts a Django, a DRF or an ORM type on its boundary, plus+ every capability submodule that holds a body rather than a re-export.++ crossings.py turns each finding into a `facade-*` line of the model-crossing ledger, which is+ where the ratchet holds it. The rule is products/architecture.md § Facades: The Public Interface,+ and checks.py holds the move that clears each kind.+ """+ findings: list[FacadeShapeFinding] = []+ model_names = _ModelNames(backend_dir)+ for path in _iter_facade_modules(backend_dir):+ tree = ast_parse_safe(path)+ if tree is None:+ continue+ dotted_module = _facade_module_dotted(name, path.name)+ env = _facade_import_env(tree, model_names, backend_dir)+ findings.extend(_iter_module_signature_findings(tree, env, name, path.name, dotted_module))+ findings.extend(+ _iter_reexport_signature_findings(tree, backend_dir, name, path.name, dotted_module, model_names)+ )+ if _is_capability_module(tree, path.name, backend_dir):+ logic = _capability_finding(tree, name, path.name, dotted_module)+ if logic is not None:+ findings.append(logic)+ return sorted(findings, key=lambda f: (f.facade_module, f.symbol, f.kind, f.type_name, f.parameter))++# ---------------------------------------------------------------------------# High-level status — the synthesis both lint and maturity read# ---------------------------------------------------------------------------diff --git a/tools/hogli-commands/hogli_commands/product/lint.py b/tools/hogli-commands/hogli_commands/product/lint.pyindex 75e0ac98f98d..4ffffafb44ff 100644--- a/tools/hogli-commands/hogli_commands/product/lint.py+++ b/tools/hogli-commands/hogli_commands/product/lint.py@@ -93,7 +93,7 @@ def lint_all_products() -> None:click.echo("Checks: required root files, package.json scripts (presence + content), misplaced files (strict), ""file/folder conflicts, tach boundaries (+ interfaces for strict), isolation progress (lenient), "- "isolation baseline\n"+ "facade shape, isolation baseline\n")structure = load_structure()diff --git a/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.py b/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.pyindex 16072ff51b91..51c73a5e291a 100644--- a/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.py+++ b/tools/hogli-commands/hogli_commands/tests/test_ast_helpers.py@@ -8,6 +8,7 @@ from hogli_commands.product.ast_helpers import get_frozen_dataclass_names, get_mMODELS_SOURCE = """from django.db import models+from pydantic import BaseModelfrom posthog.models.scoping import TeamScopedRootMixinfrom posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel@@ -32,6 +33,14 @@ class AbstractBase(TeamScopedRootMixin, UUIDModel):abstract = True+class Derived(AbstractBase):+ pass+++class Payload(BaseModel):+ name: str++class Flavor(models.TextChoices):VANILLA = "vanilla", "Vanilla"@@ -44,14 +53,6 @@ class PlainHelper:pass"""-NO_DJANGO_SOURCE = """-from pydantic import BaseModel---class Payload(BaseModel):- name: str-"""-class TestGetModelNames:@pytest.mark.parametrize(@@ -61,6 +62,8 @@ class TestGetModelNames:("SyncConfig", True), # meta-fields mixins only("Widget", True), # classic 'Model'-suffix base("AbstractBase", False), # Meta.abstract = True never comes out of the registry+ ("Derived", True), # ...but it is still how its subclass reaches a Django base+ ("Payload", False), # a pydantic model in a models file validates a field, not a table("Flavor", False), # module-level choices class("ChannelType", False), # nested choices class("WidgetManager", False), # manager helper@@ -73,11 +76,22 @@ class TestGetModelNames:(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) == []+ def test_a_proxy_model_is_reached_through_its_concrete_model(self, tmp_path: Path) -> None:+ # A proxy model sits in another module and subclasses its concrete model, so only a+ # resolution that reaches across the model modules finds it. Dropping it lets a facade hand+ # the class out with no finding.+ models_dir = tmp_path / "backend" / "models"+ models_dir.mkdir(parents=True)+ (models_dir / "widgets.py").write_text(MODELS_SOURCE)+ (models_dir / "web_widget.py").write_text(+ "from posthog.models.utils import RootTeamManager\n\n"+ "from .widgets import Widget\n\n\n"+ "class WebWidgetManager(RootTeamManager):\n pass\n\n\n"+ "class WebWidget(Widget):\n class Meta:\n proxy = True\n"+ )+ names = get_model_names(tmp_path / "backend")+ assert "WebWidget" in names+ assert "WebWidgetManager" not in namesFROZEN_DATACLASS_SOURCE = """diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex 3404781e6f23..c11c368b8bd6 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -14,6 +14,7 @@ from hogli_commands.product import (from hogli_commands.product.checks import (BackendPackageMarkerCheck,CheckContext,+ FacadeShapeCheck,FileFolderConflictsCheck,ImportSurfaceCheck,IsolationChainCheck,@@ -30,11 +31,13 @@ from hogli_commands.product.checks import (validate_interface_blocks,validate_tach_references,)+from hogli_commands.product.crossings import facade_shape_usefrom hogli_commands.product.isolation import (MODEL_SURFACE_PREFIXES,facade_carveout_modules,facade_class_imports,facade_model_crossings,+ facade_shape_findings,has_narrowed_turbo_inputs,permanent_interface_modules,routes_in_turbo_inputs,@@ -2047,3 +2050,468 @@ class TestBackendPackageMarker:ctx = self._product(tmp_path, markers=[".", "facade"], trees=[])(ctx.backend_dir / "facade" / "empty").mkdir()assert self.check._missing_markers(ctx) == []+++_MODELS_PY = (+ "from django.db import models\n\n\n"+ "class Thing(models.Model):\n pass\n\n\n"+ "class ThingKind(models.TextChoices):\n RED = 'red'\n\n\n"+ "class ExternalDataSource(models.Model):\n pass\n"+)+++def _write_shape_product(+ tmp_path: Path,+ facade_files: dict[str, str],+ *,+ name: str = "my_product",+ sources: dict[str, str] | None = None,+) -> Path:+ """A product whose models module defines Thing, the ThingKind choices, and ExternalDataSource."""+ _, backend = _write_facade_product(+ tmp_path, name=name, facade_files=facade_files, sources={"models.py": _MODELS_PY, **(sources or {})}+ )+ return backend+++class TestFacadeShape:+ @pytest.mark.parametrize(+ "facade_files, expected",+ [+ # a public function returning the product's own model hands the caller managers,+ # save()/delete(), and FK descriptors that query on attribute access+ (+ {"api.py": "from ..models import Thing\n\n\ndef get_thing() -> Thing:\n return Thing()\n"},+ {("get_thing", "", "returns", "Thing")},+ ),+ # the facade's own models shim re-exports the same class, so it cannot be the spelling+ # that gets the model past the check+ (+ {"api.py": "from .models import Thing\n\n\ndef get_thing() -> Thing:\n return Thing()\n"},+ {("get_thing", "", "returns", "Thing")},+ ),+ # a models module also holds choices and enums, which are values a contract may carry+ (+ {"api.py": "from ..models import ThingKind\n\n\ndef kind() -> ThingKind:\n ...\n"},+ set(),+ ),+ # a QuerySet return lets the caller keep building the query outside the product+ (+ {+ "api.py": "from django.db.models import QuerySet\n\n\ndef list_things() -> QuerySet[int]:\n return []\n"+ },+ {("list_things", "", "returns", "QuerySet")},+ ),+ # a Prefetch is an ORM plan object, so the caller decides what the product loads+ (+ {"api.py": "from django.db.models import Prefetch\n\n\ndef tiles() -> Prefetch:\n ...\n"},+ {("tiles", "", "returns", "Prefetch")},+ ),+ # the `models.QuerySet` spelling must resolve like the direct import+ (+ {"api.py": "from django.db import models\n\n\ndef things() -> models.QuerySet:\n ...\n"},+ {("things", "", "returns", "QuerySet")},+ ),+ # a bare relative import binds the submodule too, so `models.Thing` after it names the+ # model, which is the spelling several facades already use for their own models shim+ (+ {"api.py": "from . import models\n\n\ndef get_thing() -> models.Thing:\n ...\n"},+ {("get_thing", "", "returns", "Thing")},+ ),+ (+ {"api.py": "from .. import models\n\n\ndef get_thing() -> models.Thing:\n ...\n"},+ {("get_thing", "", "returns", "Thing")},+ ),+ # ...but only the model surface binds that way: contracts are what the facade is for+ (+ {"api.py": "from . import contracts\n\n\ndef get_thing() -> contracts.Thing:\n ...\n"},+ set(),+ ),+ # a nested class attribute carries no instance of the outer class, so `Thing.Status` is+ # a value a contract may hold+ (+ {"api.py": "from ..models import Thing\n\n\ndef status() -> Thing.Status:\n ...\n"},+ set(),+ ),+ # an alias must report the type at the source, or the row cannot be matched to a class+ (+ {"api.py": "from django.db.models import QuerySet as QS\n\n\ndef things() -> QS:\n ...\n"},+ {("things", "", "returns", "QuerySet")},+ ),+ # a module-level alias is a name for the same type, so the spelling a facade picks+ # cannot decide whether the model on it counts+ (+ {+ "api.py": "from collections.abc import Callable\n\nfrom ..models import Thing\n\nHandler = Callable[[Thing], None]\n\n\ndef register(handler: Handler) -> None:\n return None\n"+ },+ {("register", "handler", "accepts", "Thing")},+ ),+ # ...and the explicit TypeAlias spelling of the same alias+ (+ {+ "api.py": "from typing import TypeAlias\n\nfrom ..models import Thing\n\nRows: TypeAlias = list[Thing]\n\n\ndef load() -> Rows:\n ...\n"+ },+ {("load", "", "returns", "Thing")},+ ),+ # ...and the PEP 695 statement, which facades already write+ (+ {"api.py": "from ..models import Thing\n\ntype Rows = list[Thing]\n\n\ndef load() -> Rows:\n ...\n"},+ {("load", "", "returns", "Thing")},+ ),+ # a dataclass field is a keyword of the constructor the decorator generates, so a model+ # on one is a model the caller hands the class+ (+ {+ "api.py": "from dataclasses import dataclass\n\nfrom ..models import Thing\n\n\n@dataclass\nclass Row:\n thing: Thing\n"+ },+ {("Row.__init__", "thing", "accepts", "Thing")},+ ),+ (+ {+ "api.py": "from dataclasses import dataclass\n\nfrom ..models import Thing\n\n\n@dataclass(frozen=True)\nclass Row:\n thing: Thing\n"+ },+ {("Row.__init__", "thing", "accepts", "Thing")},+ ),+ # a frozen contract is precisely what must never carry a model, so contracts.py is read+ # like every other facade module+ (+ {+ "contracts.py": "from posthog.dataclasses import frozen\n\nfrom ..models import Thing\n\n\n@frozen\nclass ThingData:\n thing: Thing\n"+ },+ {("ThingData.__init__", "thing", "accepts", "Thing")},+ ),+ # a bare `-> Any` promises nothing, which is the evasion the check exists to close+ (+ {"api.py": "from typing import Any\n\n\ndef serialize() -> Any:\n ...\n"},+ {("serialize", "", "returns", "Any")},+ ),+ # ...and typing_extensions exports the same name, so it cannot be the import that gets+ # an `Any` past the check+ (+ {"api.py": "from typing_extensions import Any\n\n\ndef serialize() -> Any:\n ...\n"},+ {("serialize", "", "returns", "Any")},+ ),+ # ...but data inside a container is still data+ (+ {"api.py": "from typing import Any\n\n\ndef serialize() -> dict[str, Any]:\n ...\n"},+ set(),+ ),+ # `Any` on the tenant parameter is how a Team model crosses without naming itself+ (+ {"api.py": "from typing import Any\n\n\ndef digest(team: Any) -> None:\n return None\n"},+ {("digest", "team", "accepts", "Any")},+ ),+ # ...but `Any` on an ordinary payload says nothing about a Django object+ (+ {"api.py": "from typing import Any\n\n\ndef digest(payload: Any) -> None:\n return None\n"},+ set(),+ ),+ # product -> core is the sanctioned direction, so a core model is not a finding+ (+ {"api.py": "from posthog.models import Team\n\n\ndef digest(team: Team) -> None:\n return None\n"},+ set(),+ ),+ # a DRF request in the facade means the facade knows the transport+ (+ {+ "api.py": "from rest_framework.request import Request\n\n\ndef provenance(request: Request) -> None:\n return None\n"+ },+ {("provenance", "request", "accepts", "Request")},+ ),+ # ...and importing the submodule instead binds a namespace, so `request.Request` names+ # the same class and cannot be the spelling that gets it past the check+ (+ {+ "api.py": "from rest_framework import request\n\n\ndef provenance(req: request.Request) -> None:\n return None\n"+ },+ {("provenance", "req", "accepts", "Request")},+ ),+ # a constructor takes what the caller hands the class, so it is part of the surface+ (+ {+ "api.py": "from django.db.models import QuerySet\n\n\nclass Rows:\n def __init__(self, queryset: QuerySet) -> None:\n self._queryset = queryset\n"+ },+ {("Rows.__init__", "queryset", "accepts", "QuerySet")},+ ),+ # the arguments of a Literal are values, so a model name among them is data+ (+ {+ "api.py": "from typing import Literal\n\nfrom ..models import Thing\n\n\ndef pick(kind: Literal['Thing', 'ExternalDataSource']) -> None:\n return None\n"+ },+ set(),+ ),+ # Annotated is one type plus metadata: the type counts and the metadata does not+ (+ {+ "api.py": "from typing import Annotated\n\nfrom ..models import Thing\n\n\ndef pick(row: Annotated[Thing, 'ExternalDataSource']) -> None:\n return None\n"+ },+ {("pick", "row", "accepts", "Thing")},+ ),+ # a TYPE_CHECKING import plus a quoted annotation is the same promise, spelled to dodge+ # the import graph+ (+ {+ "api.py": "from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from ..models import Thing\n\n\ndef get_thing() -> 'Thing':\n ...\n"+ },+ {("get_thing", "", "returns", "Thing")},+ ),+ # converting a model to a contract is what a private facade helper is for+ (+ {"api.py": "from ..models import Thing\n\n\ndef _to_contract(row: Thing) -> None:\n return None\n"},+ set(),+ ),+ (+ {+ "api.py": "from ..models import Thing\n\n\nclass Mapper:\n def to_contract(self, row: Thing) -> None:\n return None\n"+ },+ {("Mapper.to_contract", "row", "accepts", "Thing")},+ ),+ ],+ )+ def test_detection(+ self, tmp_path: Path, facade_files: dict[str, str], expected: set[tuple[str, str, str, str]]+ ) -> None:+ backend = _write_shape_product(tmp_path, facade_files)+ findings = facade_shape_findings(backend, "my_product")+ assert {(f.symbol, f.parameter, f.kind, f.type_name) for f in findings} == expected++ def test_a_model_routed_through_another_facade_is_still_a_model(self, tmp_path: Path) -> None:+ # The owner's facade.models shim is the sanctioned way to reach its models, so a foreign+ # model arrives spelled through it rather than through the models module directly.+ _write_shape_product(+ tmp_path, {"models.py": "from ..models import Thing\n\n__all__ = ['Thing']\n"}, name="owner"+ )+ backend = _write_shape_product(+ tmp_path,+ {+ "api.py": "from products.owner.backend.facade.models import Thing\n\n\n"+ "def get_thing() -> Thing:\n ...\n"+ },+ )+ findings = facade_shape_findings(backend, "my_product")+ assert [(f.source, f.type_name, f.kind) for f in findings] == [("owner", "Thing", "returns")]++ def test_a_sanctioned_model_crossing_is_not_a_shape_finding(self, tmp_path: Path) -> None:+ # warehouse_sources holds the ExternalDataSource entry in MODEL_CROSSINGS, so its facade may+ # hand the class out. Without the exemption the sanctioned crossing would fail the lint the+ # day the check lands, and the allowance is keyed per product, so nobody else inherits it.+ facade = {+ "api.py": "from ..models import ExternalDataSource\n\n\ndef source() -> ExternalDataSource:\n ...\n"+ }+ allowed = _write_shape_product(tmp_path / "a", facade, name="warehouse_sources")+ other = _write_shape_product(tmp_path / "b", facade, name="unrelated_product")+ assert facade_shape_findings(allowed, "warehouse_sources") == []+ assert [f.type_name for f in facade_shape_findings(other, "unrelated_product")] == ["ExternalDataSource"]++ def test_the_allowance_does_not_cover_a_same_named_class_from_another_product(self, tmp_path: Path) -> None:+ # warehouse_sources may hand out its own ExternalDataSource, and the identically named class+ # from another product is a crossing nobody sanctioned. Both sit in one annotation, so a+ # per-name key would collapse them and let the sanctioned one hide the other.+ _write_shape_product(tmp_path, {}, name="lookalike")+ backend = _write_shape_product(+ tmp_path,+ {+ "api.py": "from ..models import ExternalDataSource\n"+ "from products.lookalike.backend.models import ExternalDataSource as Other\n\n\n"+ "def sources() -> tuple[ExternalDataSource, Other]:\n ...\n"+ },+ name="warehouse_sources",+ )+ findings = facade_shape_findings(backend, "warehouse_sources")+ assert [(f.source, f.type_name) for f in findings] == [("lookalike", "ExternalDataSource")]++ @pytest.mark.parametrize(+ "facade_api, extra_sources, symbol",+ [+ # a PEP 562 map: the consumer imports the name from the facade and the map decides+ # which module answers+ (+ '_B = "products.my_product.backend."\n'+ '_LAZY = {"get_thing": "logic.crud"}\n\n\n'+ "def __getattr__(name):\n ...\n",+ {},+ "get_thing",+ ),+ # a module with no definitions of its own hands out everything it imports+ ("from ..logic.crud import get_thing\n", {}, "get_thing"),+ # the self-alias idiom, which also suppresses ruff's F401+ (+ "from ..logic.crud import get_thing as get_thing\n\n\ndef other() -> None:\n return None\n",+ {},+ "get_thing",+ ),+ # a renamed re-export is read under the name the facade hands out+ ("from ..logic.crud import get_thing as fetch\n\n__all__ = ['fetch']\n", {}, "fetch"),+ # a facade reaches its logic through the package, whose __init__ commonly surfaces the+ # function from a submodule rather than defining it+ (+ "from ..logic import get_thing\n",+ {"logic/__init__.py": "from .crud import get_thing\n"},+ "get_thing",+ ),+ ],+ )+ def test_a_re_exported_function_is_read_under_the_facade_name(+ self, tmp_path: Path, facade_api: str, extra_sources: dict[str, str], symbol: str+ ) -> None:+ # A re-export is part of the facade's own call surface: the consumer imports the name from+ # the facade, so neither spelling can be what gets the model past the check.+ backend = _write_shape_product(+ tmp_path,+ {"api.py": facade_api},+ sources={+ "logic/crud.py": "from ..models import Thing\n\n\ndef get_thing() -> Thing:\n ...\n",+ **extra_sources,+ },+ )+ findings = facade_shape_findings(backend, "my_product")+ assert [(f.dotted_module, f.symbol, f.kind, f.type_name) for f in findings] == [+ ("products.my_product.backend.facade.api", symbol, "returns", "Thing")+ ]++ @pytest.mark.parametrize(+ "facade_files, expected",+ [+ # a task body in facade/tasks.py is the implementation core registers, sitting in the one+ # package core imports instead of in backend/tasks/ where the inputs watch it+ (+ {"tasks.py": "from celery import shared_task\n\n\n@shared_task\ndef run_it() -> None:\n print(1)\n"},+ ("run_it",),+ ),+ # the same module doing only what it is for stays clean+ (+ {"tasks.py": "from ..tasks import run_it\n\n__all__ = ['run_it']\n"},+ None,+ ),+ (+ {"temporal.py": "from temporalio import workflow\n\n\[email protected]\nclass Flow:\n x = 1\n"},+ ("Flow",),+ ),+ # one row per module, so the count says how many bodies are left to move+ (+ {"queries.py": "def one():\n return 1\n\n\nclass Two:\n x = 1\n"},+ ("one", "Two"),+ ),+ # api.py holds the data capabilities, so a body there is the designed shape+ (+ {"api.py": "def run_query():\n return 1\n"},+ None,+ ),+ # the PEP 562 hook is the re-export mechanism, not logic of the module's own+ (+ {+ "models.py": "_LAZY = {'Thing': 'models'}\n\n\ndef __getattr__(name):\n import importlib\n\n return getattr(importlib.import_module('x'), name)\n"+ },+ None,+ ),+ ],+ )+ def test_capability_submodule_logic(+ self, tmp_path: Path, facade_files: dict[str, str], expected: tuple[str, ...] | None+ ) -> None:+ backend = _write_shape_product(tmp_path, facade_files)+ logic = [f for f in facade_shape_findings(backend, "my_product") if f.kind == "logic"]+ assert [f.bodies for f in logic] == ([expected] if expected else [])+ assert [f.count for f in logic] == ([len(expected)] if expected else [])++ @pytest.mark.parametrize(+ "reexport, expected",+ [+ # a module that hands out a Temporal definition is wiring whatever it is called, and+ # products already name such a module workflow_tasks.py or tools.py+ ("from ..temporal.flows import run_it\n\n__all__ = ['run_it']\n", ("helper",)),+ # a module that hands out logic is an ordinary facade module, where a body is allowed+ ("from ..logic.crud import run_it\n\n__all__ = ['run_it']\n", None),+ # an alias may name the wiring package itself rather than a name inside it, and then the+ # module the facade hands out is that package. Both spellings reach the same directory.+ ("from products.my_product.backend import tasks as tasks\n", ("helper",)),+ ("from .. import tasks\n\n__all__ = ['tasks']\n", ("helper",)),+ ],+ )+ def test_a_capability_module_is_recognized_by_what_it_hands_out(+ self, tmp_path: Path, reexport: str, expected: tuple[str, ...] | None+ ) -> None:+ backend = _write_shape_product(+ tmp_path,+ {"wiring.py": f"{reexport}\n\ndef helper():\n return 1\n"},+ sources={+ "temporal/flows.py": "def run_it():\n ...\n",+ "logic/crud.py": "def run_it():\n ...\n",+ "tasks/__init__.py": "def run_it():\n ...\n",+ },+ )+ logic = [f for f in facade_shape_findings(backend, "my_product") if f.kind == "logic"]+ assert [f.bodies for f in logic] == ([expected] if expected else [])+++class TestFacadeShapeLedgerRows:+ @pytest.mark.parametrize(+ "facade_files, expected",+ [+ # a product model keeps `<product>.<Class>` in the first column, like every other+ # crossing row, so one grep over the ledger finds every way the class leaves+ (+ {"api.py": "from ..models import Thing\n\n\ndef get_thing() -> Thing:\n return Thing()\n"},+ "my_product.Thing products.my_product.backend.facade.api.get_thing facade-returns 1",+ ),+ # everything else names the library it comes from, so `QuerySet` cannot read as a class+ (+ {"api.py": "from django.db.models import QuerySet\n\n\ndef things() -> QuerySet:\n ...\n"},+ "django.QuerySet products.my_product.backend.facade.api.things facade-returns 1",+ ),+ # the parameter rides in the kind, the way drives(...) and reverse-accessor(...) carry+ # their detail, so the row stays four fields wide+ (+ {"api.py": "from typing import Any\n\n\ndef digest(team: Any) -> None:\n return None\n"},+ "typing.Any products.my_product.backend.facade.api.digest facade-accepts(team) 1",+ ),+ # a method keeps its class in the path, and the parameter never enters it+ (+ {+ "api.py": "from ..models import Thing\n\n\nclass Mapper:\n def to_contract(self, row: Thing) -> None:\n return None\n"+ },+ "my_product.Thing products.my_product.backend.facade.api.Mapper.to_contract facade-accepts(row) 1",+ ),+ # a logic row has no type to name, so it is keyed by the module that holds the bodies —+ # the same location shape the drives(...) rows use — and counted in the count column+ (+ {+ "tasks.py": "from celery import shared_task\n\n\n@shared_task\ndef run_it() -> None:\n print(1)\n\n\ndef helper() -> None:\n print(2)\n"+ },+ "my_product:backend/facade/tasks.py products.my_product.backend.facade.tasks facade-logic 2",+ ),+ ],+ )+ def test_a_finding_renders_one_ledger_row(+ self, tmp_path: Path, facade_files: dict[str, str], expected: str+ ) -> None:+ backend = _write_shape_product(tmp_path, facade_files)+ findings = facade_shape_findings(backend, "my_product")+ assert [facade_shape_use(f).as_baseline_line() for f in findings] == [expected]+++class TestFacadeShapeBaseline:+ _ROW = "my_product.Thing products.my_product.backend.facade.api.get_thing facade-returns 1"++ def _leaking_product(self, tmp_path: Path) -> CheckContext:+ ctx = _make_product(tmp_path, isolated=True)+ (ctx.backend_dir / "models.py").write_text(_MODELS_PY)+ (ctx.backend_dir / "facade" / "api.py").write_text(+ "from ..models import Thing\n\n\ndef get_thing() -> Thing:\n return Thing()\n"+ )+ return ctx++ def test_an_unrecorded_finding_fails_and_a_recorded_one_only_warns(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Both directions of the same fixture: without the ratchet the debt would either block every+ # product on day one or never block anything.+ ctx = self._leaking_product(tmp_path)+ monkeypatch.setattr(checks_module, "recorded_facade_shape_rows", lambda name: frozenset())+ unrecorded = FacadeShapeCheck().run(ctx)+ assert any("returns my_product.Thing" in i and "frozen contract" in i for i in unrecorded.issues)++ monkeypatch.setattr(checks_module, "recorded_facade_shape_rows", lambda name: frozenset({self._ROW}))+ recorded = FacadeShapeCheck().run(ctx)+ assert recorded.issues == []+ assert recorded.lines == ["⚠ facade shape debt: 1 rows"]diff --git a/tools/hogli-commands/hogli_commands/tests/test_crossings.py b/tools/hogli-commands/hogli_commands/tests/test_crossings.pyindex 81faadba7335..14341b2b2e7c 100644--- a/tools/hogli-commands/hogli_commands/tests/test_crossings.py+++ b/tools/hogli-commands/hogli_commands/tests/test_crossings.py@@ -808,11 +808,14 @@ class TestGarageDrives:assert hint.matches(b'client.post(url, {"query": {"kind": NodeKind.PATHS_QUERY}})')assert not hint.matches(b"NodeKind.TRENDS_QUERY")- def test_driven_wiring_locations_reads_the_products_lines(self, tmp_path: Path) -> None:+ def test_driven_wiring_locations_reads_the_products_drives_lines(self, tmp_path: Path) -> None:+ # A facade-logic line is keyed by a location too, so matching the product prefix alone would+ # report backend/facade/ as a wiring location no test outside the product drives.baseline = tmp_path / "baseline.txt"baseline.write_text("# header\n""product_analytics:backend/hogql_queries/ posthog.api.test.test_x drives(PathsQuery) 1\n"+ "product_analytics:backend/facade/models.py products.product_analytics.backend.facade.models facade-logic 1\n""product_analytics.Insight posthog.api.sharing instance-many(all) 1\n""web_analytics:backend/hogql_queries/ posthog.test.test_y drives(WebOverviewQueryRunner) 1\n")