Skip to content

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

feat(autoresearch): cut backend test collection overhead (#88759)

Paul D'Ambra5df7d36a3e64
diff --git a/conftest.py b/conftest.py
index 914fe84ff58a..15e25b9736e9 100644
--- a/conftest.py
+++ b/conftest.py
@@ -180,6 +180,29 @@ def _cache_url_resolution() -> None:
resolvers.URLResolver.resolve = resolve # type: ignore[method-assign] # ty: ignore[invalid-assignment]
+def _cache_fixture_parent_nodeids() -> None:
+ # FixtureManager._matchfactories rebuilds a node's parent-nodeid set for every fixture-name
+ # lookup, and collection resolves many fixture names per item. A node's parents are fixed at
+ # construction, so the set can be reused. Node uses __slots__, so key by id() and keep a strong
+ # reference to prevent id() reuse for the node's session lifetime.
+ from _pytest import fixtures, nodes # noqa: PLC0415 — deferred until pytest_configure
+
+ orig_matchfactories = fixtures.FixtureManager._matchfactories
+ parents: dict[int, tuple[nodes.Node, set[str]]] = {}
+
+ def _matchfactories(self, fixturedefs, node):
+ entry = parents.get(id(node))
+ if entry is None:
+ entry = parents[id(node)] = (node, {n.nodeid for n in node.iter_parents()})
+ parentnodeids = entry[1]
+ for fixturedef in fixturedefs:
+ if fixturedef.baseid in parentnodeids:
+ yield fixturedef
+
+ _matchfactories.__wrapped__ = orig_matchfactories # exposes the original for the canary tests
+ fixtures.FixtureManager._matchfactories = _matchfactories # type: ignore[method-assign] # ty: ignore[invalid-assignment]
+
+
def _cheapen_freezegun_module_hash() -> None:
# Every freeze_time().start() revalidates freezegun's per-module patch cache by
# hashing each loaded module's attribute list: hash(frozenset(dir(module))) across
@@ -211,6 +234,7 @@ def pytest_configure(config) -> None:
_cache_select_masks()
_cache_drf_field_info()
_cache_url_resolution()
+ _cache_fixture_parent_nodeids()
_cheapen_freezegun_module_hash()
diff --git a/ee/hogai/eval/offline/conftest.py b/ee/hogai/eval/offline/conftest.py
index 7cf652bf12ef..385f9a8ead7a 100644
--- a/ee/hogai/eval/offline/conftest.py
+++ b/ee/hogai/eval/offline/conftest.py
@@ -1,3 +1,4 @@
+import os
import json
from collections.abc import Awaitable, Callable, Generator
from contextlib import contextmanager
@@ -224,7 +225,11 @@ def pytest_collection_modifyitems(items):
One test file might contain multiple evaluation tests cases.
This hook will automatically apply the local evaluation context to all of them.
"""
- current_dir = Path(__file__).parent
+ # pytest calls this hook with every item in the session, not only the ones under this
+ # directory, so the test runs tens of thousands of times on a full-tree shard. A string
+ # prefix is the same test as is_relative_to for these absolute paths, and it avoids both
+ # re-parsing item.fspath into a Path and walking Path.parents once per item.
+ current_dir_prefix = f"{Path(__file__).parent}{os.sep}"
for item in items:
- if Path(item.fspath).is_relative_to(current_dir):
+ if str(item.path).startswith(current_dir_prefix):
item.obj = with_eval_context(item.obj)
diff --git a/posthog/test/test_conftest_cache_canaries.py b/posthog/test/test_conftest_cache_canaries.py
index b18bc0d62e22..f9e3ce85addb 100644
--- a/posthog/test/test_conftest_cache_canaries.py
+++ b/posthog/test/test_conftest_cache_canaries.py
@@ -17,6 +17,7 @@ from django.db.models.fields.reverse_related import ForeignObjectRel
from django.db.models.sql.query import Query
from django.urls import resolvers
+from _pytest.fixtures import FixtureManager
from rest_framework.utils import model_meta
from posthog.clickhouse.client.connection import get_client_from_pool, get_pool
@@ -99,6 +100,24 @@ def test_clickhouse_checkout_counter_is_wired():
assert test_base._clickhouse_pool_checkouts > before
+def test_fixture_parent_nodeids_cache_matches_unpatched_pytest(request):
+ # Assumption: a node's parents, and their nodeids, are fixed once the node is
+ # constructed, so the set can be memoized per node instead of rebuilt per lookup.
+ manager = request._fixturemanager
+ node = request.node
+ orig = _unpatched(FixtureManager._matchfactories)
+ names = sorted(manager._arg2fixturedefs)
+ assert names, "no fixtures registered — this canary needs a populated fixture manager"
+ for argname in names:
+ fixturedefs = manager._arg2fixturedefs[argname]
+ fresh = list(orig(manager, fixturedefs, node))
+ assert list(manager._matchfactories(fixturedefs, node)) == fresh, (
+ f"cached parent nodeids changed which fixtures match {argname!r}"
+ )
+ # The second call is served from the memo and must still agree.
+ assert list(manager._matchfactories(fixturedefs, node)) == fresh
+
+
def test_drf_field_info_cache_matches_unpatched_drf():
# Assumption: get_field_info is static per model class and consumers never mutate it.
patched = model_meta.get_field_info(Team)