Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(product-analytics): follow query execution across module boundaries (#92170)

Thomas Obermüller683686bcdfd2
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 147269ffec89..ae28a52ee98f 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -674,6 +674,12 @@ product_analytics.Insight products.reminders.backend.constants in-collection 1
product_analytics.Insight products.slack_app.backend.slack_link_unfurl instance-single 1
product_analytics.Insight products.surveys.backend.api.survey instance-single 1
product_analytics.Insight surveys.Survey.linked_insight reverse-accessor(surveys_linked_insight) 1
+product_analytics:backend/hogql_queries/ products.cohorts.backend.models.test.test_util drives(FunnelsQuery) 1
+product_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_endpoint_materialization drives(LifecycleQuery) 1
+product_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_endpoint_materialization drives(RetentionQuery) 1
+product_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_insight_response_parity drives(LifecycleQuery) 1
+product_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_insight_response_parity drives(RetentionQuery) 1
+product_analytics:backend/hogql_queries/ products.posthog_ai.scripts.hogql_example.test.test_hogql_example drives(FunnelsQuery) 1
replay_vision.ReplayScanner posthog.TaggedItem.replay_scanner reverse-accessor(tagged_items) 1
signals.SignalReport tasks.Task.signal_report reverse-accessor(task) 1
surveys.Survey product_tours.ProductTour.linked_surveys reverse-accessor(product_tours) 1
@@ -825,7 +831,7 @@ warehouse_sources.WarehouseColumnAnnotation products.data_warehouse.backend.pres
warehouse_sources.WarehouseColumnAnnotation products.posthog_ai.evals.data_warehouse.seeder construct 2
warehouse_sources.WarehouseColumnAnnotation products.posthog_ai.evals.data_warehouse.seeder write(bulk_create) 1
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) 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.hogql.database.schema.test.test_persons drives(TrendsQuery) 1
@@ -840,6 +846,7 @@ web_analytics:backend/hogql_queries/ posthog.hogql.transforms.test.test_preaggre
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_dashboard_filters_overrides drives(TrendsQuery) 1
web_analytics:backend/hogql_queries/ posthog.hogql_queries.test.test_insight_actors_query_runner drives(TrendsQuery) 7
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
@@ -856,21 +863,26 @@ 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.cohorts.backend.models.test.test_util drives(TrendsQuery) 1
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_catalog.backend.tests.test_execution drives(TrendsQuery) 2
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_endpoint_materialization drives(TrendsQuery) 10
+web_analytics:backend/hogql_queries/ products.endpoints.backend.tests.test_insight_response_parity drives(TrendsQuery) 9
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.endpoints.backend.tests.test_variable_materialization drives(TrendsQuery) 1
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.posthog_ai.scripts.hogql_example.test.test_hogql_example drives(TrendsQuery) 3
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.product_analytics.backend.tests.test_insight_write_validation drives(TrendsQuery) 6
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) 3
diff --git a/products/product_analytics/turbo.json b/products/product_analytics/turbo.json
index 0be4d6c10996..c72b121729e4 100644
--- a/products/product_analytics/turbo.json
+++ b/products/product_analytics/turbo.json
@@ -4,6 +4,7 @@
"backend:contract-check": {
"inputs": [
"backend/facade/**",
+ "backend/hogql_queries/**",
"backend/presentation/**",
"backend/routes.py",
"backend/models/**",
diff --git a/tools/hogli-commands/hogli_commands/product/crossings.py b/tools/hogli-commands/hogli_commands/product/crossings.py
index 2ce0858783fa..9c5dfa6c89ab 100644
--- a/tools/hogli-commands/hogli_commands/product/crossings.py
+++ b/tools/hogli-commands/hogli_commands/product/crossings.py
@@ -371,7 +371,7 @@ def _candidates(kind_hint: _KindHint | None = None) -> list[_Candidate]:
package = dotted if path.name == "__init__.py" else dotted.rsplit(".", 1)[0]
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)
+ mentions_dispatch = any(call in source for call in _DISPATCH_CALL_BYTES)
found.append(
_Candidate(
path,
@@ -989,6 +989,42 @@ def _enclosing(node: ast.AST, parents: dict[int, ast.AST]) -> tuple[_Function |
return function, None
+# What `unittest.mock` binds a replacement to. `patch("a.b.run")` and `patch.object(b, "run")` both
+# name `run`; the leaf is all the scan needs, because it follows calls by name too.
+_PATCH_CALLS: frozenset[str] = frozenset({"patch", "object"})
+
+
+def _patched_names(scope: ast.AST, skip: frozenset[int] = frozenset()) -> set[str]:
+ """The names `scope` replaces with a mock, decorator and context manager alike.
+
+ A test that patches the seam a helper would have reached does not execute a query through it,
+ however faithfully the call chain reads. Without this the scan counts the mock.
+
+ `skip` prunes subtrees whose patches do not reach the code being judged."""
+ patched: set[str] = set()
+ pending: list[ast.AST] = [scope]
+ while pending:
+ node = pending.pop()
+ if isinstance(node, ast.Call) and _callee_name(node) in _PATCH_CALLS:
+ for argument in node.args:
+ if isinstance(argument, ast.Constant) and isinstance(argument.value, str):
+ patched.add(argument.value.rsplit(".", 1)[-1])
+ pending.extend(child for child in ast.iter_child_nodes(node) if id(child) not in skip)
+ return patched
+
+
+def _sibling_tests(scope: ast.AST, function: _Function) -> frozenset[int]:
+ """The other test functions of `scope`, whose patches apply to themselves alone.
+
+ A `setUp` patcher and a class decorator reach every method, so those stay readable. A patch
+ inside a sibling test does not, and reading it would suppress a call this test really makes."""
+ return frozenset(
+ id(node)
+ for node in ast.iter_child_nodes(scope)
+ if isinstance(node, _Function) and node is not function and node.name.startswith("test")
+ )
+
+
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))
@@ -1003,18 +1039,30 @@ class _Executions:
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."""
+ name never answer for each other.
+
+ A helper the module imports is followed too, when a `_CallGraph` is supplied; without one the
+ walk stops at the module edge and a test that runs its query through an imported helper reads
+ as building only."""
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:
+ def __init__(
+ self,
+ tree: ast.Module,
+ dispatchers: frozenset[str],
+ calls: _CallGraph | None = None,
+ module: 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)}
+ self._calls = calls
+ self._module = module
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
@@ -1050,6 +1098,7 @@ class _Executions:
helpers.setdefault(name, []).extend(nodes)
seen: set[int] = set()
pending = [function]
+ outward: set[str] = set()
while pending:
current = pending.pop()
if id(current) in seen:
@@ -1059,11 +1108,151 @@ class _Executions:
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, []))
+ resolved = helpers.get(name)
+ if resolved:
+ pending.extend(resolved)
+ elif name is not None:
+ outward.add(name)
+ if self._calls is None:
+ return False
+ patched = frozenset(_patched_names(function) | _patched_names(scope, _sibling_tests(scope, function)))
+ return any(self._calls.executes(self._module, name, patched) for name in sorted(outward - patched))
+
+
+# How far a call chain is followed out of the module that starts it. The chains this exists for are
+# short — a test helper, the function it delegates to, the extractor that runs the query — and an
+# unbounded walk would parse most of the repo for every test module that names a kind.
+_MAX_CALL_DEPTH = 8
+
+
+@dataclass(frozen=True)
+class _ModuleDefs:
+ """The callables one module defines, indexed the three ways a call site can name them."""
+
+ functions: Mapping[str, tuple[_Function, ...]] # top-level, by name
+ methods: Mapping[str, tuple[_Function, ...]] # every method of every class, by bare name
+ methods_of: Mapping[str, Mapping[str, tuple[_Function, ...]]] # class -> method -> definitions
+
+
+def _module_defs(tree: ast.Module) -> _ModuleDefs:
+ functions: dict[str, list[_Function]] = defaultdict(list)
+ methods: dict[str, list[_Function]] = defaultdict(list)
+ methods_of: dict[str, dict[str, tuple[_Function, ...]]] = {}
+ for node in tree.body:
+ if isinstance(node, _Function):
+ functions[node.name].append(node)
+ elif isinstance(node, ast.ClassDef):
+ own: dict[str, list[_Function]] = defaultdict(list)
+ for child in ast.iter_child_nodes(node):
+ if isinstance(child, _Function):
+ own[child.name].append(child)
+ methods[child.name].append(child)
+ methods_of[node.name] = {name: tuple(defs) for name, defs in own.items()}
+ return _ModuleDefs(
+ {name: tuple(defs) for name, defs in functions.items()},
+ {name: tuple(defs) for name, defs in methods.items()},
+ methods_of,
+ )
+
+
+class _CallGraph:
+ """Whether a call that leaves its module reaches a query execution.
+
+ The scan already reads every module's imports, so no real call graph is needed: an import edge
+ names the module a helper came from, and that module's own edges carry the next hop.
+
+ A method call is followed only inside the module that defines the class. Across a module edge
+ the receiver has no type here, and matching on the bare method name instead answers for every
+ unrelated object with a method of that name — measured, that reported query executions in a
+ prompt-formatting suite that runs nothing."""
+
+ def __init__(self, candidates: Iterable[_Candidate]) -> None:
+ self._paths = {candidate.dotted: candidate.path for candidate in candidates}
+ self._imports = {candidate.dotted: candidate.imports for candidate in candidates}
+ self._defs_cache: dict[str, _ModuleDefs | None] = {}
+ self._memo: dict[tuple[str, str, frozenset[str], bool], bool] = {}
+
+ def _defs(self, module: str) -> _ModuleDefs | None:
+ if module not in self._defs_cache:
+ self._defs_cache[module] = self._parse(module)
+ return self._defs_cache[module]
+
+ def _parse(self, module: str) -> _ModuleDefs | None:
+ path = self._paths.get(module)
+ if path is None:
+ return None
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", SyntaxWarning)
+ return _module_defs(ast.parse(path.read_bytes()))
+ except (OSError, SyntaxError, ValueError):
+ return None
+
+ def _imported(self, module: str) -> tuple[_ImportEdge, ...]:
+ table = self._imports.get(module)
+ return table.edges if table is not None else ()
+
+ def _targets(self, module: str, name: str, local: bool) -> list[tuple[str, _Function]]:
+ """Every (module, function) a call to `name` inside `module` can reach.
+
+ `local` is off for the module that starts the walk, whose own functions and methods the
+ caller has already resolved under stricter rules than this."""
+ found: list[tuple[str, _Function]] = []
+ defs = self._defs(module)
+ if local and defs is not None:
+ found += [(module, fn) for fn in defs.functions.get(name, ())]
+ found += [(module, fn) for fn in defs.methods.get(name, ())]
+ for edge in self._imported(module):
+ if edge.bound != name:
+ continue
+ target = self._defs(edge.module)
+ if target is not None:
+ found += [(edge.module, fn) for fn in target.functions.get(edge.exported, ())]
+ return found
+
+ def executes(
+ self,
+ module: str,
+ name: str,
+ patched: frozenset[str] = frozenset(),
+ depth: int = 0,
+ local: bool = False,
+ ) -> bool:
+ """Whether a call to `name` inside `module` reaches a query execution.
+
+ `patched` carries the names the calling test replaced with a mock, all the way down: the
+ seam is usually mocked several hops from the test, and a chain that ends at one runs
+ nothing."""
+ if name in patched or depth >= _MAX_CALL_DEPTH or module not in self._paths:
+ return False
+ # `local` belongs in the key: it widens the search to the module's own definitions, so the
+ # two modes can answer differently for one name.
+ key = (module, name, patched, local)
+ if key in self._memo:
+ return self._memo[key]
+ # A recursive chain answers "no" while it is still being walked, so a cycle terminates.
+ self._memo[key] = False
+ for target_module, function in self._targets(module, name, local):
+ if _executes_directly(function, DISPATCH_CALLS - patched):
+ self._memo[key] = True
+ return True
+ called = {_callee_name(node) for node in ast.walk(function) if isinstance(node, ast.Call)}
+ if any(
+ self.executes(target_module, call, patched, depth + 1, local=True)
+ for call in sorted(filter(None, called))
+ ):
+ self._memo[key] = True
+ return True
return False
-def kind_drives(tree: ast.Module, kinds: _QueryKinds, names: _KindNames | None = None) -> Counter[_KindDrive]:
+def kind_drives(
+ tree: ast.Module,
+ kinds: _QueryKinds,
+ names: _KindNames | None = None,
+ calls: _CallGraph | None = None,
+ module: str = "",
+) -> 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
@@ -1076,7 +1265,7 @@ def kind_drives(tree: ast.Module, kinds: _QueryKinds, names: _KindNames | None =
if not mentions:
return Counter()
parents = _parent_map(tree)
- executions = _Executions(tree, names.dispatchers)
+ executions = _Executions(tree, names.dispatchers, calls, module)
scope_executes: dict[int, bool] = {}
found: Counter[_KindDrive] = Counter()
for node, kind in mentions:
@@ -1141,7 +1330,13 @@ def _query_position_dicts(tree: ast.Module, dispatchers: frozenset[str]) -> Iter
yield value
-def unresolved_kind_drives(tree: ast.Module, kinds: _QueryKinds, names: _KindNames | None = None) -> int:
+def unresolved_kind_drives(
+ tree: ast.Module,
+ kinds: _QueryKinds,
+ names: _KindNames | None = None,
+ calls: _CallGraph | None = None,
+ module: str = "",
+) -> 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
@@ -1166,7 +1361,7 @@ def unresolved_kind_drives(tree: ast.Module, kinds: _QueryKinds, names: _KindNam
if not pending:
return 0
parents = _parent_map(tree)
- executions = _Executions(tree, names.dispatchers)
+ executions = _Executions(tree, names.dispatchers, calls, module)
resolved = {id(_enclosing(node, parents)[0]) for node, _ in _kind_mentions(tree, kinds, names)}
scope_executes: dict[int, bool] = {}
found = 0
@@ -1313,6 +1508,7 @@ def scan_crossing_uses(products: Iterable[str] | None = None) -> list[CrossingUs
False: {export.name for export, label in seeds.items() if ":" not in label},
}
candidates = _candidates(_KindHint.for_kinds(kinds) if kinds else None)
+ calls = _CallGraph(candidates)
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}
@@ -1364,13 +1560,13 @@ def scan_crossing_uses(products: Iterable[str] | None = None) -> list[CrossingUs
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)
+ unresolved = unresolved_kind_drives(tree, kinds, kind_names, calls, candidate.dotted)
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():
+ for drive, count in kind_drives(tree, kinds, kind_names, calls, candidate.dotted).items():
if drive.product in query_products and not candidate.path.is_relative_to(PRODUCTS_DIR / drive.product):
counts[
(
diff --git a/tools/hogli-commands/hogli_commands/tests/test_crossings.py b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
index fbfd57dcb134..ae82fa507619 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_crossings.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_crossings.py
@@ -23,6 +23,29 @@ def _candidate(source: str, dotted: str = "posthog.api.consumer") -> crossings._
return crossings._Candidate(Path(f"{dotted.replace('.', '/')}.py"), dotted, imports, b"get_model" in encoded)
+def _write_modules(tmp_path: Path, sources: dict[str, str]) -> list[crossings._Candidate]:
+ """Lay `sources` out on disk as importable modules, with their imports read."""
+ candidates = []
+ for dotted, source in sources.items():
+ path = tmp_path / f"{dotted.replace('.', '/')}.py"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ encoded = textwrap.dedent(source).encode()
+ path.write_bytes(encoded)
+ package = dotted.rsplit(".", 1)[0]
+ candidates.append(crossings._Candidate(path, dotted, crossings._read_imports(encoded, package), False))
+ return candidates
+
+
+def _drives_across_modules(tmp_path: Path, sources: dict[str, str], entry: str) -> dict[tuple[str, str], int]:
+ """Run `kind_drives` over `entry` with the other sources on disk as importable modules."""
+ candidates = _write_modules(tmp_path, sources)
+ calls = crossings._CallGraph(candidates)
+ tree = ast.parse((tmp_path / f"{entry.replace('.', '/')}.py").read_bytes())
+ names = crossings._kind_names(next(c.imports for c in candidates if c.dotted == entry), KINDS)
+ drives = crossings.kind_drives(tree, KINDS, names, calls, entry)
+ return {(drive.product, drive.kind): count for drive, count in drives.items()}
+
+
def classify(source: str) -> list[str]:
candidate = _candidate(source)
origins = crossings._origins([candidate], [ALERT])
@@ -475,6 +498,104 @@ class TestGarageDrives:
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_a_helper_in_another_module_still_counts_as_running_the_query(self, tmp_path: Path) -> None:
+ """A test that hands its query to an imported helper drives the runner just as directly."""
+ drives = _drives_across_modules(
+ tmp_path,
+ {
+ "app.helpers": """
+ from posthog.api.services.query import process_query_dict
+
+ def run_it(team, query):
+ return process_query_dict(team, query)
+ """,
+ "app.test_thing": """
+ from app.helpers import run_it
+
+ def test_paths(team):
+ run_it(team, {"kind": "PathsQuery"})
+ """,
+ },
+ "app.test_thing",
+ )
+ assert drives == {("product_analytics", "PathsQuery"): 1}
+
+ def test_a_sibling_tests_patch_does_not_hide_this_tests_run(self, tmp_path: Path) -> None:
+ """A patch reaches the test that declares it, not the whole class."""
+ drives = _drives_across_modules(
+ tmp_path,
+ {
+ "app.helpers": """
+ from posthog.api.services.query import process_query_dict
+
+ def run_it(team, query):
+ return process_query_dict(team, query)
+ """,
+ "app.test_thing": """
+ from unittest.mock import patch
+
+ from app.helpers import run_it
+
+ class TestPaths:
+ @patch("app.helpers.process_query_dict")
+ def test_mocked(self, mock_run, team):
+ run_it(team, {"kind": "PathsQuery"})
+
+ def test_real(self, team):
+ run_it(team, {"kind": "PathsQuery"})
+ """,
+ },
+ "app.test_thing",
+ )
+ assert drives == {("product_analytics", "PathsQuery"): 1}
+
+ def test_a_local_call_is_not_answered_by_the_outward_lookup(self, tmp_path: Path) -> None:
+ """The two resolution modes search different targets, so one cannot cache for the other.
+
+ Reached in a real scan when a test module both is scanned and is imported from."""
+ calls = crossings._CallGraph(
+ _write_modules(
+ tmp_path,
+ {
+ "app.thing": """
+ from posthog.api.services.query import process_query_dict
+
+ def helper(team, query):
+ return process_query_dict(team, query)
+ """
+ },
+ )
+ )
+
+ # Nothing binds `helper` through an import, so the outward-only lookup finds no target.
+ assert calls.executes("app.thing", "helper") is False
+ assert calls.executes("app.thing", "helper", local=True) is True
+
+ def test_a_patched_seam_is_not_a_run(self, tmp_path: Path) -> None:
+ """Following the chain faithfully still has to notice the test replaced its end."""
+ drives = _drives_across_modules(
+ tmp_path,
+ {
+ "app.helpers": """
+ from posthog.api.services.query import process_query_dict
+
+ def run_it(team, query):
+ return process_query_dict(team, query)
+ """,
+ "app.test_thing": """
+ from unittest.mock import patch
+
+ from app.helpers import run_it
+
+ @patch("app.helpers.process_query_dict")
+ def test_paths(mock_run, team):
+ run_it(team, {"kind": "PathsQuery"})
+ """,
+ },
+ "app.test_thing",
+ )
+ assert drives == {}
+
def test_lazy_facade_map_resolves_to_its_source_module(self) -> None:
facade = textwrap.dedent(
"""