: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): watch a wiring location only while an outside test drives it (#89147)
Julian Bezf3b768e27594
diff --git a/posthog/test/repo_invariants/test_model_crossing_uses.py b/posthog/test/repo_invariants/test_model_crossing_uses.pyindex 420d7233f7d4..231d25fbd56e 100644--- a/posthog/test/repo_invariants/test_model_crossing_uses.py+++ b/posthog/test/repo_invariants/test_model_crossing_uses.py@@ -6,7 +6,13 @@ frozen here, so the count can fall but never rise.`apps.get_model` is frozen the same way, for every product model rather than only the listed ones:it resolves through the Django app registry, so no import linter can see the edge. Test modules stay-out of scope, which keeps the pattern available to core test fixtures.+out of scope on that channel.++`drives(...)` lines read tests only: a test outside a product that executes a query runner in the+product's wiring location `backend/hogql_queries/`. `drives(<Kind>)` is a query kind the test builds+and runs; `drives(<Name>)` is a name it imports from there. `hogli product:lint` keeps that location+in the product's contract-check inputs while a line stands, so the isolated tests stay sound. A new+line is a new outside test that drives product code, and that test belongs in the product.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.@@ -36,8 +42,9 @@ def test_disallowed_crossing_uses_match_the_baseline() -> None:"change the caller: move the query, serializer or write into the model's own product and ""call a facade function instead. A 'get_model' line is an apps.get_model reference from ""outside the owning product; it is a coupling the import linters cannot see, and it belongs "- "behind a facade function too. Only a doctrine amendment in products/architecture.md "- "§ Wiring couplings can add a line.\n"+ "behind a facade function too. A 'drives(...)' line is a test outside the product that executes "+ "one of its query runners; move that test into the product. Only a doctrine amendment in "+ "products/architecture.md § Wiring couplings can add a line.\n"f"A '-' line means a use went away — good, but the file must record that too. Run: {REGENERATE}\n"f"{report}")diff --git a/products/architecture.md b/products/architecture.mdindex 74653b72ba7a..1cc8b4a14e9f 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -98,7 +98,15 @@ These cross the boundary as classes — allowed only under all three rules:Extending the list is a core PR: define the base and validate at the registration point.DRF viewsets are not part of this channel: they live in `presentation/`, register through `routes.py`, and never pass through the facade (a facade must not import DRF, and not its own `presentation/`; the `facade must not import presentation or DRF` import-linter contract enforces both, with the existing violations grandfathered in its TODO list) — their soundness is governed by the presentation rules above.2. **Designated location.**- The implementation lives in the product's wiring location — `backend/hogql_queries/`, `backend/max_tools.py`, `backend/temporal/`, `backend/tasks/` (a flat `backend/tasks.py` also qualifies) — and isolated products keep those locations in their `backend:contract-check` inputs, so any change to a wiring implementation still re-runs the full suite.+ The implementation lives in the product's wiring location — `backend/hogql_queries/`, `backend/max_tools.py`, `backend/temporal/`, `backend/tasks/` (a flat `backend/tasks.py` also qualifies).+ An isolated product keeps a wiring location in its `backend:contract-check` inputs while a test outside the product can execute what lives there, so such a change still re-runs the full suite.+ The full suite matters only while such a test exists.+ For `backend/hogql_queries/` that is measured.+ Core dispatches runners by query kind, so `hogli product:crossings` reads the dispatch table and records every outside test that runs one of the product's kinds, or imports anything from the location, as a `drives(...)` line in the crossings baseline.+ A test whose kind the scan cannot read statically counts as `drives(unresolved-kind)` against every query location it could reach, so an unreadable spelling holds the inputs instead of releasing them in silence.+ `hogli product:lint` keeps the location in the inputs while a line for it stands, and lets it go when none does.+ Nothing is declared. Move the driving tests into the product, regenerate the baseline, and the input may leave.+ The other locations stay in the inputs by presence until their channel (Celery task names, Temporal workflow names, Max tool names) is read the same way.3. **Validated registration.**Registration points check `issubclass(cls, Base)` and reject anything else.Import linters (tach, import-linter) see only the import graph; _what an object is_ can only be checked at runtime, at the door.@@ -158,6 +166,9 @@ Production code may not add one.**The ratchet.**`products/model_crossing_uses_baseline.txt` records every disallowed use still in the tree: one line for each model class, consumer module, kind, and count.+`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.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.@@ -533,7 +544,7 @@ Turbo uses file-based inputs to determine cache validity. The key distinction:- `backend/facade/contracts.py` — frozen dataclasses (enums can live here too)- `backend/facade/enums.py` — optional, for exported enums/constants/shared types when contracts.py grows-- the product's wiring locations (`backend/hogql_queries/`, `backend/max_tools.py`, `backend/temporal/`, `backend/tasks/`) — implementations core registers and drives (see [Wiring couplings](#wiring-couplings))+- the product's wiring locations (`backend/hogql_queries/`, `backend/max_tools.py`, `backend/temporal/`, `backend/tasks/`) — implementations core registers and drives (see [Wiring couplings](#wiring-couplings)); `backend/hogql_queries/` may leave the list once the crossings baseline records no outside test driving it, the others stay by presence**Implementation inputs** (used by `backend:test`):diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 5360f2edabeb..d1013f5de475 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -2,17 +2,22 @@# One line per (product.Class, consumer module, kind, count); see products/architecture.md# § Wiring couplings for which shapes are allowed.#-# Two channels land here. Name-level uses of a watched-models crossing class, in any kind the-# doctrine does not call instance-free. And the kind `get_model`: an `apps.get_model` reference+# Three 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 channels: a migration reaches a model-# through the historical registry, which is the only way a migration can.+# Test modules and migrations are out of scope on both: a migration reaches a model through the+# historical registry, which is the only way a migration can.+# And the kind `drives(<Kind or Name>)`, read from tests only: a test outside the product that+# executes a query runner in the product's wiring location backend/hogql_queries/, by the query+# kind it builds and runs, or by the name it imports from there. While a line stands for a+# location, `hogli product:lint` keeps that location in the contract-check inputs.## Counts may only go down, and a line that disappears must be deleted here too.# A new line needs a doctrine amendment, not a baseline edit.## Regenerate: bin/hogli product:crossings --all --write-baselinecanvas.Canvas products.tasks.backend.logic.services.loop_runs get_model 1+customer_analytics:backend/hogql_queries/ posthog.api.test.test_sharing drives(AccountsQuery) 1data_modeling.DataWarehouseSavedQuery products.customer_analytics.backend.facade.api get_model 5error_tracking.ErrorTrackingIssue products.demo.backend.logic.products.hedgebox.matrix get_model 1error_tracking.ErrorTrackingIssue products.posthog_ai.evals.error_tracking.seeders get_model 1@@ -23,6 +28,16 @@ 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/hogql_queries/ products.posthog_ai.eval_harness.test.test_eval_seeders drives(ErrorTrackingQueryRunner) 1+error_tracking:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_insight_query drives(ErrorTrackingQuery) 1+experiments:backend/hogql_queries/ ee.clickhouse.views.test.test_experiment_saved_metrics drives(ExperimentTrendsQuery) 2+experiments:backend/hogql_queries/ posthog.session_recordings.queries.test.listing_recordings.test_session_recordings_list_by_experiment_exposure drives(ExposureQueryBuilder) 1+experiments:backend/hogql_queries/ posthog.temporal.experiments.test_cache_warming drives(ExperimentQueryRunner) 2+experiments:backend/hogql_queries/ posthog.temporal.experiments.test_cache_warming drives(ExperimentQueryRunnerBaseTest) 1+experiments:backend/hogql_queries/ posthog.temporal.experiments.test_cache_warming drives(compute_metric_fingerprint) 2+experiments:backend/hogql_queries/ posthog.temporal.experiments.test_cache_warming drives(get_experiment_stats_method) 2+experiments:backend/hogql_queries/ products.actions.backend.api.test.test_action drives(ExperimentTrendsQuery) 3+metrics:backend/hogql_queries/ posthog.tasks.alerts.test.test_metrics_alerts drives(MetricsQuery) 1product_analytics.Insight ee.api.subscription instance-many(filter) 2product_analytics.Insight ee.api.subscription instance-many(manager) 2product_analytics.Insight ee.hogai.artifacts.handlers.visualization instance-many(filter) 1@@ -233,3 +248,58 @@ 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:backend/hogql_queries/ ee.clickhouse.views.test.test_experiment_saved_metrics drives(TrendsQuery) 2+web_analytics:backend/hogql_queries/ posthog.api.test.dashboards.test_dashboard drives(TrendsQuery) 5+web_analytics:backend/hogql_queries/ posthog.api.test.test_alert_15_minute_interval drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ posthog.api.test.test_alert_real_time_interval drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ posthog.api.test.test_cohort drives(TrendsQuery) 6+web_analytics:backend/hogql_queries/ posthog.api.test.test_query drives(TrendsQuery) 3+web_analytics:backend/hogql_queries/ posthog.api.test.test_sharing drives(TrendsQuery) 6+web_analytics:backend/hogql_queries/ posthog.api.test.test_sharing_access_token_security drives(TrendsQuery) 12+web_analytics:backend/hogql_queries/ posthog.hogql.database.schema.test.test_persons drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ posthog.hogql.functions.test.test_traffic_type_functions drives(BOT_DEFINITIONS) 7+web_analytics:backend/hogql_queries/ posthog.hogql.functions.test.test_traffic_type_functions drives(BOT_IP_DEFINITIONS) 4+web_analytics:backend/hogql_queries/ posthog.hogql.functions.test.test_traffic_type_real_ua drives(BOT_DEFINITIONS) 4+web_analytics:backend/hogql_queries/ posthog.hogql.functions.test.test_traffic_type_real_ua drives(BOT_IP_DEFINITIONS) 3+web_analytics:backend/hogql_queries/ posthog.hogql.functions.test.test_traffic_type_real_ua drives(BOT_USER_AGENTS) 3+web_analytics:backend/hogql_queries/ posthog.hogql.functions.test.test_traffic_type_real_ua drives(CATEGORY_TO_TRAFFIC_CATEGORY) 2+web_analytics:backend/hogql_queries/ posthog.hogql.transforms.test.test_preaggregated_table_transformation drives(EVENT_PROPERTY_TO_FIELD) 4+web_analytics:backend/hogql_queries/ posthog.hogql.transforms.test.test_preaggregated_table_transformation drives(SESSION_PROPERTY_TO_FIELD) 4+web_analytics:backend/hogql_queries/ posthog.hogql_queries.insights.test.test_insight_actors_query_runner drives(TrendsQuery) 7+web_analytics:backend/hogql_queries/ posthog.hogql_queries.insights.trends.test.test_trends_data_warehouse_query drives(TrendsQuery) 23+web_analytics:backend/hogql_queries/ posthog.hogql_queries.insights.trends.test.test_trends_query_builder drives(TrendsQuery) 7+web_analytics:backend/hogql_queries/ posthog.hogql_queries.insights.trends.test.test_trends_query_runner drives(TrendsQuery) 2+web_analytics:backend/hogql_queries/ posthog.hogql_queries.test.test_query_runner drives(TrendsQuery) 4+web_analytics:backend/hogql_queries/ posthog.models.web_preaggregated.test_web_pre_aggregated_timezones drives(FloatAwareTestCase) 1+web_analytics:backend/hogql_queries/ posthog.models.web_preaggregated.test_web_pre_aggregated_timezones drives(WebAnalyticsPreAggregatedTestBase) 1+web_analytics:backend/hogql_queries/ posthog.models.web_preaggregated.test_web_pre_aggregated_timezones drives(WebStatsTableQueryRunner) 2+web_analytics:backend/hogql_queries/ posthog.models.web_preaggregated.test_web_preaggregated_sql drives(WebAnalyticsPreAggregatedTestBase) 1+web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_alert_check_helpers drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_alert_evaluation drives(TrendsQuery) 5+web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_alert_subscriptions drives(TrendsQuery) 3+web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_metrics_alerts drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_trends_absolute_alerts drives(TrendsQuery) 2+web_analytics:backend/hogql_queries/ posthog.tasks.alerts.test.test_trends_relative_alerts drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ posthog.test.activity_log_utils drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ posthog.test.base drives(stats_table) 1+web_analytics:backend/hogql_queries/ posthog.test.base drives(web_overview) 1+web_analytics:backend/hogql_queries/ products.actions.backend.api.test.test_action drives(TrendsQuery) 9+web_analytics:backend/hogql_queries/ products.alerts.backend.tests.api.test_alert drives(TrendsQuery) 7+web_analytics:backend/hogql_queries/ products.dashboards.backend.api.test.test_dashboard_templates drives(TrendsQuery) 2+web_analytics:backend/hogql_queries/ products.dashboards.backend.api.test.test_run_insights drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ products.data_warehouse.backend.tests.api.test_data_warehouse drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_endpoint drives(TrendsQuery) 12+web_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_endpoint_ducklake_shadow drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_endpoint_execution drives(TrendsQuery) 32+web_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_endpoint_materialization drives(TrendsQuery) 9+web_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_insight_response_parity drives(TrendsQuery) 6+web_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_materialization_suggestion drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_openapi_spec drives(TrendsQuery) 4+web_analytics:backend/hogql_queries/ products.experiments.backend.test.test_presentation_api drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ products.feature_flags.backend.api.test.test_feature_flag drives(TrendsQuery) 6+web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_insight drives(TrendsQuery) 19+web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_insight_metadata drives(TrendsQuery) 5+web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_insight_query drives(TrendsQuery) 4+web_analytics:backend/hogql_queries/ products.product_analytics.backend.tests.api.test_paths_v2 drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ products.signals.backend.test.test_scout_report_api drives(TrendsQuery) 1+web_analytics:backend/hogql_queries/ products.tasks.backend.tests.test_api drives(TrendsQuery) 3diff --git a/products/product_analytics/turbo.json b/products/product_analytics/turbo.jsonindex 545458f55c59..0be4d6c10996 100644--- a/products/product_analytics/turbo.json+++ b/products/product_analytics/turbo.json@@ -7,9 +7,7 @@"backend/presentation/**","backend/routes.py","backend/models/**",- "backend/migrations/**",- "backend/hogql_queries/**",- "!backend/hogql_queries/*/test/**"+ "backend/migrations/**"],"outputs": [],"cache": truediff --git a/tools/hogli-commands/hogli_commands/product/checks.py b/tools/hogli-commands/hogli_commands/product/checks.pyindex b7cfa206e59d..cd0bdfe7e5fd 100644--- a/tools/hogli-commands/hogli_commands/product/checks.py+++ b/tools/hogli-commands/hogli_commands/product/checks.py@@ -17,6 +17,7 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom .ast_helpers import module_import_targets+from .crossings import driven_wiring_locationsfrom .isolation import (IsolationStatus,compute_isolation_status,@@ -262,7 +263,11 @@ class CheckContext:"""if self._isolation is None:self._isolation = compute_isolation_status(- self.name, self.product_dir, self.backend_dir, is_isolated=self.is_isolated+ self.name,+ self.product_dir,+ self.backend_dir,+ is_isolated=self.is_isolated,+ driven_wiring_locations=driven_wiring_locations(self.name),)return self._isolation@@ -763,7 +768,7 @@ class IsolationChainCheck(ProductCheck):"a real facade should convert models to contracts, not just re-export")- # The wiring-doctrine gate. Facade class re-exports from a non-garage module gate NARROWING,+ # The wiring-doctrine gate. Facade class re-exports from outside a wiring location gate NARROWING,# not the script: while a product is un-narrowed the skip is inert (everything is watched), so# a leak there is guidance, not breakage. Once narrowed, the same leak means core can reach an# unsanctioned class the suite may not re-test — a hard error. See products/architecture.md@@ -786,7 +791,7 @@ class IsolationChainCheck(ProductCheck):if facade_violations:detail = format_facade_imports(facade_violations)remedies = (- "move it to a garage (backend/hogql_queries/, backend/max_tools.py, backend/temporal/, "+ "move it to a wiring location (backend/hogql_queries/, backend/max_tools.py, backend/temporal/, ""backend/tasks.py) if it implements a core-owned base; move it to facade/contracts.py ""if it's a data/error type; or drop the turbo.json narrowing to watch everything")@@ -881,15 +886,24 @@ class IsolationChainCheck(ProductCheck):f"would skip the Django suite. Add the matching input(s) ({globs}) to keep the skip sound")- # Watching the wiring garages: a garage the product has must stay in the contract-check+ # Watching the wiring locations: a location the product has must stay in the contract-check# inputs, or a change to a query runner / Max tool / Temporal defn / Celery task the facade- # wires would skip the Django suite. Mirrors routes_unwatched, presence-based.+ # wires would skip the Django suite. Presence-based, except for the computed locations,+ # which are listed only while the crossings baseline records an outside test driving them.if has_narrowed and status.unwatched_garages:globs = ", ".join(location_input_glob(g) for g in status.unwatched_garages)+ 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."+ if driven+ else ""+ )result.issues.append("turbo.json narrows contract-check inputs but omits the wiring location(s) "f"{', '.join(status.unwatched_garages)} — implementations core registers and drives live there, "- f"so a change to them would skip the Django suite. Add the matching input(s) ({globs})"+ f"so a change to them would skip the Django suite. Add the matching input(s) ({globs}).{evidence}")# Watching the carve-out modules: a sanctioned model-registry carve-out crosses the facade bydiff --git a/tools/hogli-commands/hogli_commands/product/crossings.py b/tools/hogli-commands/hogli_commands/product/crossings.pyindex 252bcb3fd2b5..0dfbe429c4fe 100644--- a/tools/hogli-commands/hogli_commands/product/crossings.py+++ b/tools/hogli-commands/hogli_commands/product/crossings.py@@ -18,9 +18,21 @@ resolves through the Django app registry, leaves no import edge, and so reachesfrom anywhere. That scan therefore runs over every model class a product registers, and each foreignreference is counted as the disallowed kind `get_model`.-Tests are out of scope. A test reaches concrete classes through testing doors on purpose, so counting-its fixtures would measure the fixture, not the coupling. That leaves `apps.get_model` in a test-fixture uncounted; it is still a dependency with the import edge removed, not a sanctioned door.+Tests are out of scope on both model channels. A test reaches concrete classes through testing doors+on purpose, so counting its fixtures would measure the fixture, not the coupling. That leaves+`apps.get_model` in a test fixture uncounted; it is still a dependency with the import edge removed,+not a sanctioned door.++The third channel reads tests only. Core runs a product's query runners by the query's kind string.+A test outside the product can therefore execute a runner in the wiring location+`backend/hogql_queries/` with no import. The isolated tests are sound for that location only while+no such test exists. Each such test is counted as the disallowed kind `drives(<Kind>)`, and+`hogli product:lint` keeps the location in the contract-check inputs while a line for it stands. A+test that imports anything the location defines, through the facade or directly, is counted as+`drives(<Name>)`. Python spells a kind in more ways than a scan can read, and a kind it cannot read+yields no line at all, which reads the same as no dependency. Such a test is counted as+`drives(unresolved-kind)` against every query location it could reach, so the unreadable case holds+the inputs rather than releasing them in silence."""from __future__ import annotations@@ -29,13 +41,15 @@ import osimport reimport astimport textwrap+import warnings+import functoolsfrom collections import Counter, defaultdict-from collections.abc import Iterable, Iterator+from collections.abc import Callable, Iterable, Iterator, Mappingfrom dataclasses import dataclassfrom pathlib import Path-from .ast_helpers import ast_parse_safe, get_model_names-from .isolation import MODEL_CROSSINGS, facade_model_crossings+from .ast_helpers import ast_parse_safe, get_model_names, lazy_reexport_map+from .isolation import COMPUTED_WIRING_LOCATIONS, MODEL_CROSSINGS, facade_model_crossingsfrom .paths import PRODUCTS_DIR, REPO_ROOT# Where Python that can consume a product model lives. Everything else at the repo root is@@ -231,12 +245,16 @@ def product_model_labels(products: Iterable[str] | None = None) -> dict[str, str# ---------------------------------------------------------------------------+def _is_test_module(path: Path) -> bool:+ if "test" in path.parts or "tests" in path.parts:+ return True+ return path.name.startswith("test_") or path.name.endswith("_test.py") or path.name == "conftest.py"++def _is_out_of_scope_module(path: Path) -> bool:"""Tests reach concrete classes through testing doors, so they are not consumers. A migrationreaches a model through the historical registry, which is the only way a migration can."""- if "test" in path.parts or "tests" in path.parts or "migrations" in path.parts:- return True- return path.name.startswith("test_") or path.name.endswith("_test.py") or path.name == "conftest.py"+ return _is_test_module(path) or "migrations" in path.parts@dataclass(frozen=True, slots=True)@@ -272,6 +290,8 @@ class _Candidate:dotted: strimports: _ImportTablementions_get_model: bool+ mentions_query_kind: bool = False+ mentions_dispatcher: bool = False# One import statement, parenthesized or not. Imports are the only thing the first pass reads, and@@ -325,11 +345,13 @@ def _read_imports(source: bytes, package: str) -> _ImportTable:return _ImportTable(tuple(edges), tuple(aliases))-def _candidates() -> list[_Candidate]:+def _candidates(kind_hint: _KindHint | None = None) -> list[_Candidate]:"""Every scanned .py file, with its imports read.Reading imports only is what keeps the full AST pass — and so the repo-invariant test — small:- a file is parsed whole only once its imports show it can reach a crossing class."""+ a file is parsed whole only once its imports show it can reach a crossing class. The two+ textual hints (`get_model`, a product query kind) are read here too, while the bytes are in+ hand, so the scan never re-reads a file just to rule it out."""found = []for root in SCANNED_ROOTS:for path in sorted((REPO_ROOT / root).rglob("*.py")):@@ -338,7 +360,19 @@ def _candidates() -> list[_Candidate]:source = path.read_bytes()dotted = _dotted_module(path)package = dotted if path.name == "__init__.py" else dotted.rsplit(".", 1)[0]- found.append(_Candidate(path, dotted, _read_imports(source, package), b"get_model" in source))+ is_test = _is_test_module(path)+ mentions_kind = kind_hint is not None and is_test and kind_hint.matches(source)+ mentions_dispatch = is_test and any(call in source for call in _DISPATCH_CALL_BYTES)+ found.append(+ _Candidate(+ path,+ dotted,+ _read_imports(source, package),+ b"get_model" in source,+ mentions_kind,+ mentions_dispatch,+ )+ )return found@@ -356,11 +390,14 @@ class _Export:def _origins(candidates: list[_Candidate], classes: list[CrossingClass]) -> dict[_Export, str]:- """Export -> crossing label, for every path an import of the class can take.+ """Export -> crossing label, for every path an import of the class can take."""+ return _grow_origins(candidates, {_Export(c.defining_module, c.class_name): c.label for c in classes})- Seeded with the defining module and grown to a fixpoint over re-exports, so `facade/models.py`,- a package `__init__`, and a renaming alias all resolve back to the same class."""- origins: dict[_Export, str] = {_Export(c.defining_module, c.class_name): c.label for c in classes}++def _grow_origins(candidates: list[_Candidate], seeds: dict[_Export, str]) -> dict[_Export, str]:+ """Seeded with the defining module and grown to a fixpoint over re-exports, so `facade/models.py`,+ a package `__init__`, and a renaming alias all resolve back to the same label."""+ origins = dict(seeds)while True:grew = Falsefor candidate in candidates:@@ -395,6 +432,15 @@ def _dotted_of(node: ast.expr) -> str | None:return None+def _callee_name(node: ast.Call) -> str | None:+ func = node.func+ if isinstance(func, ast.Name):+ return func.id+ if isinstance(func, ast.Attribute):+ return func.attr+ return None++def _class_nodes(tree: ast.Module, names: dict[str, str], module_aliases: dict[str, str], origins: dict[_Export, str]) -> list[tuple[ast.expr, str]]:@@ -445,10 +491,9 @@ def _enclosing_call_name(node: ast.AST, parents: dict[int, ast.AST]) -> str | Nocurrent = parents.get(id(node))while current is not None:if isinstance(current, ast.Call):- func = current.func- name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)+ name = _callee_name(current)if name:- return str(name)+ return nameif isinstance(current, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):return Nonecurrent = parents.get(id(current))@@ -564,66 +609,768 @@ def _get_model_uses(tree: ast.Module, product_by_label: dict[str, str], label_byreturn found+# ---------------------------------------------------------------------------+# Wiring locations that tests outside the product drive+# ---------------------------------------------------------------------------+++# Core's query dispatch table: `if kind == "X": from products.<p>... import XRunner`, and the+# wiring location that holds the runners it dispatches to. The kind channel is what makes that+# location computable, so it must be in the computed set. Some branches compare against the+# `NodeKind` enum instead of a literal; the enum values are read off the generated module.+QUERY_DISPATCHER = REPO_ROOT / "posthog" / "hogql_queries" / "query_runner.py"+NODE_KIND_ENUM = REPO_ROOT / "posthog" / "schema_enums.py"+_NODE_KIND_CLASS_RE = re.compile(r"^class (\w*NodeKind)\(.*?\):\n(.*?)(?=^class |\Z)", re.MULTILINE | re.DOTALL)+_ENUM_MEMBER_RE = re.compile(r"^\s+(\w+)\s*=\s*[\"'](\w+)[\"']", re.MULTILINE)+QUERY_WIRING_LOCATION = "backend/hogql_queries/"+assert QUERY_WIRING_LOCATION in COMPUTED_WIRING_LOCATIONS++# The calls that hand a query to core's dispatcher, and so execute whichever runner owns its kind.+# `execute_hogql_query` belongs here because a HogQL string can embed a query in tag syntax+# (`<StickinessQuery ... />`), which the executor dispatches to that kind's runner.+DISPATCH_CALLS: frozenset[str] = frozenset(+ {+ "process_query_dict",+ "process_query_model",+ "process_query",+ "get_query_runner",+ "get_query_runner_or_none",+ "execute_hogql_query",+ }+)++# Read as text in the first pass, to admit a test that calls a dispatcher but names no kind.+_DISPATCH_CALL_BYTES: tuple[bytes, ...] = tuple(sorted(call.encode() for call in DISPATCH_CALLS))++# The Django test client runs a request in-process, so a query posted to any endpoint that executes+# queries (query, insights, endpoints, exports) reaches the runner the same way.+TEST_CLIENT_METHODS: frozenset[str] = frozenset({"get", "post", "put", "patch", "delete"})+++def wiring_location_label(product: str, location: str) -> str:+ """The baseline label of one product's wiring location, e.g. `product_analytics:backend/hogql_queries/`."""+ return f"{product}:{location}"+++@dataclass(frozen=True, slots=True, order=True)+class _WiringLocation:+ """One computed wiring location of one product."""++ product: str+ location: str++ @property+ def label(self) -> str:+ return wiring_location_label(self.product, self.location)+++@dataclass(frozen=True, slots=True)+class _KindDrive:+ """A product query kind a test both builds and runs."""++ product: str+ kind: str+++@dataclass(frozen=True, slots=True)+class _ModuleDrive:+ """A wiring-location module a test binds as an object."""++ label: str # wiring_location_label(...)+ module: str # the module's own name, e.g. "web_overview"+++def _node_kind_enums(source: str) -> dict[str, dict[str, str]]:+ """Enum class name -> its member name -> kind string, read off the source without importing it.++ `NodeKind` is not the only enum that carries query kinds. `InsightNodeKind` repeats the insight+ subset, and a test reaches the same runner through either one, so both must be read."""+ return {name: dict(_ENUM_MEMBER_RE.findall(body)) for name, body in _NODE_KIND_CLASS_RE.findall(source)}+++def _node_kind_values(source: str) -> dict[str, str]:+ """Member name -> kind string, across every enum that carries query kinds."""+ values: dict[str, str] = {}+ for members in _node_kind_enums(source).values():+ values |= members+ return values+++def _kinds_in_dispatcher(source: str, node_kinds: Mapping[str, str] | None = None) -> dict[str, frozenset[str]]:+ """Query kind -> products whose runners its dispatch branch can reach.++ The whole branch is read, not only its direct statements: a core kind can hand off to a+ product runner under a nested condition (a trends query tagged for web analytics), and a test+ that runs that kind may then execute product code."""+ tree = ast.parse(source)+ kinds: dict[str, set[str]] = {}+ for node in ast.walk(tree):+ if not isinstance(node, ast.If):+ continue+ branch_kinds = _compared_kinds(node.test, node_kinds or {})+ if not branch_kinds:+ continue+ products = {+ statement.module.split(".")[1]+ for body_statement in node.body+ for statement in ast.walk(body_statement)+ if isinstance(statement, ast.ImportFrom) and statement.module and statement.module.startswith("products.")+ }+ for kind in branch_kinds:+ kinds.setdefault(kind, set()).update(products)+ return {kind: frozenset(products) for kind, products in kinds.items() if products}+++def _compared_kinds(test: ast.expr, node_kinds: Mapping[str, str]) -> list[str]:+ """The kinds of `kind == "X"`, `kind == NodeKind.X`, or `kind in (...)`; empty for any other test."""+ if not (isinstance(test, ast.Compare) and isinstance(test.left, ast.Name) and test.left.id == "kind"):+ return []+ target = test.comparators[0]+ members = target.elts if isinstance(target, ast.Tuple) else [target]+ kinds = []+ for member in members:+ if isinstance(member, ast.Constant) and isinstance(member.value, str):+ kinds.append(member.value)+ elif isinstance(member, ast.Attribute) and isinstance(member.value, ast.Name) and member.value.id == "NodeKind":+ if member.attr in node_kinds:+ kinds.append(node_kinds[member.attr])+ return kinds+++@dataclass(frozen=True)+class _QueryKinds:+ """The product query kinds core dispatches, by literal and by `NodeKind` member.++ A test names a kind either way (`"PathsQuery"` or `NodeKind.PATHS_QUERY`); both must count."""++ products: Mapping[str, frozenset[str]] # kind -> products whose runners it can reach+ members: Mapping[str, str] # enum member -> kind, for the kinds in `products`+ enums: frozenset[str] = frozenset({"NodeKind"}) # the enum classes those members live on++ def __bool__(self) -> bool:+ return bool(self.products)+++def product_query_kinds(products: Iterable[str] | None = None) -> _QueryKinds:+ """The query kinds that reach product runners, read off core's dispatch table."""+ enums = _node_kind_enums(NODE_KIND_ENUM.read_text(encoding="utf-8"))+ node_kinds = _node_kind_values(NODE_KIND_ENUM.read_text(encoding="utf-8"))+ kinds = _kinds_in_dispatcher(QUERY_DISPATCHER.read_text(encoding="utf-8"), node_kinds)+ if products is not None:+ wanted = frozenset(products)+ kinds = {kind: owners & wanted for kind, owners in kinds.items() if owners & wanted}+ return _QueryKinds(+ kinds,+ {member: kind for member, kind in node_kinds.items() if kind in kinds},+ frozenset(enums),+ )+++def _wiring_location_exports(product: str, location: str) -> dict[_Export, str]:+ """Every name a module in the wiring location defines at top level, labeled with the location.++ Classes, functions, and constants alike: a test that imports a bot-definition table from the+ location depends on it as much as one that imports a runner. A facade module that hands those+ names out through a PEP 562 lazy map is an export path too, so an import through the facade+ resolves to the location like a static re-export would."""+ label = wiring_location_label(product, location)+ root = PRODUCTS_DIR / product / location.rstrip("/")+ paths = sorted(root.rglob("*.py")) if root.is_dir() else [root] if root.is_file() else []+ exports: dict[_Export, str] = {}+ for path in paths:+ tree = ast_parse_safe(path)+ if tree is None:+ continue+ module = _dotted_module(path)+ for name in _top_level_names(tree):+ exports[_Export(module, name)] = label+ for facade_path in sorted((PRODUCTS_DIR / product / "backend" / "facade").glob("*.py")):+ tree = ast_parse_safe(facade_path)+ if tree is None:+ continue+ for name, source in _lazy_reexports(tree, product, _module_exists).items():+ if (REPO_ROOT / source.replace(".", "/")).with_suffix(".py").is_relative_to(root):+ exports[_Export(_dotted_module(facade_path), name)] = label+ return exports+++def _top_level_names(tree: ast.Module) -> list[str]:+ """Every public name a module defines at top level: classes, functions, and assigned constants."""+ names: list[str] = []+ for node in tree.body:+ if isinstance(node, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef):+ names.append(node.name)+ elif isinstance(node, ast.Assign):+ names.extend(target.id for target in node.targets if isinstance(target, ast.Name))+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):+ names.append(node.target.id)+ return [name for name in names if not name.startswith("_")]+++def module_drives(+ imports: _ImportTable, locations: Iterable[_WiringLocation], exists: Callable[[str], bool] | None = None+) -> Counter[_ModuleDrive]:+ """Every wiring-location module a test binds as an object, with how often.++ `import ...hogql_queries.web_overview as m` or `from ...hogql_queries import web_overview`+ binds the module itself, usually to patch an attribute on it. No exported name is read, so+ the origins pass cannot see it; the module alias table can. Every `from a import b` lands in+ that table as a possible module `a.b`, so only names that are modules on disk count here;+ a class imported that way is the origins pass's to count."""+ exists = exists or _module_exists+ found: Counter[_ModuleDrive] = Counter()+ prefixes = [+ (f"products.{loc.product}." + loc.location.rstrip("/").replace("/", ".") + ".", loc) for loc in locations+ ]+ for alias in imports.module_aliases:+ for prefix, location in prefixes:+ if alias.module.startswith(prefix) and exists(alias.module):+ found[_ModuleDrive(location.label, alias.module.rsplit(".", 1)[-1])] += 1+ return found+++def _module_exists(dotted: str) -> bool:+ path = REPO_ROOT / dotted.replace(".", "/")+ return path.with_suffix(".py").is_file() or (path / "__init__.py").is_file()+++def _lazy_reexports(tree: ast.Module, product: str, exists: Callable[[str], bool]) -> dict[str, str]:+ """Exported name -> absolute dotted source module, for a facade's PEP 562 lazy map.++ Lazy maps store their values relative to some package: absolute, relative to the product's+ backend 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(".")+ ]+ 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}"]+ for candidate in candidates:+ if exists(candidate):+ resolved[name] = candidate+ break+ return resolved+++def _is_test_client_call(node: ast.Call) -> bool:+ func = node.func+ if not isinstance(func, ast.Attribute) or func.attr not in TEST_CLIENT_METHODS:+ return False+ receiver = _dotted_of(func.value)+ return receiver is not None and receiver.endswith("client")+++def _kind_mentions(tree: ast.Module, kinds: _QueryKinds, names: _KindNames | None = None) -> list[tuple[ast.AST, str]]:+ """Nodes that name a product query kind: a `"X"` or `NodeKind.X` value, or the schema+ constructor `X(...)`.++ A bare value counts too: a parametrize row or a constant reaches the dispatcher through a+ variable as often as through a literal `{"kind": ...}`. What separates a drive from a mention+ is whether the enclosing test executes, which `kind_drives` decides. A URL segment or a+ substring of a longer string is not a value equal to a kind, so it does not count.++ A HogQL string that embeds a query in tag syntax (`<StickinessQuery ... />`) names the kind+ too; every tag in the string counts once.++ `names` maps the local names the module binds back to their kinds; without it, a constructor+ counts by its own name only and the enum counts only as `NodeKind`."""+ names = names or _unimported_kind_names(kinds)+ by_local = {kind: kind for kind in kinds.products} | dict(names.constructors)+ tag = re.compile(r"<(" + "|".join(sorted(re.escape(k) for k in kinds.products)) + r")\b") if kinds else None+ # `NodeKind.PATHS_QUERY.value` holds the member node inside the `.value` node, and a walk+ # reaches both. The outer node stands for the whole spelling, so the member counts once.+ consumed = {+ id(node.value)+ for node in ast.walk(tree)+ if isinstance(node, ast.Attribute) and node.attr == "value" and isinstance(node.value, ast.Attribute)+ }+ found: list[tuple[ast.AST, str]] = []+ for node in ast.walk(tree):+ if id(node) in consumed:+ continue+ if isinstance(node, ast.Constant | ast.Attribute):+ kind = _kind_of(node, kinds, names.enum_bases)+ if kind is not None:+ found.append((node, kind))+ elif tag is not None and isinstance(node, ast.Constant) and isinstance(node.value, str):+ found.extend((node, match.group(1)) for match in tag.finditer(node.value))+ elif isinstance(node, ast.Call):+ name = _callee_name(node)+ if name in by_local:+ found.append((node, by_local[name]))+ return found+++@dataclass(frozen=True)+class _KindNames:+ """The local names one module binds to the parts of a drive: schema constructors, the `NodeKind`+ enum, and the dispatchers that execute a query.++ Each of the three can carry an alias (`from posthog.schema import PathsQuery as Query`,+ `NodeKind as Kind`, `process_query_dict as run_query`). An alias reaches the runner exactly like+ the plain spelling, so each one must resolve back to the name it was imported under."""++ constructors: Mapping[str, str] # local name -> kind+ enum_bases: frozenset[str] # local names that carry the `NodeKind` members+ dispatchers: frozenset[str] # local names that execute a query+++def _unimported_kind_names(kinds: _QueryKinds) -> _KindNames:+ """The spellings that need no import of their own, because a module can reach them through a+ package path (`schema.NodeKind.PATHS_QUERY`) or call them as a method."""+ return _KindNames({}, kinds.enums, DISPATCH_CALLS)+++def _kind_names(imports: _ImportTable, kinds: _QueryKinds) -> _KindNames:+ """The kind-bearing names a module binds, under whatever local name it imports them."""+ unimported = _unimported_kind_names(kinds)+ constructors = {edge.bound: edge.exported for edge in imports.edges if edge.exported in kinds.products}+ enum_bases = {edge.bound for edge in imports.edges if edge.exported in kinds.enums}+ dispatchers = {edge.bound for edge in imports.edges if edge.exported in DISPATCH_CALLS}+ return _KindNames(+ constructors,+ frozenset(enum_bases) | unimported.enum_bases,+ frozenset(dispatchers) | unimported.dispatchers,+ )+++def _base_name(value: ast.expr) -> str | None:+ """The last name segment of a reference: `NodeKind` and `schema.NodeKind` both give `NodeKind`.++ A module that imports the enum's package rather than the enum itself reads the members off a+ dotted path, and the segment before the member is the only part that identifies the enum."""+ if isinstance(value, ast.Name):+ return value.id+ if isinstance(value, ast.Attribute):+ return value.attr+ return None+++def _kind_of(value: ast.expr, kinds: _QueryKinds, enum_bases: frozenset[str]) -> str | None:+ if isinstance(value, ast.Constant) and value.value in kinds.products:+ return str(value.value)+ # `NodeKind.PATHS_QUERY.value` names the same member as `NodeKind.PATHS_QUERY`; a `StrEnum`+ # member and its string are interchangeable at the dispatcher, and tests spell it both ways.+ if isinstance(value, ast.Attribute) and value.attr == "value":+ value = value.value+ if isinstance(value, ast.Attribute) and _base_name(value.value) in enum_bases:+ return kinds.members.get(value.attr)+ return None+++_Function = ast.FunctionDef | ast.AsyncFunctionDef+++def _enclosing(node: ast.AST, parents: dict[int, ast.AST]) -> tuple[_Function | None, ast.ClassDef | None]:+ """The nearest function and the nearest class around `node`; a decorator counts as inside its function."""+ function: _Function | None = None+ current = parents.get(id(node))+ while current is not None:+ if isinstance(current, _Function) and function is None:+ function = current+ if isinstance(current, ast.ClassDef):+ return function, current+ current = parents.get(id(current))+ return function, None+++def _executes_directly(scope: ast.AST, dispatchers: frozenset[str]) -> bool:+ return any(+ isinstance(node, ast.Call) and (_callee_name(node) in dispatchers or _is_test_client_call(node))+ for node in ast.walk(scope)+ )+++class _Executions:+ """Which functions of a module execute queries, directly or through a helper they call.++ A test method that builds a query and hands it to `self._run(...)` executes it a call away;+ helper calls are followed by name to a fixpoint, no real call graph needed. Helpers resolve+ inside the function's own class first (including bases defined in the same module), then+ among the module's top-level functions, so two unrelated classes with a method of the same+ name never answer for each other."""++ def _executes_directly(self, function: _Function) -> bool:+ if id(function) not in self._direct:+ self._direct[id(function)] = _executes_directly(function, self._dispatchers)+ return self._direct[id(function)]++ def __init__(self, tree: ast.Module, dispatchers: frozenset[str]) -> None:+ self._dispatchers = dispatchers+ self._direct: dict[int, bool] = {}+ self._module_helpers = {node.name: node for node in tree.body if isinstance(node, _Function)}+ self._classes = {node.name: node for node in tree.body if isinstance(node, ast.ClassDef)}++ def _class_helpers(self, class_def: ast.ClassDef) -> dict[str, list[_Function]]:+ """The methods a class can call on `self`: its own, then those of base classes defined in+ the same module. A name defined more than once along the hierarchy keeps every definition;+ the scan does not model Python's method resolution order, and answering "executes" when+ any definition does is the safe direction. A base from another module is out of reach."""+ helpers: dict[str, list[_Function]] = {}+ pending = [class_def]+ seen: set[int] = set()+ while pending:+ current = pending.pop()+ if id(current) in seen:+ continue+ seen.add(id(current))+ for node in ast.iter_child_nodes(current):+ if isinstance(node, _Function):+ helpers.setdefault(node.name, []).append(node)+ pending.extend(+ self._classes[base.id]+ for base in current.bases+ if isinstance(base, ast.Name) and base.id in self._classes+ )+ return helpers++ def executes(self, function: _Function, scope: ast.AST) -> bool:+ """Whether `function` executes a query, itself or through helpers followed to a fixpoint.++ Helpers resolve inside the function's own class (own methods and same-module bases), and+ among the module's top-level functions, which a method reaches by name too."""+ helpers: dict[str, list[_Function]] = {name: [node] for name, node in self._module_helpers.items()}+ if isinstance(scope, ast.ClassDef):+ for name, nodes in self._class_helpers(scope).items():+ helpers.setdefault(name, []).extend(nodes)+ seen: set[int] = set()+ pending = [function]+ while pending:+ current = pending.pop()+ if id(current) in seen:+ continue+ seen.add(id(current))+ if self._executes_directly(current):+ return True+ called = {_callee_name(node) for node in ast.walk(current) if isinstance(node, ast.Call)}+ for name in called:+ pending.extend(helpers.get(name, []))+ return False+++def kind_drives(tree: ast.Module, kinds: _QueryKinds, names: _KindNames | None = None) -> Counter[_KindDrive]:+ """Drive -> mentions, for every kind this module both builds and executes.++ Building alone is not a drive: a test that checks a schema or a formatter constructs the query+ and never runs it. Execution is a dispatcher call or a test-client request. A kind built inside+ a test function counts when that function executes (itself or through a helper it calls); a+ kind built elsewhere, a `setUp` fixture or a class attribute, counts when any function of the+ enclosing class (or of the module, outside a class) executes."""+ names = names or _unimported_kind_names(kinds)+ mentions = _kind_mentions(tree, kinds, names)+ if not mentions:+ return Counter()+ parents = _parent_map(tree)+ executions = _Executions(tree, names.dispatchers)+ scope_executes: dict[int, bool] = {}+ found: Counter[_KindDrive] = Counter()+ for node, kind in mentions:+ function, class_def = _enclosing(node, parents)+ scope: ast.AST = class_def if class_def is not None else tree+ if function is not None and function.name.startswith("test"):+ executes = executions.executes(function, scope)+ else:+ if id(scope) not in scope_executes:+ scope_executes[id(scope)] = _executes_directly(scope, names.dispatchers)+ executes = scope_executes[id(scope)]+ if executes:+ for product in kinds.products[kind]:+ found[_KindDrive(product, kind)] += 1+ return found+++# The dict keys that hold a query. Core reads `kind` at the top of a payload, and nests the real+# query under `query` (the endpoint envelope) or `source` (an insight's viz node). The key `kind`+# on its own is far too common to use as the signal: products name unrelated enums with it.+QUERY_DICT_KEYS: frozenset[str] = frozenset({"query", "source"})++UNRESOLVED_KIND_DRIVE = "drives(unresolved-kind)"+++def _constant_parameters(function: _Function | None) -> set[str]:+ """The parameters whose signature binds them to a constant.++ A helper that takes `kind="DataTableNode"` and posts it names its kind statically, even though+ the body reads a variable."""+ if function is None:+ return set()+ args = function.args+ positional = args.posonlyargs + args.args+ pairs = list(zip(positional[len(positional) - len(args.defaults) :], args.defaults))+ pairs += [(arg, default) for arg, default in zip(args.kwonlyargs, args.kw_defaults) if default is not None]+ return {arg.arg for arg, default in pairs if isinstance(default, ast.Constant)}+++def _kind_is_resolvable(value: ast.expr, enum_bases: frozenset[str], function: _Function | None) -> bool:+ """Whether the scan can tell what kind this expression names, even when the answer is "none".++ A constant and a known enum member are both answers: the scan reads the kind, and a kind that+ belongs to no product is a decision, not a gap. A name the scan cannot follow is different,+ because the kind it carries at run time stays unknown."""+ if isinstance(value, ast.Constant):+ return True+ if isinstance(value, ast.Name) and value.id in _constant_parameters(function):+ return True+ inner = value.value if isinstance(value, ast.Attribute) and value.attr == "value" else value+ return isinstance(inner, ast.Attribute) and _base_name(inner.value) in enum_bases+++def _query_position_dicts(tree: ast.Module, dispatchers: frozenset[str]) -> Iterator[ast.Dict]:+ """Every dict that sits where a query goes: a dispatcher argument, or under a `query`/`source` key."""+ for node in ast.walk(tree):+ if isinstance(node, ast.Call) and _callee_name(node) in dispatchers:+ yield from (arg for arg in node.args if isinstance(arg, ast.Dict))+ elif isinstance(node, ast.Dict):+ for key, value in zip(node.keys, node.values):+ if isinstance(key, ast.Constant) and key.value in QUERY_DICT_KEYS and isinstance(value, ast.Dict):+ yield value+++def unresolved_kind_drives(tree: ast.Module, kinds: _QueryKinds, names: _KindNames | None = None) -> int:+ """How many times this module runs a query whose kind the scan cannot resolve.++ A drive line needs a kind, so a kind the scan cannot read produces no line at all. That silence+ then reads as "no outside test drives this location", which is the one wrong answer available:+ the location leaves the contract-check inputs while a test still runs a runner inside it, and+ nothing reports it. Counting the unreadable case instead keeps every query wiring location+ watched until a person spells the kind out.++ Python has more ways to name a kind than a scan can follow, so this is the floor under the+ spellings `_kind_of` does read, not a substitute for reading them. A scope that already names a+ kind the scan resolved is not counted: the evidence for that scope stands on the resolved kind,+ and a parametrized test names its kinds in the decorator."""+ names = names or _unimported_kind_names(kinds)+ # Almost every module spells its kinds out, and the parent map and the mention pass are not+ # free, so the constants are dropped before either one is built.+ pending = [+ value+ for node in _query_position_dicts(tree, names.dispatchers)+ for key, value in zip(node.keys, node.values)+ if isinstance(key, ast.Constant) and key.value == "kind" and not isinstance(value, ast.Constant)+ ]+ if not pending:+ return 0+ parents = _parent_map(tree)+ executions = _Executions(tree, names.dispatchers)+ resolved = {id(_enclosing(node, parents)[0]) for node, _ in _kind_mentions(tree, kinds, names)}+ scope_executes: dict[int, bool] = {}+ found = 0+ for value in pending:+ function, class_def = _enclosing(value, parents)+ if _kind_is_resolvable(value, names.enum_bases, function) or id(function) in resolved:+ continue+ scope: ast.AST = class_def if class_def is not None else tree+ if function is not None and function.name.startswith("test"):+ executes = executions.executes(function, scope)+ else:+ if id(scope) not in scope_executes:+ scope_executes[id(scope)] = _executes_directly(scope, names.dispatchers)+ executes = scope_executes[id(scope)]+ found += bool(executes)+ return found+++def _wiring_location_targets(products: list[str] | None) -> set[_WiringLocation]:+ """Every computed wiring location that exists, in the products the scan covers.++ Every product with the directory counts, not only the products in the dispatch table. The+ import channel applies to all of them, and a location the scan did not read must not count as+ clean."""+ owners = [d.name for d in PRODUCTS_DIR.iterdir() if d.is_dir()] if products is None else products+ return {+ _WiringLocation(product, location)+ for location in COMPUTED_WIRING_LOCATIONS+ for product in owners+ if (PRODUCTS_DIR / product / location.rstrip("/")).exists()+ }+++def driven_wiring_locations(product: str, path: Path | None = None) -> frozenset[str]:+ """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."""+ prefix = f"{product}:"+ return frozenset(+ line.split(" ", 1)[0].removeprefix(prefix)+ for line in _baseline_lines(path or BASELINE_PATH)+ if line.startswith(prefix)+ )++[email protected]_cache(maxsize=4)+def _baseline_lines(path: Path) -> tuple[str, ...]:+ """Read once per process: `product:lint --all` asks for every product's locations in one run."""+ return tuple(read_baseline(path))++# ---------------------------------------------------------------------------# Scan# ---------------------------------------------------------------------------+def _alternation(names: Iterable[str]) -> bytes:+ return b"|".join(sorted(re.escape(n).encode() for n in names))+++@dataclass(frozen=True)+class _KindHint:+ """A cheap test for the textual shapes `_kind_mentions` accepts, so a file that only names a+ kind inside a longer string (a URL segment) is never parsed.++ The alternation over every kind is slow at each position of a large file; the longest common+ suffix of each spelling gates it with one substring search ("Query" for the kinds today,+ "_QUERY" for the enum members).++ The enum clause matches a member off any base name rather than off `NodeKind` alone, because a+ test can import the enum under an alias. That admits an unrelated `Other.PATHS_QUERY`, which+ costs one parse; `_kind_of` resolves the base against the file's imports and refuses it."""++ gate: bytes+ member_gate: bytes+ pattern: re.Pattern[bytes]++ @staticmethod+ def _common_suffix(names: Iterable[str]) -> bytes:+ return os.path.commonprefix([name[::-1] for name in names])[::-1].encode()++ @classmethod+ def for_kinds(cls, kinds: _QueryKinds) -> _KindHint:+ names = sorted(kinds.products)+ alternation = _alternation(names)+ clauses = [+ rb"[\"'](?:" + alternation + rb")[\"']",+ rb"\b(?:" + alternation + rb")\(",+ rb"\b(?:" + alternation + rb")\s+as\s",+ rb"<(?:" + alternation + rb")\b",+ ]+ if kinds.members:+ clauses.append(rb"\.(?:" + _alternation(kinds.members) + rb")\b")+ return cls(+ cls._common_suffix(names),+ cls._common_suffix(kinds.members) if kinds.members else b"",+ re.compile(rb"|".join(clauses)),+ )++ def matches(self, source: bytes) -> bool:+ """Members with no shared suffix leave the enum gate empty, which admits every file to the+ pattern: slower, and still correct. A missed drive would not be."""+ gated = self.gate in source or (self.member_gate != b"" and self.member_gate in source)+ return gated and self.pattern.search(source) is not None++def _reads_class_off_module(source: bytes, aliases: dict[str, str], class_names: set[str]) -> bool:"""Whether `alias.ClassName` appears in the text at all, for any module alias and crossing class.Most files that alias a module handing out a crossing class never read the class off it, and- this check spares them the full parse."""- names = b"|".join(sorted(re.escape(n).encode() for n in class_names))- locals_ = b"|".join(sorted(re.escape(a).encode() for a in aliases))- return re.search(rb"\b(?:" + locals_ + rb")\.(?:" + names + rb")\b", source) is not None+ this check spares them the full parse. The alias pattern is small and per file; the class names+ are matched as a set so the thousands of them are never compiled into a regex."""+ pattern = rb"\b(?:" + _alternation(aliases) + rb")\.(\w+)"+ return any(match.group(1).decode() in class_names for match in re.finditer(pattern, source))def scan_crossing_uses(products: Iterable[str] | None = None) -> list[CrossingUse]:"""Every use of every crossing class in consumer code, sorted, one entry per kind per module.- Plus every `apps.get_model` reference to any product model from outside the owning product."""- # Consumed twice below; a generator argument would silently empty the second pass.+ Plus every `apps.get_model` reference to any product model from outside the owning product.+ Plus, from test modules only, every drive of a computed wiring location: `drives(<Kind>)` for a+ query kind the test builds and runs (see `kind_drives`), `drives(<Name>)` for an import of+ anything the location defines, by any re-export path. One pass over the tree serves all three+ channels."""+ # Consumed more than once below; a generator argument would silently empty the later passes.products = list(products) if products is not None else Noneclasses = crossing_classes(products)owning_dir = {c.label: PRODUCTS_DIR / c.product for c in classes}owning_dir |= {label: PRODUCTS_DIR / product for label, product in product_model_labels(products).items()}+ kinds = product_query_kinds(products)+ locations = _wiring_location_targets(products)+ owning_dir |= {location.label: PRODUCTS_DIR / location.product for location in locations}if not owning_dir:return []- class_names = {c.class_name for c in classes}- candidates = _candidates()- origins = _origins(candidates, classes)++ seeds = {_Export(c.defining_module, c.class_name): c.label for c in classes}+ for location in sorted(locations):+ seeds |= _wiring_location_exports(location.product, location.location)+ # Tests are read for wiring-location exports only, and consumer code for model classes only.+ # A test that imports a model class (most API tests do) is then never parsed for nothing.+ names_by_scope = {+ True: {export.name for export, label in seeds.items() if ":" in label},+ False: {export.name for export, label in seeds.items() if ":" not in label},+ }+ candidates = _candidates(_KindHint.for_kinds(kinds) if kinds else None)+ origins = _grow_origins(candidates, seeds)origin_modules = {export.module for export in origins}+ query_products = {location.product for location in locations if location.location == QUERY_WIRING_LOCATION}product_by_label = _app_labels()# Django resolves a model name case-insensitively, so the get_model scan matches on the lowered form.label_by_lower = {label.lower(): label for label in owning_dir}counts: dict[tuple[str, str, str], int] = defaultdict(int)for candidate in candidates:- if _is_out_of_scope_module(candidate.path):+ is_test = _is_test_module(candidate.path)+ if not is_test and _is_out_of_scope_module(candidate.path):continue- names = _bound_names(candidate, origins)+ names = {name: label for name, label in _bound_names(candidate, origins).items() if (":" in label) == is_test}aliases = {a.alias: a.module for a in candidate.imports.module_aliases if a.module in origin_modules}- if not names and not aliases and not candidate.mentions_get_model:+ # A dispatcher call admits a test with no kind literal: an unreadable kind is exactly the+ # case that leaves nothing to hint on.+ hinted = (+ candidate.mentions_query_kind or candidate.mentions_dispatcher if is_test else candidate.mentions_get_model+ )+ if is_test:+ for drive, count in module_drives(candidate.imports, locations).items():+ if not candidate.path.is_relative_to(owning_dir[drive.label]):+ counts[(drive.label, candidate.dotted, f"drives({drive.module})")] += count+ if not names and not aliases and not hinted:continuetry:source = candidate.path.read_bytes()except OSError:continue- if not names and not candidate.mentions_get_model and not _reads_class_off_module(source, aliases, class_names):+ if not names and not hinted and not _reads_class_off_module(source, aliases, names_by_scope[is_test]):continuetry:- tree = ast.parse(source)+ with warnings.catch_warnings():+ warnings.simplefilter("ignore", SyntaxWarning)+ tree = ast.parse(source)except (SyntaxError, ValueError):continue- class_nodes = _class_nodes(tree, names, aliases, origins)- if class_nodes:- parents = _parent_map(tree)- for node, label in class_nodes:- if candidate.path.is_relative_to(owning_dir[label]):- continue+ parents: dict[int, ast.AST] | None = None+ for node, label in _class_nodes(tree, names, aliases, origins):+ if (":" in label) != is_test or candidate.path.is_relative_to(owning_dir[label]):+ continue+ # A test drives whatever it imports from a wiring location; a model class use is classified.+ if is_test:+ name = node.id if isinstance(node, ast.Name) else node.attr+ counts[(label, candidate.dotted, f"drives({name})")] += 1+ else:+ parents = parents or _parent_map(tree)counts[(label, candidate.dotted, classify_use(node, parents))] += 1- if candidate.mentions_get_model:+ if is_test and (candidate.mentions_query_kind or candidate.mentions_dispatcher):+ kind_names = _kind_names(candidate.imports, kinds)+ # An unreadable kind names no product, so it counts against every location it could reach.+ unresolved = unresolved_kind_drives(tree, kinds, kind_names)+ for product in query_products if unresolved else ():+ if candidate.path.is_relative_to(PRODUCTS_DIR / product):+ continue+ label = wiring_location_label(product, QUERY_WIRING_LOCATION)+ counts[(label, candidate.dotted, UNRESOLVED_KIND_DRIVE)] += unresolved+ for drive, count in kind_drives(tree, kinds, kind_names).items():+ if drive.product in query_products and not candidate.path.is_relative_to(PRODUCTS_DIR / drive.product):+ counts[+ (+ wiring_location_label(drive.product, QUERY_WIRING_LOCATION),+ candidate.dotted,+ f"drives({drive.kind})",+ )+ ] += count+ if not is_test and candidate.mentions_get_model:for label, count in _get_model_uses(tree, product_by_label, label_by_lower).items():if not candidate.path.is_relative_to(owning_dir[label]):counts[(label, candidate.dotted, "get_model")] += count@@ -700,11 +1447,15 @@ BASELINE_HEADER = """\# One line per (product.Class, consumer module, kind, count); see products/architecture.md# § Wiring couplings for which shapes are allowed.#-# Two channels land here. Name-level uses of a watched-models crossing class, in any kind the-# doctrine does not call instance-free. And the kind `get_model`: an `apps.get_model` reference+# Three 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 channels: a migration reaches a model-# through the historical registry, which is the only way a migration can.+# Test modules and migrations are out of scope on both: a migration reaches a model through the+# historical registry, which is the only way a migration can.+# And the kind `drives(<Kind or Name>)`, read from tests only: a test outside the product that+# executes a query runner in the product's wiring location backend/hogql_queries/, by the query+# kind it builds and runs, or by the name it imports from there. While a line stands for a+# location, `hogli product:lint` keeps that location in the contract-check inputs.## Counts may only go down, and a line that disappears must be deleted here too.# A new line needs a doctrine amendment, not a baseline edit.@@ -724,3 +1475,4 @@ def read_baseline(path: Path = BASELINE_PATH) -> list[str]:def write_baseline(uses: Iterable[CrossingUse], path: Path = BASELINE_PATH) -> None:path.write_text(render_baseline(uses))+ _baseline_lines.cache_clear()diff --git a/tools/hogli-commands/hogli_commands/product/isolation.py b/tools/hogli-commands/hogli_commands/product/isolation.pyindex c9f5d1d08c38..5a5617cbf8d4 100644--- a/tools/hogli-commands/hogli_commands/product/isolation.py+++ b/tools/hogli-commands/hogli_commands/product/isolation.py@@ -297,9 +297,9 @@ _FACADE_PREFIX = "backend/facade/"_FACADE_PRESENTATION_PREFIXES = (_FACADE_PREFIX, "backend/presentation/")_ROUTES_PREFIXES = ("backend/routes.py", "backend/routes/")-# The wiring locations ("garages"). A garage prefix is either a directory (trailing slash) or a-# single-file module; a class re-exported from one of these is accepted wiring, everything else is-# a leak. See products/architecture.md § Wiring couplings.+# The wiring locations; the identifiers below call them garages. A prefix is either a directory+# (trailing slash) or a single-file module. A class re-exported from one of these is accepted+# wiring, everything else is a leak. See products/architecture.md § Wiring couplings.GARAGE_PREFIXES: tuple[str, ...] = ("backend/hogql_queries/","backend/max_tools.py",@@ -308,6 +308,14 @@ GARAGE_PREFIXES: tuple[str, ...] = ("backend/tasks/",)+# Wiring locations whose watch is computed, not presence-based. Core runs a query runner by the+# query's kind string, so `product:crossings` can read the dispatch table and find every test+# outside the product that executes a runner (the `drives(...)` lines in the crossings baseline).+# Such a location must stay in the inputs only while a line exists for it. The other locations are+# reached through channels the scan does not read yet (Celery task names, Temporal workflow names,+# Max tool names), so they stay watched by presence until their channel is scanned too.+COMPUTED_WIRING_LOCATIONS: frozenset[str] = frozenset({"backend/hogql_queries/"})+def _glob_targets(glob: str, prefixes: tuple[str, ...]) -> bool:"""Anchored prefix test for a contract-check input glob. removeprefix (not lstrip, which strips@@ -343,7 +351,7 @@ def has_narrowed_turbo_inputs(skip inert, and a routes-only narrowing isn't a real contract surface — both are rejected.Negated globs ('!...') are excluded from the surface test.- Permanently-exposed modules, garage wiring locations, carve-out modules, and the model surface+ Permanently-exposed modules, wiring locations, carve-out modules, and the model surfaceall count as extended surface: a product may list them without forfeiting the narrowing, sincecore depends on each outside the plain facade->contracts channel and they must re-run the suiteon change (see uncovered_permanent_modules, unwatched_garages, and the carve-out/model coverage@@ -382,7 +390,7 @@ def _uncovered_locations(product_dir: Path, targets_to_prefixes: dict[str, tuple"""Targets whose accepted input forms match no narrowed contract-check input.Empty when the product has no narrowing override — everything is watched, so nothing is- uncovered. Shared by the permanent-exposure, garage, and carve-out coverage checks: same+ uncovered. Shared by the permanent-exposure, wiring-location, and carve-out coverage checks: sameanchored predicate everywhere, the convention is location-level, no glob simulation."""if not targets_to_prefixes:return set()@@ -480,9 +488,9 @@ def routes_in_turbo_inputs(product_dir: Path) -> bool:# ---------------------------------------------------------------------------## A class only crosses the boundary soundly if it implements a core-owned base and lives in a-# wiring location ("garage", GARAGE_PREFIXES above) core keeps in the contract-check inputs. These-# checks catch the two ways that breaks: a facade re-exporting a class from somewhere that ISN'T a-# garage, and a garage that exists but isn't watched. See products/architecture.md § Wiring couplings.+# wiring location (GARAGE_PREFIXES above) core keeps in the contract-check inputs. These checks+# catch the two ways that breaks: a facade re-exporting a class from outside a wiring location,+# and a wiring location that exists but isn't watched. See products/architecture.md § Wiring couplings.# Sanctioned model-registry carve-outs, keyed (product, class). These model classes cross the@@ -502,7 +510,7 @@ CARVE_OUTS: frozenset[tuple[str, str]] = frozenset(# The watched-models allowance, keyed (product, class) like CARVE_OUTS above. These facades may# hand out the named Django model class defined under backend/models/, provided the whole model# surface (models + migrations) stays in the narrowed contract-check inputs — the same soundness-# contract garages have. Sanctioned interim debt, surfaced as a standing lint warning.+# contract wiring locations have. Sanctioned interim debt, surfaced as a standing lint warning.## Keyed per class, not per product, so a product on the list can't quietly grow a new crossing: an# unlisted class is a leak again, and sanctioning it costs a doctrine amendment. The list only@@ -533,7 +541,7 @@ MODEL_SURFACE_PREFIXES: tuple[str, ...] = (*_MODEL_SOURCE_PREFIXES, "backend/mig@dataclass(frozen=True)class FacadeClassImport:- """A class a facade module re-exports from a product-internal, non-garage module."""+ """A class a facade module re-exports from a product-internal module outside a wiring location."""facade_module: str # e.g. "queries.py"class_name: str # e.g. "MetricsQueryRunner"@@ -665,7 +673,7 @@ def _is_test_module(filename: str) -> bool:def _iter_facade_class_reexports(backend_dir: Path) -> Iterator[FacadeClassImport]:- """Every product-internal class a facade module hands out, from a non-facade, non-garage module —+ """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:- a pure re-export module (no top-level function definitions) hands out every class it imports.@@ -743,11 +751,11 @@ def _split_facade_reexports(backend_dir: Path, name: str) -> FacadeReexports:def facade_class_imports(backend_dir: Path, name: str) -> list[FacadeClassImport]:- """Classes the facade re-exports from a non-garage internal module, minus sanctioned carve-outs+ """Classes the facade re-exports from an internal module outside a wiring location, minus sanctioned carve-outsand watched-models-allowance crossings.Each is a class the facade can hand out that the wiring doctrine doesn't sanction. The remedy is- always one of three: move it to a garage (if it implements a core-owned base), to+ always one of three: move it to a wiring location (if it implements a core-owned base), tofacade/contracts.py (if it's a data/error type), or drop the turbo.json narrowing.Division of labor: deliberate re-exports from a function-bearing facade module must surface via@@ -761,7 +769,7 @@ def facade_class_imports(backend_dir: Path, name: str) -> list[FacadeClassImportdef facade_carveout_modules(backend_dir: Path, name: str) -> set[str]:"""Backend-relative modules that define the carve-out classes this product's facade re-exports.- A narrowed product must keep these in its contract-check inputs, exactly like a garage."""+ A narrowed product must keep these in its contract-check inputs, exactly like a wiring location."""return set(_split_facade_reexports(backend_dir, name).carveout_modules)@@ -784,9 +792,18 @@ def _unwatched_present_locations(product_dir: Path, prefixes: tuple[str, ...]) -return _uncovered_locations(product_dir, {p: (p,) for p in present})-def unwatched_garages(product_dir: Path) -> set[str]:- """Garage locations present in the product but missing from its (narrowed) contract-check inputs."""- return _unwatched_present_locations(product_dir, GARAGE_PREFIXES)+def unwatched_garages(product_dir: Path, driven: frozenset[str] | None = None) -> set[str]:+ """Wiring locations present in the product but missing from its (narrowed) contract-check inputs.++ `driven` is the subset of COMPUTED_WIRING_LOCATIONS that a test outside the product executes, read+ from the crossings baseline. A computed location with no driver may leave the inputs. `None`+ means the caller has no evidence, so every present location counts as driven: the safe+ direction."""+ if driven is None:+ prefixes = GARAGE_PREFIXES+ else:+ prefixes = tuple(p for p in GARAGE_PREFIXES if p not in COMPUTED_WIRING_LOCATIONS or p in driven)+ return _unwatched_present_locations(product_dir, prefixes)def uncovered_carveout_modules(product_dir: Path, carveout_modules: frozenset[str]) -> set[str]:@@ -810,9 +827,9 @@ def unwatched_model_surface(product_dir: Path) -> set[str]:the facade checks cannot prove nothing outside observes it, and a model or migration change hasto re-run the full suite.- Stricter than the garage check on purpose: the WHOLE surface must be watched, so a directory+ Stricter than the wiring-location check on purpose: the WHOLE surface must be watched, so a directorylocation needs its full glob (backend/models/**) — an input inside it, or a negation that may- carve files out of it, does not count. A garage may be watched piecemeal; the model+ carve files out of it, does not count. A wiring location may be watched piecemeal; the modelsurface may not, because any unwatched model file is a class core can observe without re-runningthe suite. There is no glob engine here, so a negation only passes when its literal prefix (upto the first wildcard) is provably disjoint from the surface — `!backend/**/x.py` could match a@@ -858,13 +875,15 @@ class IsolationStatus:# schema registry — so they don't qualify as irreducible interfaces and the marker is being# abused to keep an internal (models/logic) walled off. IsolationChainCheck blocks on these.unqualified_permanent_exposures: tuple[str, ...] = ()- # Classes the facade re-exports from a non-garage, non-carve-out internal module — behavior+ # Classes the facade re-exports from an internal module that is neither wiring location nor carve-out — behavior# crossing the boundary that the wiring doctrine doesn't sanction (see facade_class_imports).# Blocks narrowing; a warning-only signal while the product is still un-narrowed.facade_leaks: tuple[FacadeClassImport, ...] = ()- # Garage wiring locations present in the product but missing from a narrowed product's inputs,- # and carve-out modules missing the same way. Both keep the skip sound and block when narrowed.+ # Wiring locations present in the product but missing from a narrowed product's inputs, and+ # carve-out modules missing the same way. Both keep the skip sound and block when narrowed. A+ # location in COMPUTED_WIRING_LOCATIONS is listed only while an outside test drives it (driven_wiring_locations).unwatched_garages: tuple[str, ...] = ()+ driven_wiring_locations: tuple[str, ...] = ()uncovered_carveout_modules: tuple[str, ...] = ()# Model classes the facade hands out under the watched-models allowance (see# MODEL_CROSSINGS). uncovered_model_surface lists the model/migration locations a narrowed@@ -910,8 +929,12 @@ def compute_isolation_status(tach_content: str | None = None,pyproject_text: str | None = None,repo_root: Path | None = None,+ driven_wiring_locations: frozenset[str] | None = None,) -> IsolationStatus:- """Compute the full isolation seal status for one product."""+ """Compute the full isolation seal status for one product.++ `driven_wiring_locations` is the evidence `unwatched_garages` reads. Without it, every present wiring+ location must stay watched."""if is_isolated is None:is_isolated = is_isolated_product(backend_dir)if tach_content is None:@@ -939,7 +962,8 @@ def compute_isolation_status(sorted(unqualified_permanent_modules(module_path, permanent_modules, repo_root=repo_root))),facade_leaks=reexports.leaks,- unwatched_garages=tuple(sorted(unwatched_garages(product_dir))),+ unwatched_garages=tuple(sorted(unwatched_garages(product_dir, driven_wiring_locations))),+ driven_wiring_locations=tuple(sorted(driven_wiring_locations or ())),uncovered_carveout_modules=tuple(sorted(uncovered_carveout_modules(product_dir, carveout_modules))),model_crossings=reexports.model_crossings,uncovered_model_surface=tuple(sorted(unwatched_model_surface(product_dir))),diff --git a/tools/hogli-commands/hogli_commands/tests/test_checks.py b/tools/hogli-commands/hogli_commands/tests/test_checks.pyindex 4c135e39202f..3404781e6f23 100644--- a/tools/hogli-commands/hogli_commands/tests/test_checks.py+++ b/tools/hogli-commands/hogli_commands/tests/test_checks.py@@ -1880,6 +1880,24 @@ class TestUnwatchedGarages:product_dir, _ = _write_facade_product(tmp_path, sources={garage_file: ""}, turbo_inputs=turbo_inputs)assert unwatched_garages(product_dir) == expected+ @pytest.mark.parametrize(+ "garage_file, driven, expected",+ [+ # no evidence at all: every present garage must stay watched+ ("hogql_queries/paths.py", None, {"backend/hogql_queries/"}),+ # evidence says nothing outside drives the computed garage: it may leave the inputs+ ("hogql_queries/paths.py", frozenset(), set()),+ ("hogql_queries/paths.py", frozenset({"backend/hogql_queries/"}), {"backend/hogql_queries/"}),+ # a garage whose drive channel is not scanned stays presence-watched whatever the evidence says+ ("tasks/tasks.py", frozenset(), {"backend/tasks/"}),+ ],+ )+ def test_computed_garage_follows_the_evidence(+ self, tmp_path: Path, garage_file: str, driven: frozenset[str] | None, expected: set[str]+ ) -> None:+ product_dir, _ = _write_facade_product(tmp_path, sources={garage_file: ""}, turbo_inputs=["backend/facade/**"])+ assert unwatched_garages(product_dir, driven) == expected+class TestNarrowedTurboWiringSurface:@pytest.mark.parametrize(diff --git a/tools/hogli-commands/hogli_commands/tests/test_crossings.py b/tools/hogli-commands/hogli_commands/tests/test_crossings.pyindex eca680a6d1b3..fbfd57dcb134 100644--- a/tools/hogli-commands/hogli_commands/tests/test_crossings.py+++ b/tools/hogli-commands/hogli_commands/tests/test_crossings.py@@ -10,6 +10,7 @@ import pytestfrom hogli_commands.product import crossingsfrom hogli_commands.product.crossings import CrossingClass, classify_use, kind_is_allowed+from parameterized import parameterizedALERT = CrossingClass("alerts", "AlertConfiguration", "products.alerts.backend.models.alert")LOOKUP = {ALERT.label.lower(): ALERT.label}@@ -201,3 +202,544 @@ class TestRenderReport:crossings.CrossingUse("alerts.AlertConfiguration", "posthog.api.b", "annotation", 2),]assert "allowed: annotation 3" in crossings.render_report(uses)+++DISPATCHER = """+def get_query_runner(query, team, kind=None):+ if kind == "TrendsQuery":+ from .insights.trends.trends_query_runner import TrendsQueryRunner++ return TrendsQueryRunner(query=query, team=team)+ if kind == "PathsQuery":+ from products.product_analytics.backend.facade.queries import PathsQueryRunner++ return PathsQueryRunner(query=query, team=team)+ if kind in ("WebOverviewQuery", "WebStatsTableQuery"):+ from products.web_analytics.backend.hogql_queries.web_overview import WebOverviewQueryRunner++ return WebOverviewQueryRunner(query=query, team=team)+ if kind == NodeKind.MARKETING_ANALYTICS_TABLE_QUERY:+ from products.marketing_analytics.backend.hogql_queries.table import MarketingAnalyticsTableQueryRunner++ return MarketingAnalyticsTableQueryRunner(query=query, team=team)+ if kind == "TrendsQuery":+ if query.tags and query.tags.productKey == "web_analytics":+ from products.web_analytics.backend.hogql_queries.web_trends import WebTrendsQueryRunner++ return WebTrendsQueryRunner(query=query, team=team)+ from .insights.trends.trends_query_runner import TrendsQueryRunner++ return TrendsQueryRunner(query=query, team=team)+"""++NODE_KIND_ENUM = """+class OtherEnum(StrEnum):+ X = "NotAKind"+++class NodeKind(StrEnum):+ EVENTS_NODE = "EventsNode"+ MARKETING_ANALYTICS_TABLE_QUERY = "MarketingAnalyticsTableQuery"+++class After(StrEnum):+ Y = "AlsoNotAKind"+"""++KINDS = crossings._QueryKinds(+ {"PathsQuery": frozenset({"product_analytics"}), "WebOverviewQuery": frozenset({"web_analytics"})},+ {"PATHS_QUERY": "PathsQuery"},+)+++class TestGarageDrives:+ def test_dispatch_table_maps_product_kinds_only(self) -> None:+ node_kinds = crossings._node_kind_values(NODE_KIND_ENUM)+ assert node_kinds == {+ "EVENTS_NODE": "EventsNode",+ "MARKETING_ANALYTICS_TABLE_QUERY": "MarketingAnalyticsTableQuery",+ }+ assert crossings._kinds_in_dispatcher(DISPATCHER, node_kinds) == {+ "PathsQuery": frozenset({"product_analytics"}),+ "WebOverviewQuery": frozenset({"web_analytics"}),+ "WebStatsTableQuery": frozenset({"web_analytics"}),+ "MarketingAnalyticsTableQuery": frozenset({"marketing_analytics"}),+ # a core kind that hands off to a product under a nested condition reaches that product+ "TrendsQuery": frozenset({"web_analytics"}),+ }++ @pytest.mark.parametrize(+ "source, expected",+ [+ # a kind literal handed to the dispatcher is a drive+ (+ """+ def test_paths(team):+ process_query_dict(team, {"kind": "PathsQuery", "pathsFilter": {}})+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # the schema constructor run through the dispatcher is a drive too+ (+ """+ def test_paths(team):+ get_query_runner(PathsQuery(pathsFilter={}), team).calculate()+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # a fixture built in setUp and executed over the in-process test client, same class+ (+ """+ class TestInsights(APIBaseTest):+ def setUp(self):+ self.query = {"kind": "PathsQuery"}++ def test_run(self):+ self.client.post("/api/projects/1/query/", {"query": self.query})+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # built and never run: a schema or formatter check, not a drive+ (+ """+ def test_metadata():+ assert extract(PathsQuery(pathsFilter={})).kind == "PathsQuery"+ """,+ {},+ ),+ # a parametrize row that flows into the dispatcher is a drive+ (+ """+ class TestKinds(TestCase):+ @parameterized.expand([("PathsQuery",), ("TrendsQuery",)])+ def test_runs(self, kind):+ process_query_dict(self.team, {"kind": kind})+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # a test that reaches the client through two helpers still executes+ (+ """+ class TestChain(APIBaseTest):+ def _post(self, body):+ return self.client.post("/api/projects/1/query/", body)++ def _run(self, query):+ return self._post({"query": query})++ def test_paths(self):+ assert self._run({"kind": "PathsQuery"}).status_code == 200+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # a method that runs the kind through a module-level helper executes too+ (+ """+ def post_query(client, query):+ return client.post("/api/projects/1/query/", {"query": query})++ class TestPaths(APIBaseTest):+ def test_paths(self):+ assert post_query(self.client, {"kind": "PathsQuery"}).status_code == 200+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # a helper inherited from a base class in the same module executes too+ (+ """+ class QueryTestBase(APIBaseTest):+ def run_query(self, query):+ return self.client.post("/api/projects/1/query/", {"query": query})++ class TestPaths(QueryTestBase):+ def test_paths(self):+ assert self.run_query({"kind": "PathsQuery"}).status_code == 200+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # a HogQL string that embeds the kind in tag syntax and runs through the executor+ (+ """+ class TestActors(ClickhouseTestMixin, APIBaseTest):+ def select(self, query):+ return execute_hogql_query(query=query, team=self.team)++ def test_stickiness_actors(self):+ hogql = "select * from (<InsightActorsQuery day={2}><PathsQuery series={[]} /></InsightActorsQuery>)"+ assert self.select(hogql).results+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # two bases define the helper; the one that executes wins whatever the order+ (+ """+ class Quiet(TestCase):+ def _run(self, query):+ return query++ class Posting(APIBaseTest):+ def _run(self, query):+ return self.client.post("/api/projects/1/query/", {"query": query})++ class TestPaths(Quiet, Posting):+ def test_paths(self):+ assert self._run({"kind": "PathsQuery"})+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # a bare string in a test that never executes, or a URL segment, is not a drive+ (+ """+ class TestTags(TestCase):+ @parameterized.expand([("PathsQuery",), ("TrendsQuery",)])+ def test_tags(self, kind):+ assert tag_for(kind)++ def test_other(self):+ self.client.get("/api/projects/1/query/PathsQuery/")+ """,+ {},+ ),+ # a test method that only builds the kind is not a drive, whatever its siblings run+ (+ """+ class TestEndpoints(APIBaseTest):+ @parameterized.expand([("paths", {"kind": "PathsQuery"})])+ def test_rejects(self, _name, query):+ assert not can_materialize(query)++ def test_materializes(self):+ self.client.patch("/api/projects/1/endpoints/x/", {"is_materialized": True})+ """,+ {},+ ),+ # a test method that runs the kind through a helper of its own is a drive+ (+ """+ class TestPaths(APIBaseTest):+ def _run(self, query):+ return self.client.post("/api/projects/1/query/", {"query": query})++ def test_paths(self):+ assert self._run({"kind": "PathsQuery"}).status_code == 200+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # the enum form of a kind counts like the literal+ (+ """+ def test_paths(team):+ process_query_dict(team, {"kind": NodeKind.PATHS_QUERY, "pathsFilter": {}})+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # a same-named method in a later class does not answer for the one that executes+ (+ """+ class TestRuns(APIBaseTest):+ def test_paths(self):+ self.client.post("/api/projects/1/query/", {"query": {"kind": "PathsQuery"}})++ class TestBuilds(TestCase):+ def test_paths(self):+ assert {"kind": "PathsQuery"}["kind"]+ """,+ {("product_analytics", "PathsQuery"): 1},+ ),+ # execution in another class does not count for this class's fixture+ (+ """+ class TestBuild(TestCase):+ def test_build(self):+ assert {"kind": "PathsQuery"}["kind"]++ class TestRun(APIBaseTest):+ def test_run(self):+ self.client.post("/api/projects/1/query/", {"query": {"kind": "TrendsQuery"}})+ """,+ {},+ ),+ # a core kind is never a drive, and two products are told apart+ (+ """+ def test_both(team):+ process_query_dict(team, {"kind": "TrendsQuery"})+ process_query_dict(team, {"kind": "WebOverviewQuery"})+ process_query_dict(team, {"kind": "WebOverviewQuery"})+ """,+ {("web_analytics", "WebOverviewQuery"): 2},+ ),+ ],+ )+ def test_kind_drives(self, source: str, expected: dict[tuple[str, str], int]) -> None:+ drives = crossings.kind_drives(ast.parse(textwrap.dedent(source)), KINDS)+ assert {(drive.product, drive.kind): count for drive, count in drives.items()} == expected++ def test_lazy_facade_map_resolves_to_its_source_module(self) -> None:+ facade = textwrap.dedent(+ """+ _B = "products.product_analytics.backend.hogql_queries."+ _LAZY = {"PathsQueryRunner": "paths.paths_query_runner", "helper": "logic.helpers"}++ def __getattr__(name):+ return None+ """+ )+ existing = {+ "products.product_analytics.backend.hogql_queries.paths.paths_query_runner",+ "products.product_analytics.backend.logic.helpers",+ }+ assert crossings._lazy_reexports(ast.parse(facade), "product_analytics", existing.__contains__) == {+ "PathsQueryRunner": "products.product_analytics.backend.hogql_queries.paths.paths_query_runner",+ "helper": "products.product_analytics.backend.logic.helpers",+ }++ def test_top_level_names_include_constants(self) -> None:+ module = "BOT_DEFINITIONS = [...]\nLIMIT: int = 5\n_private = 1\n\nclass Runner: ...\n\ndef helper(): ...\n"+ assert crossings._top_level_names(ast.parse(module)) == ["BOT_DEFINITIONS", "LIMIT", "Runner", "helper"]++ def test_aliased_constructor_counts_by_its_kind(self) -> None:+ source = textwrap.dedent(+ """+ from posthog.schema import PathsQuery as Query++ def test_paths(team):+ get_query_runner(Query(pathsFilter={}), team).calculate()+ """+ )+ imports = crossings._read_imports(source.encode(), "posthog.test")+ names = crossings._kind_names(imports, KINDS)+ assert names.constructors == {"Query": "PathsQuery"}+ drives = crossings.kind_drives(ast.parse(source), KINDS, names)+ assert {(d.product, d.kind): n for d, n in drives.items()} == {("product_analytics", "PathsQuery"): 1}+ assert crossings._KindHint.for_kinds(KINDS).matches(source.encode())++ def test_aliased_enum_counts_by_its_kind(self) -> None:+ source = textwrap.dedent(+ """+ from posthog.schema import NodeKind as Kind++ def test_paths(team):+ process_query_dict(team, {"kind": Kind.PATHS_QUERY})+ """+ )+ imports = crossings._read_imports(source.encode(), "posthog.test")+ names = crossings._kind_names(imports, KINDS)+ assert names.enum_bases == frozenset({"Kind", "NodeKind"})+ drives = crossings.kind_drives(ast.parse(source), KINDS, names)+ assert {(d.product, d.kind): n for d, n in drives.items()} == {("product_analytics", "PathsQuery"): 1}+ assert crossings._KindHint.for_kinds(KINDS).matches(source.encode())++ def test_member_off_an_unrelated_base_is_not_a_kind(self) -> None:+ source = textwrap.dedent(+ """+ from elsewhere import Other as Kind++ def test_paths(team):+ process_query_dict(team, {"kind": Kind.PATHS_QUERY})+ """+ )+ imports = crossings._read_imports(source.encode(), "posthog.test")+ names = crossings._kind_names(imports, KINDS)+ assert names.enum_bases == frozenset({"NodeKind"})+ assert crossings.kind_drives(ast.parse(source), KINDS, names) == {}++ def test_package_qualified_enum_counts_by_its_kind(self) -> None:+ source = textwrap.dedent(+ """+ from posthog import schema++ def test_paths(team):+ process_query_dict(team, {"kind": schema.NodeKind.PATHS_QUERY})+ """+ )+ names = crossings._kind_names(crossings._read_imports(source.encode(), "posthog.test"), KINDS)+ drives = crossings.kind_drives(ast.parse(source), KINDS, names)+ assert {(d.product, d.kind): n for d, n in drives.items()} == {("product_analytics", "PathsQuery"): 1}++ def test_enum_member_value_counts_once(self) -> None:+ source = textwrap.dedent(+ """+ from posthog.schema import NodeKind++ def test_paths(team):+ process_query_dict(team, {"kind": NodeKind.PATHS_QUERY.value})+ """+ )+ names = crossings._kind_names(crossings._read_imports(source.encode(), "posthog.test"), KINDS)+ drives = crossings.kind_drives(ast.parse(source), KINDS, names)+ assert {(d.product, d.kind): n for d, n in drives.items()} == {("product_analytics", "PathsQuery"): 1}++ def test_aliased_dispatcher_still_executes(self) -> None:+ source = textwrap.dedent(+ """+ from posthog.schema import PathsQuery+ from posthog.api.services.query import process_query_dict as run_query++ def test_paths(team):+ run_query(team, PathsQuery(pathsFilter={}))+ """+ )+ imports = crossings._read_imports(source.encode(), "posthog.test")+ names = crossings._kind_names(imports, KINDS)+ assert "run_query" in names.dispatchers+ drives = crossings.kind_drives(ast.parse(source), KINDS, names)+ assert {(d.product, d.kind): n for d, n in drives.items()} == {("product_analytics", "PathsQuery"): 1}++ def test_every_node_kind_enum_is_read(self) -> None:+ source = textwrap.dedent(+ """+ class InsightNodeKind(StrEnum):+ PATHS_QUERY = "PathsQuery"+++ class NodeKind(StrEnum):+ EVENTS_NODE = "EventsNode"+ """+ )+ assert set(crossings._node_kind_enums(source)) == {"InsightNodeKind", "NodeKind"}+ assert crossings._node_kind_values(source) == {"PATHS_QUERY": "PathsQuery", "EVENTS_NODE": "EventsNode"}++ def test_module_object_imports_count_as_drives(self) -> None:+ source = textwrap.dedent(+ """+ import products.web_analytics.backend.hogql_queries.web_overview as overview+ from products.web_analytics.backend.hogql_queries import stats_table+ from products.web_analytics.backend.facade.queries import WebOverviewQueryRunner+ """+ )+ imports = crossings._read_imports(source.encode(), "posthog.test")+ location = crossings._WiringLocation("web_analytics", "backend/hogql_queries/")+ modules = {+ "products.web_analytics.backend.hogql_queries.web_overview",+ "products.web_analytics.backend.hogql_queries.stats_table",+ }+ assert crossings.module_drives(imports, [location], modules.__contains__) == {+ crossings._ModuleDrive(location.label, "web_overview"): 1,+ crossings._ModuleDrive(location.label, "stats_table"): 1,+ }++ def test_hint_matches_the_enum_form(self) -> None:+ hint = crossings._KindHint.for_kinds(KINDS)+ 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:+ 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.Insight posthog.api.sharing instance-many(all) 1\n"+ "web_analytics:backend/hogql_queries/ posthog.test.test_y drives(WebOverviewQueryRunner) 1\n"+ )+ assert crossings.driven_wiring_locations("product_analytics", baseline) == {"backend/hogql_queries/"}+ assert crossings.driven_wiring_locations("error_tracking", baseline) == frozenset()+++class TestUnresolvedKindDrives:+ """The floor under the spellings `_kind_of` reads: a kind the scan cannot read still counts."""++ @staticmethod+ def _count(body: str) -> int:+ source = textwrap.dedent(body)+ names = crossings._kind_names(crossings._read_imports(source.encode(), "posthog.test"), KINDS)+ return crossings.unresolved_kind_drives(ast.parse(source), KINDS, names)++ def test_unreadable_kind_reaching_a_dispatcher_counts(self) -> None:+ assert (+ self._count(+ """+ from posthog.api.services.query import process_query_dict++ def test_paths(team, kind):+ process_query_dict(team, {"kind": kind})+ """+ )+ == 1+ )++ def test_unreadable_kind_posted_to_the_client_counts(self) -> None:+ assert (+ self._count(+ """+ class TestPaths:+ def test_paths(self):+ self.client.post("/api/environments/1/query/", {"query": {"kind": self.kind}})+ """+ )+ == 1+ )++ @parameterized.expand(+ [+ ("a kind the scan reads", '{"kind": "PathsQuery"}'),+ ("a kind that belongs to no product", '{"kind": "EventsQuery"}'),+ ("an enum member", '{"kind": NodeKind.PATHS_QUERY}'),+ ]+ )+ def test_a_readable_kind_does_not_count(self, _name: str, payload: str) -> None:+ assert (+ self._count(+ f"""+ from posthog.schema import NodeKind+ from posthog.api.services.query import process_query_dict++ def test_paths(team):+ process_query_dict(team, {payload})+ """+ )+ == 0+ )++ def test_a_scope_that_names_a_kind_does_not_count(self) -> None:+ """A parametrized test names its kinds in the decorator, which stands as the evidence."""+ assert (+ self._count(+ """+ from posthog.api.services.query import process_query_dict++ @parameterized.expand([("PathsQuery",)])+ def test_paths(team, kind):+ process_query_dict(team, {"kind": kind})+ """+ )+ == 0+ )++ def test_a_constant_default_is_readable(self) -> None:+ assert (+ self._count(+ """+ from posthog.api.services.query import process_query_dict++ def test_paths(team, kind="DataTableNode"):+ process_query_dict(team, {"kind": kind})+ """+ )+ == 0+ )++ def test_a_kind_that_never_executes_does_not_count(self) -> None:+ assert (+ self._count(+ """+ def test_paths(kind):+ payload = {"query": {"kind": kind}}+ assert payload["query"]["kind"] == kind+ """+ )+ == 0+ )++ def test_an_unrelated_kind_key_does_not_count(self) -> None:+ """`kind` names many things; only a dict in query position is a query."""+ assert (+ self._count(+ """+ class TestEmail:+ def test_email(self):+ self.client.post("/api/environments/1/query/", {"kind": self.channel.kind})+ """+ )+ == 0+ )