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.

perf(hogql): cache static catalog via pickle instead of rebuilding (#63591)

Robbieefc4f2f77c1c
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 1d3a0e7aa9df..e7a58a7f4e07 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -1,5 +1,9 @@
+import io
import copy
+import pickle
+import threading
import dataclasses
+import pickletools
from collections import defaultdict
from collections.abc import Callable, Sequence
from datetime import UTC, datetime
@@ -296,7 +300,49 @@ ROOT_TABLES__DO_NOT_ADD_ANY_MORE: dict[str, TableNode] = {
# --------------------
+# The static catalog is identical for every team/request, so build + pickle it once and reload per
+# request. Each load returns an independent tree (so per-request mutation can't leak between teams);
+# the in-process blob can't go stale across deploys. Every catalog node must stay picklable.
+_DATABASE_ROOT_NODE_BLOBS: dict[bool, bytes] = {}
+_DATABASE_ROOT_NODE_BLOBS_LOCK = threading.Lock()
+
+# We only ever load our own freshly-built blob, but restrict the unpickler anyway as defense in depth:
+# it can reconstruct only the classes the catalog is built from, so even a future change that fed it
+# untrusted bytes couldn't instantiate arbitrary code (os.system, etc.). Every catalog class lives
+# under posthog.hogql.* except the Workload enum, so new table/field/AST types keep working and
+# anything else fails loudly.
+_CATALOG_PICKLE_MODULE_PREFIXES = ("posthog.hogql.",)
+_CATALOG_PICKLE_MODULES = frozenset({"posthog.clickhouse.workload"})
+
+
+class _CatalogUnpickler(pickle.Unpickler):
+ def find_class(self, module: str, name: str) -> Any:
+ if module.startswith(_CATALOG_PICKLE_MODULE_PREFIXES) or module in _CATALOG_PICKLE_MODULES:
+ return super().find_class(module, name)
+ # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle (allowlist guard rejecting a class, not deserialising untrusted data)
+ raise pickle.UnpicklingError(f"refusing to unpickle disallowed catalog global {module}.{name}")
+
+
def build_database_root_node(*, include_posthog_tables: bool = True) -> TableNode:
+ # Double-checked locking so concurrent first-callers don't each rebuild + pickle the catalog.
+ blob = _DATABASE_ROOT_NODE_BLOBS.get(include_posthog_tables)
+ if blob is None:
+ with _DATABASE_ROOT_NODE_BLOBS_LOCK:
+ blob = _DATABASE_ROOT_NODE_BLOBS.get(include_posthog_tables)
+ if blob is None:
+ # Built lazily, not eager-warmed at import: that would move this cost onto startup for every importer of this module, query-related or not.
+ # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle (serialising our own code-built catalog; loads are restricted by _CatalogUnpickler)
+ blob = pickle.dumps(
+ _construct_database_root_node(include_posthog_tables=include_posthog_tables),
+ protocol=pickle.HIGHEST_PROTOCOL,
+ )
+ blob = pickletools.optimize(blob) # drop unused memo opcodes: ~10% smaller, faster load
+ _DATABASE_ROOT_NODE_BLOBS[include_posthog_tables] = blob
+ # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle (_CatalogUnpickler restricts find_class to catalog classes, so untrusted bytes still can't execute code)
+ return _CatalogUnpickler(io.BytesIO(blob)).load()
+
+
+def _construct_database_root_node(*, include_posthog_tables: bool) -> TableNode:
def clone_root_tables() -> dict[str, TableNode]:
return {name: table_node.model_copy(deep=True) for name, table_node in ROOT_TABLES__DO_NOT_ADD_ANY_MORE.items()}
diff --git a/posthog/hogql/database/models.py b/posthog/hogql/database/models.py
index 660e907945aa..f8ca90123f1c 100644
--- a/posthog/hogql/database/models.py
+++ b/posthog/hogql/database/models.py
@@ -1,6 +1,6 @@
import datetime
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Literal, Optional
+from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from pydantic import (
BaseModel,
@@ -21,9 +21,33 @@ if TYPE_CHECKING:
from posthog.hogql.context import HogQLContext
+# Trim pydantic's default per-node pickle state to just __dict__ and rebuild the bookkeeping on load.
+# This improves performance by 20-40%
+def _slim_pickle_getstate(model: BaseModel) -> dict[Any, Any]:
+ if model.__pydantic_extra__ is None and model.__pydantic_private__ is None:
+ return cast("dict[Any, Any]", model.__dict__)
+ return BaseModel.__getstate__(model)
+
+
+def _slim_pickle_setstate(model: BaseModel, state: dict[Any, Any]) -> None:
+ if "__pydantic_fields_set__" in state: # pydantic's full state — restore verbatim
+ BaseModel.__setstate__(model, state)
+ return
+ object.__setattr__(model, "__dict__", state)
+ object.__setattr__(model, "__pydantic_fields_set__", set(state))
+ object.__setattr__(model, "__pydantic_extra__", None)
+ object.__setattr__(model, "__pydantic_private__", None)
+
+
class FieldOrTable(BaseModel):
hidden: bool = False
+ def __getstate__(self) -> dict[Any, Any]:
+ return _slim_pickle_getstate(self)
+
+ def __setstate__(self, state: dict[Any, Any]) -> None:
+ _slim_pickle_setstate(self, state)
+
class DatabaseField(FieldOrTable):
"""
@@ -239,6 +263,12 @@ class TableNode(BaseModel):
# via subqueries) but is omitted from the SQL editor schema and autocomplete lists.
hidden: bool = False
+ def __getstate__(self) -> dict[Any, Any]:
+ return _slim_pickle_getstate(self)
+
+ def __setstate__(self, state: dict[Any, Any]) -> None:
+ _slim_pickle_setstate(self, state)
+
def get(self) -> FieldOrTable:
"""
Evaluates and returns the table currently associated with this node.
diff --git a/posthog/hogql/database/test/test_database.py b/posthog/hogql/database/test/test_database.py
index 5320543c82c5..08da550e6378 100644
--- a/posthog/hogql/database/test/test_database.py
+++ b/posthog/hogql/database/test/test_database.py
@@ -1,13 +1,18 @@
+import io
import json
+import pickle
+import dataclasses
from typing import Any, cast
import pytest
from posthog.test.base import BaseTest, FuzzyInt, QueryMatchingTest, snapshot_postgres_queries
+from unittest import TestCase
from unittest.mock import patch
from django.test import override_settings
from parameterized import parameterized
+from pydantic import BaseModel
from posthog.schema import (
DatabaseSchemaDataWarehouseTable,
@@ -22,7 +27,9 @@ from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import (
ROOT_TABLES__DO_NOT_ADD_ANY_MORE,
Database,
+ _CatalogUnpickler,
_compute_system_table_access_decision,
+ _construct_database_root_node,
_preload_active_external_data_schemas,
build_database_root_node,
get_data_warehouse_table_name,
@@ -62,6 +69,99 @@ from products.warehouse_sources.backend.models.external_data_source import Exter
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+def _collect_mutable_object_ids(obj: Any, ids: set[int]) -> None:
+ # Record the id() of every mutable object in a catalog tree, so two trees can be checked for sharing.
+ stack = [obj]
+ seen: set[int] = set()
+ while stack:
+ current = stack.pop()
+ if id(current) in seen:
+ continue
+ seen.add(id(current))
+ if isinstance(current, BaseModel):
+ ids.add(id(current))
+ stack.extend(current.__dict__.values())
+ elif dataclasses.is_dataclass(current) and not isinstance(current, type):
+ ids.add(id(current))
+ stack.extend(getattr(current, f.name) for f in dataclasses.fields(current))
+ elif isinstance(current, dict):
+ ids.add(id(current))
+ stack.extend(current.values())
+ elif isinstance(current, (list, set)):
+ ids.add(id(current))
+ stack.extend(current)
+ elif isinstance(current, (tuple, frozenset)):
+ stack.extend(current)
+
+
+class TestBuildDatabaseRootNode(TestCase):
+ # The static catalog build touches no database, so these run on a plain TestCase (no Postgres).
+
+ @parameterized.expand([("with_posthog_tables", True), ("without_posthog_tables", False)])
+ def test_build_database_root_node_matches_fresh_construction(self, _name: str, include_posthog_tables: bool):
+ cached = build_database_root_node(include_posthog_tables=include_posthog_tables)
+ fresh = _construct_database_root_node(include_posthog_tables=include_posthog_tables)
+
+ assert cached == fresh
+ assert cached is not fresh
+ if include_posthog_tables:
+ assert "events" in cached.children
+
+ @parameterized.expand([("with_posthog_tables", True), ("without_posthog_tables", False)])
+ def test_build_database_root_node_catalog_stays_picklable(self, _name: str, include_posthog_tables: bool):
+ # Guards against a future catalog field becoming unpicklable (which would otherwise fail at request time).
+ fresh = _construct_database_root_node(include_posthog_tables=include_posthog_tables)
+ restored = pickle.loads(pickle.dumps(fresh, protocol=pickle.HIGHEST_PROTOCOL))
+
+ assert restored == fresh
+ if include_posthog_tables:
+ assert restored.children["events"].table is not fresh.children["events"].table
+
+ def test_build_database_root_node_loads_are_deeply_independent(self):
+ # Hold both trees while walking, or a GC'd first tree's id()s get recycled by the second (false overlap).
+ first = build_database_root_node()
+ second = build_database_root_node()
+ first_ids: set[int] = set()
+ second_ids: set[int] = set()
+ _collect_mutable_object_ids(first, first_ids)
+ _collect_mutable_object_ids(second, second_ids)
+
+ assert first_ids and second_ids
+ assert first_ids.isdisjoint(second_ids)
+
+ def test_slim_pickle_state_falls_back_when_private_or_extra_present(self):
+ # Slim path: a plain field round-trips its values.
+ field = StringDatabaseField(name="col")
+ restored = pickle.loads(pickle.dumps(field, protocol=pickle.HIGHEST_PROTOCOL))
+ assert restored == field and restored.name == "col"
+
+ # extra/private set: must fall back to full state so they survive the round-trip.
+ with_private = StringDatabaseField(name="col")
+ object.__setattr__(with_private, "__pydantic_private__", {"secret": 1})
+ restored_private = pickle.loads(pickle.dumps(with_private, protocol=pickle.HIGHEST_PROTOCOL))
+ assert restored_private.__pydantic_private__ == {"secret": 1}
+
+ with_extra = StringDatabaseField(name="col")
+ object.__setattr__(with_extra, "__pydantic_extra__", {"extra_key": "value"})
+ restored_extra = pickle.loads(pickle.dumps(with_extra, protocol=pickle.HIGHEST_PROTOCOL))
+ assert restored_extra.__pydantic_extra__ == {"extra_key": "value"}
+
+ def test_catalog_unpickler_allowlists_catalog_classes_and_rejects_others(self):
+ # Restricted unpickler resolves catalog classes but rejects anything else, so a tampered blob
+ # can't instantiate code-execution gadgets.
+ unpickler = _CatalogUnpickler(io.BytesIO(b""))
+ assert unpickler.find_class("posthog.hogql.database.models", "StringDatabaseField") is not None
+ assert unpickler.find_class("posthog.clickhouse.workload", "Workload") is not None
+ for module, name in [
+ ("os", "system"),
+ ("builtins", "eval"),
+ ("subprocess", "Popen"),
+ ("posthog.models", "Team"),
+ ]:
+ with self.assertRaises(pickle.UnpicklingError):
+ unpickler.find_class(module, name)
+
+
class TestDatabase(BaseTest, QueryMatchingTest):
snapshot: Any