: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
chore(tests): cache hot request-path work to speed up backend tests (#68889)
Paul D'Ambra6ffcbfa655c4
diff --git a/conftest.py b/conftest.pyindex 6ba2c7cc0c70..780bbbfff618 100644--- a/conftest.py+++ b/conftest.py@@ -30,6 +30,156 @@ def _end_gc_boot_window() -> None:warnings.filterwarnings("ignore", message=r"It looks like `register_random` was passed")+def _cache_reverse_rel_identity() -> None:+ # ForeignObjectRel.identity is a plain property that rebuilds a large nested tuple+ # (including make_hashable over limit_choices_to) on every __eq__/__hash__ call.+ # Query compilation over models whose default manager applies .defer()/.only()+ # (Team, User) hashes and compares these rel objects millions of times per test+ # session. Rel objects are immutable once django.setup() has run, so caching the+ # identity tuple and its hash per instance is safe and cuts that cost entirely.+ from functools import cached_property # noqa: PLC0415 — deferred until pytest_configure++ from django.db.models.fields.reverse_related import ( # noqa: PLC0415 — deferred until pytest_configure+ ForeignObjectRel,+ )++ def walk(klass):+ yield klass+ for sub in klass.__subclasses__():+ yield from walk(sub)++ for klass in walk(ForeignObjectRel):+ prop = klass.__dict__.get("identity")+ if isinstance(prop, property) and prop.fget is not None:+ cached = cached_property(prop.fget)+ cached.__set_name__(klass, "identity")+ klass.identity = cached # type: ignore[assignment]++ def cached_hash(self) -> int:+ try:+ return self._identity_hash+ except AttributeError:+ self._identity_hash = h = hash(self.identity)+ return h++ ForeignObjectRel.__hash__ = cached_hash # type: ignore[assignment] # ty: ignore[invalid-assignment]++ # __eq__ compares the full identity tuples element by element (each element itself a+ # Field with a non-trivial __eq__), and dict probing in select-mask construction calls+ # it millions of times between the same pairs of objects. Rel objects are stable for+ # the life of the process, so memoize results pairwise; keeping a strong ref to the+ # other object means its id() can never be recycled while cached.+ orig_eq = ForeignObjectRel.__eq__++ def cached_eq(self, other):+ if self is other:+ return True+ cache = self.__dict__.get("_eq_cache")+ if cache is None:+ cache = self.__dict__["_eq_cache"] = {}+ entry = cache.get(id(other))+ if entry is None:+ entry = cache[id(other)] = (other, orig_eq(self, other))+ return entry[1]++ # _eq_cache is per-instance and per-session (unbounded), holding strong refs to every+ # object each rel is ever compared with. Bounded by schema size, not test count, so+ # harmless in practice — but don't mistake it for a per-test cache.+ cached_eq.__wrapped__ = orig_eq # exposes the original for the canary tests+ ForeignObjectRel.__eq__ = cached_eq # type: ignore[method-assign, assignment] # ty: ignore[invalid-assignment]+++def _cache_select_masks() -> None:+ # Query.get_select_mask() rebuilds the defer/only select-mask dict on every queryset+ # compile. Models whose default manager applies .defer() (Team, User) recompute the+ # identical mask thousands of times per test session, and building it probes dicts+ # keyed by fields/rels with expensive __hash__/__eq__. The result is a pure function+ # of (model meta, defer flag, deferred names) and its only consumer reads it without+ # mutating, so memoize it. Queries with filtered relations keep the original path.+ from django.db.models.sql.query import Query # noqa: PLC0415 — deferred until pytest_configure++ orig_get_select_mask = Query.get_select_mask+ masks: dict = {}++ def get_select_mask(self):+ field_names, defer = self.deferred_loading+ if not field_names:+ return {}+ if self._filtered_relations:+ return orig_get_select_mask(self)+ key = (self.get_meta(), defer, frozenset(field_names))+ mask = masks.get(key)+ if mask is None:+ mask = masks[key] = orig_get_select_mask(self)+ return mask++ get_select_mask.__wrapped__ = orig_get_select_mask # exposes the original for the canary tests+ Query.get_select_mask = get_select_mask # type: ignore[method-assign] # ty: ignore[invalid-assignment]+++def _cache_drf_field_info() -> None:+ # DRF's ModelSerializer.get_fields() calls model_meta.get_field_info(model) on every+ # serializer *instantiation*, re-walking the model's forward and reverse relations each+ # time. The result is static per model class and consumers never mutate it, so cache it.+ from rest_framework.utils import model_meta # noqa: PLC0415 — deferred until pytest_configure++ orig_get_field_info = model_meta.get_field_info+ infos: dict = {}++ def get_field_info(model):+ key = model if isinstance(model, type) else model.__class__+ info = infos.get(key)+ if info is None:+ info = infos[key] = orig_get_field_info(model)+ return info++ get_field_info.__wrapped__ = orig_get_field_info # exposes the original for the canary tests+ model_meta.get_field_info = get_field_info # type: ignore[method-assign] # ty: ignore[invalid-assignment]+++def _cache_url_resolution() -> None:+ # URL resolution walks PostHog's very large nested router linearly on every request+ # (~thousands of pattern match attempts per resolve). Resolution is deterministic per+ # (resolver, path) and URLResolver instances are stable module-level objects, so memoize+ # matches. Keyed weakly by resolver so urlconf overrides (which build new resolvers)+ # can't alias; the per-hit shallow copy keeps callers free to mutate the match/kwargs.+ import weakref # noqa: PLC0415 — deferred until pytest_configure++ from django.urls import resolvers # noqa: PLC0415 — deferred until pytest_configure++ orig_resolve = resolvers.URLResolver.resolve+ cache: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()++ def resolve(self, path):+ by_path = cache.get(self)+ if by_path is None:+ by_path = cache.setdefault(self, {})+ path_str = str(path)+ hit = by_path.get(path_str)+ if hit is None:+ hit = orig_resolve(self, path)+ by_path[path_str] = hit+ # ResolverMatch blocks copy.copy via __reduce_ex__, so clone through __dict__.+ # Copy the kwargs dicts — the attributes consumers realistically mutate — so+ # mutation can't poison the cached original.+ match = object.__new__(type(hit))+ match.__dict__.update(hit.__dict__)+ match.kwargs = dict(hit.kwargs)+ match.captured_kwargs = dict(getattr(hit, "captured_kwargs", None) or {})+ match.extra_kwargs = dict(getattr(hit, "extra_kwargs", None) or {})+ return match++ resolve.__wrapped__ = orig_resolve # exposes the original for the canary tests+ resolvers.URLResolver.resolve = resolve # type: ignore[method-assign] # ty: ignore[invalid-assignment]+++def pytest_configure(config) -> None:+ _cache_reverse_rel_identity()+ _cache_select_masks()+ _cache_drf_field_info()+ _cache_url_resolution()++def pytest_collection_finish() -> None:_end_gc_boot_window()diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 6a2b07d86942..1cdc4068a3bd 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -575,9 +575,16 @@ def get_query_tag_value(key: str) -> Optional[Any]:return None+# Tag snapshots are isolated copy-on-write: every mutation goes through a top-level attribute+# assignment on a fresh shallow copy (see update/with_temporal/with_dagster), and nested tag+# objects are only ever replaced, never mutated in place. That makes shallow model_copy()+# sufficient for isolation — deep copies here were the dominant cost of tag_queries, which runs+# on every request and every ClickHouse query. Keep that invariant when adding new tag helpers.++def update_tags(new_query_tags: QueryTags):current_tags = get_query_tags()- updated_tags = current_tags.model_copy(deep=True)+ updated_tags = current_tags.model_copy()updated_tags.update(**new_query_tags.model_dump(exclude_none=True))query_tags.set(updated_tags)@@ -590,7 +597,7 @@ def tag_queries(**kwargs) -> None::param kwargs: Key->value pairs of tags to be set."""current_tags = get_query_tags()- updated_tags = current_tags.model_copy(deep=True)+ updated_tags = current_tags.model_copy()updated_tags.update(**kwargs)query_tags.set(updated_tags)@@ -641,7 +648,7 @@ def get_team_query_tags(team: "Team") -> dict[str, Any]:def clear_tag(key):with suppress(LookupError):current_tags = query_tags.get()- updated_tags = current_tags.model_copy(deep=True)+ updated_tags = current_tags.model_copy()setattr(updated_tags, key, None)query_tags.set(updated_tags)@@ -802,7 +809,7 @@ def tags_context(**tags_to_set: Any) -> Generator[None]:"""tags_copy: Optional[QueryTags] = Nonetry:- tags_copy = get_query_tags().model_copy(deep=True)+ tags_copy = get_query_tags().model_copy()if tags_to_set:tag_queries(**tags_to_set)yielddiff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.pyindex b9439f6cade4..68695752ee7e 100644--- a/posthog/clickhouse/schema.py+++ b/posthog/clickhouse/schema.py@@ -1,5 +1,6 @@# This file contains all CREATE TABLE queries, used to sync and test schemaimport re+from collections.abc import Callablefrom posthog.clickhouse.dead_letter_queue import (DEAD_LETTER_QUEUE_TABLE_MV_SQL,@@ -144,6 +145,7 @@ from posthog.models.app_metrics2.sql import (from posthog.models.channel_type.sql import (CHANNEL_DEFINITION_DATA_SQL,CHANNEL_DEFINITION_DICTIONARY_SQL,+ CHANNEL_DEFINITION_TABLE_NAME,CHANNEL_DEFINITION_TABLE_SQL,)from posthog.models.cohortmembership.sql import (@@ -178,6 +180,7 @@ from posthog.models.event.sql import (from posthog.models.exchange_rate.sql import (EXCHANGE_RATE_DATA_BACKFILL_SQL,EXCHANGE_RATE_DICTIONARY_SQL,+ EXCHANGE_RATE_TABLE_NAME,EXCHANGE_RATE_TABLE_SQL,)from posthog.models.group.sql import (@@ -564,8 +567,17 @@ CREATE_DICTIONARY_QUERIES = ()+# Single source of truth for seed-data tables: (table_name, query_fn).+# CREATE_DATA_QUERIES is derived from this tuple; conftest.py imports it too+# so the per-table skip-if-present gate in create_clickhouse_tables stays in sync.+SEED_DATA_TABLES: tuple[tuple[str, Callable[[], str]], ...] = (+ (CHANNEL_DEFINITION_TABLE_NAME, CHANNEL_DEFINITION_DATA_SQL),+ (EXCHANGE_RATE_TABLE_NAME, EXCHANGE_RATE_DATA_BACKFILL_SQL),+)++def CREATE_DATA_QUERIES():- return (CHANNEL_DEFINITION_DATA_SQL(), EXCHANGE_RATE_DATA_BACKFILL_SQL())+ return tuple(fn() for _, fn in SEED_DATA_TABLES)CREATE_VIEW_QUERIES = (diff --git a/posthog/clickhouse/test/test_query_tagging.py b/posthog/clickhouse/test/test_query_tagging.pyindex 642c56dd7ce5..3cc62d33de54 100644--- a/posthog/clickhouse/test/test_query_tagging.py+++ b/posthog/clickhouse/test/test_query_tagging.py@@ -16,6 +16,7 @@ from posthog.clickhouse.query_tagging import (_PROJECT_ROOT_PREFIX,_SOURCE_SKIP_PREFIXES,AccessMethod,+ DagsterTags,Feature,HogQLFeatures,Product,@@ -141,6 +142,40 @@ def test_tags_context():assert get_query_tags() == create_base_tags(team_id=123)+def test_tags_context_snapshot_isolation():+ # Shallow-copy invariant: mutations through public helpers must not corrupt the+ # saved snapshot that tags_context restores. Regression guard for the switch from+ # deep to shallow model_copy in update_tags/tag_queries.+ #+ # A nested tag object set *before* taking the snapshot inside tags_context exercises+ # the shallow-copy hazard: if the copy is truly shallow and with_temporal were to+ # mutate the nested object in place (rather than replace the attribute), the snapshot+ # would be corrupted. Setting a sentinel value before the snapshot lets us assert+ # the nested object is untouched after all the in-context mutations.+ reset_query_tags()+ tag_queries(team_id=1)++ with tags_context(user_id=42):+ # Set a nested tag before taking the snapshot, then snapshot.+ get_query_tags().with_temporal(TemporalTags(workflow_type="wt-before"))+ snapshot = get_query_tags()+ # Drive every public mutation helper after the snapshot is taken.+ tag_queries(team_id=2)+ update_tags(create_base_tags(cohort_id=99))+ clear_tag("user_id")+ qt = get_query_tags()+ qt.with_temporal(TemporalTags(workflow_type="wt"))+ qt.with_dagster(DagsterTags(run_id="run-1"))++ # The snapshot taken inside tags_context must be untouched by all mutations above,+ # including the nested temporal object that was set before the snapshot was taken.+ expected = create_base_tags(team_id=1, user_id=42)+ expected.with_temporal(TemporalTags(workflow_type="wt-before"))+ assert snapshot == expected+ assert snapshot.temporal is not None+ assert snapshot.temporal.workflow_type == "wt-before"++@pytest.mark.asyncioasync def test_async_tasks_have_isolated_tags():reset_query_tags()@@ -312,7 +347,7 @@ def test_tag_contains_user_hogql_is_idempotent():def test_tag_contains_user_hogql_short_circuits_after_first_call():# Repeated calls (recursive property_to_expr, breakdown loops, @property accessors)- # must skip the model_copy(deep=True) inside tag_queries after the first call.+ # must skip the model_copy() inside tag_queries after the first call.reset_query_tags()tag_contains_user_hogql()first_tags = get_query_tags()diff --git a/posthog/conftest.py b/posthog/conftest.pyindex 70d07f24aff8..cce939200a5f 100644--- a/posthog/conftest.py+++ b/posthog/conftest.py@@ -27,13 +27,13 @@ def create_clickhouse_tables():# Create clickhouse tables to default before running test# Mostly so that test runs locally work correctlyfrom posthog.clickhouse.schema import (- CREATE_DATA_QUERIES,CREATE_DICTIONARY_QUERIES,CREATE_DISTRIBUTED_TABLE_QUERIES,CREATE_KAFKA_TABLE_QUERIES,CREATE_MERGETREE_TABLE_QUERIES,CREATE_MV_TABLE_QUERIES,CREATE_VIEW_QUERIES,+ SEED_DATA_TABLES,build_query,get_table_name,)@@ -74,8 +74,16 @@ def create_clickhouse_tables():if dictionary_queries:run_clickhouse_statement_in_parallel(dictionary_queries)- data_queries = list(map(build_query, CREATE_DATA_QUERIES()))- run_clickhouse_statement_in_parallel(data_queries)+ # Building the exchange-rate INSERT parses a 9 MB CSV and renders a ~100k-row VALUES+ # string on every pytest invocation. With a reused database the seed data is already+ # there, so skip the reload per-table (mirroring the `missing()` check above for tables).+ # Derived from SEED_DATA_TABLES in schema.py, which also drives CREATE_DATA_QUERIES,+ # so a new seed table added there is automatically picked up here.+ # TRUNCATE-based resets go through reset_clickhouse_tables, which reloads unconditionally.+ for table_name, query_fn in SEED_DATA_TABLES:+ count = sync_execute(f"SELECT count() FROM {table_name}")[0][0]+ if not count:+ run_clickhouse_statement_in_parallel([build_query(query_fn)])def reset_clickhouse_tables():diff --git a/posthog/git.py b/posthog/git.pyindex 2c160a45b28a..5dcba76caebb 100644--- a/posthog/git.py+++ b/posthog/git.py@@ -1,5 +1,6 @@import reimport subprocess+from functools import cachefrom typing import Optional_git_commit_baked_in: Optional[str] = None@@ -12,10 +13,14 @@ except FileNotFoundError:pass+@cachedef get_git_commit_short() -> Optional[str]:"""Return the short hash of the last commit.Example: get_git_commit_short() => "86a3c3b529"++ Cached: the commit cannot change within a running process, and callers on the+ request path (SLO events) would otherwise spawn a `git rev-parse` per request."""if _git_commit_baked_in:return _git_commit_baked_in[:10] # 10 characters is almost guaranteed to identify a commit uniquely@@ -25,10 +30,13 @@ def get_git_commit_short() -> Optional[str]:return None+@cachedef get_git_branch() -> Optional[str]:"""Returns the symbolic name of the current active branch. Will return None in case of failure.Example: get_git_branch() => "master"++ Cached for the same reason as get_git_commit_short."""try:diff --git a/posthog/test/test_conftest_cache_canaries.py b/posthog/test/test_conftest_cache_canaries.pynew file mode 100644index 000000000000..37a10ed13249--- /dev/null+++ b/posthog/test/test_conftest_cache_canaries.py@@ -0,0 +1,113 @@+# Canary tests for the test-harness monkeypatches in the repo-root conftest.py.+#+# Each patch caches a Django/DRF internal on the assumption that it is a pure function+# of immutable inputs *in the currently pinned Django/DRF version*. If an upgrade+# invalidates one of those assumptions, the harness would silently diverge from stock+# behavior and surface as unrelated flakes with nothing pointing at conftest.py.+# These tests compare each patched callable against its unpatched original (exposed+# as `__wrapped__` at the patch site) for a representative case, so the divergence+# fails loudly here instead.+#+# If one of these fails after a Django/DRF upgrade: re-verify the assumption named in+# the corresponding `_cache_*` function in conftest.py, and if it no longer holds,+# delete that patch — do not "fix" the test.++from django.db.models.fields.reverse_related import ForeignObjectRel+from django.db.models.sql.query import Query+from django.urls import resolvers++from rest_framework.utils import model_meta++from posthog.models import Team+++def _unpatched(patched):+ orig = getattr(patched, "__wrapped__", None)+ assert orig is not None, (+ f"{patched} does not expose its unpatched original via __wrapped__ — "+ "was the conftest.py patch changed without updating the canaries?"+ )+ return orig+++def test_select_mask_cache_matches_unpatched_django():+ # Assumption: get_select_mask is a pure function of (model meta, defer flag,+ # deferred names) and consumers never mutate the returned mask.+ query = Team.objects.all().query # Team's default manager applies .defer()+ field_names, _ = query.deferred_loading+ assert field_names, "Team no longer defers fields — pick another model for this canary"+ patched = query.get_select_mask()+ fresh = _unpatched(Query.get_select_mask)(query)+ assert patched == fresh+ # Repeated calls serve the memoized mask and must stay equal to a fresh compute.+ assert query.get_select_mask() == fresh+++def test_rel_identity_cache_matches_unpatched_django():+ # Assumption: ForeignObjectRel objects are immutable after django.setup(), so+ # identity/__hash__ can be cached per instance and __eq__ memoized pairwise.+ rels = [f for f in Team._meta.get_fields() if isinstance(f, ForeignObjectRel)]+ assert len(rels) >= 2, "Team has no reverse relations — pick another model for this canary"+ orig_eq = _unpatched(ForeignObjectRel.__eq__)+ for rel in rels[:5]:+ # identity is an undocumented Django internal, absent from django-stubs.+ cached_identity = rel.identity # type: ignore[attr-defined] # via the cached_property installed by conftest+ cached_hash = hash(rel)+ # Recompute from the original property fget (cached_property.func). Subclass fgets+ # (ManyToOneRel etc.) internally do `super().identity`, which routes through the+ # base class's cached_property and leaves the partial base tuple in the instance+ # dict — so clear the instance cache before and after to keep the rel pristine.+ descriptor = type(rel).identity # type: ignore[attr-defined]+ rel.__dict__.pop("identity", None)+ try:+ fresh_identity = descriptor.func(rel)+ finally:+ # Always restore: rels are process-global, and a partial tuple left behind+ # would corrupt hash/eq for every later test in the same worker.+ rel.__dict__.pop("identity", None)+ assert cached_identity == fresh_identity+ assert cached_hash == hash(fresh_identity)+ # Compare a same-class pair — across classes the original __eq__ returns+ # NotImplemented rather than a bool.+ by_type: dict[type, list[ForeignObjectRel]] = {}+ for rel in rels:+ by_type.setdefault(type(rel), []).append(rel)+ pair = next((group for group in by_type.values() if len(group) >= 2), None)+ assert pair is not None, "no two Team rels share a class — pick another model for this canary"+ a, b = pair[0], pair[1]+ assert (a == b) == bool(orig_eq(a, b))+ assert (a == a) == bool(orig_eq(a, a))+++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)+ fresh = _unpatched(model_meta.get_field_info)(Team)+ assert patched == fresh+++def test_url_resolution_cache_matches_unpatched_django():+ # Assumption: URLResolver.resolve is deterministic per (resolver, path), and the+ # __dict__-based ResolverMatch clone reproduces everything consumers read.+ resolver = resolvers.get_resolver()+ path = "/api/users/@me/"+ patched = resolver.resolve(path)+ fresh = _unpatched(resolvers.URLResolver.resolve)(resolver, path)+ for attr in (+ "func",+ "args",+ "kwargs",+ "url_name",+ "route",+ "app_names",+ "namespaces",+ "captured_kwargs",+ "extra_kwargs",+ "view_name",+ ):+ assert getattr(patched, attr) == getattr(fresh, attr), f"ResolverMatch.{attr} diverged from unpatched resolve"+ # A second resolve serves the cached match — mutating one clone's kwargs must not+ # leak into the next (the cross-test cache-poisoning hazard).+ patched.kwargs["canary"] = True+ again = resolver.resolve(path)+ assert "canary" not in again.kwargs