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(data-deletion): cache compiled hogql predicate for admin, lock team (#64532)

Paweł Szczur1e610f710ad9
diff --git a/logs/pr-64532/27758632672/findings.json b/logs/pr-64532/27758632672/findings.json
new file mode 100644
index 000000000000..81899b146852
--- /dev/null
+++ b/logs/pr-64532/27758632672/findings.json
@@ -0,0 +1,80 @@
+{
+ "analyzed_at": "2026-06-18T12:17:23.431698+00:00",
+ "run_id": "27758632672",
+ "jobs_overview": [
+ {
+ "job_name": "Python code quality (depot-ubuntu-latest)",
+ "conclusion": "failure",
+ "duration_secs": 146,
+ "failed_steps": [
+ {
+ "name": "Check static typing",
+ "conclusion": "failure",
+ "number": 15,
+ "duration_secs": 40
+ }
+ ]
+ },
+ {
+ "job_name": "Python code quality checks",
+ "conclusion": "failure",
+ "duration_secs": 3,
+ "failed_steps": [
+ {
+ "name": "Check Python CI status",
+ "conclusion": "failure",
+ "number": 2,
+ "duration_secs": 0
+ }
+ ]
+ },
+ {
+ "job_name": "Determine need to run python checks",
+ "conclusion": "success",
+ "duration_secs": 21
+ }
+ ],
+ "errors": [
+ {
+ "framework": "workflow",
+ "test_file": "Python code quality checks",
+ "test_name": "Check Python CI status",
+ "error_type": "failure",
+ "message": "",
+ "line": null,
+ "occurrences": [
+ {
+ "job": "Python code quality checks",
+ "log_file": "",
+ "traceback": null
+ }
+ ]
+ },
+ {
+ "framework": "workflow",
+ "test_file": "Python code quality (depot-ubuntu-latest)",
+ "test_name": "Check static typing",
+ "error_type": "failure",
+ "message": "",
+ "line": null,
+ "occurrences": [
+ {
+ "job": "Python code quality (depot-ubuntu-latest)",
+ "log_file": "",
+ "traceback": null
+ }
+ ]
+ }
+ ],
+ "summary": {
+ "total_unique_errors": 2,
+ "total_error_occurrences": 2,
+ "jobs_analyzed": 2,
+ "by_framework": {
+ "workflow": {
+ "unique_errors": 2,
+ "total_occurrences": 2
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/logs/pr-64532/27758632672/metadata.json b/logs/pr-64532/27758632672/metadata.json
new file mode 100644
index 000000000000..89952e603a05
--- /dev/null
+++ b/logs/pr-64532/27758632672/metadata.json
@@ -0,0 +1,308 @@
+{
+ "run_id": "27758632672",
+ "run_number": 174877,
+ "head_sha": "6eee8d8d0bec909cb34102a8f9f637d44f39fe40",
+ "head_branch": "pawel/feat/cache-data-deletion-predicate",
+ "pr_number": 64532,
+ "html_url": "https://github.com/PostHog/posthog/actions/runs/27758632672",
+ "created_at": "2026-06-18T12:13:36Z",
+ "updated_at": "2026-06-18T12:16:40Z",
+ "total_jobs": 3,
+ "failed_jobs": 2,
+ "downloaded_at": "2026-06-18T12:17:23.428629+00:00",
+ "jobs": [
+ {
+ "id": 82126849706,
+ "name": "Determine need to run python checks",
+ "conclusion": "success",
+ "started_at": "2026-06-18T12:13:39Z",
+ "completed_at": "2026-06-18T12:14:00Z",
+ "steps": [
+ {
+ "name": "Set up job",
+ "conclusion": "success",
+ "number": 1,
+ "started_at": "2026-06-18T12:13:39Z",
+ "completed_at": "2026-06-18T12:13:40Z"
+ },
+ {
+ "name": "Run actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd",
+ "conclusion": "success",
+ "number": 2,
+ "started_at": "2026-06-18T12:13:40Z",
+ "completed_at": "2026-06-18T12:13:57Z"
+ },
+ {
+ "name": "Run actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3",
+ "conclusion": "success",
+ "number": 3,
+ "started_at": "2026-06-18T12:13:57Z",
+ "completed_at": "2026-06-18T12:13:58Z"
+ },
+ {
+ "name": "Run dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d",
+ "conclusion": "success",
+ "number": 4,
+ "started_at": "2026-06-18T12:13:58Z",
+ "completed_at": "2026-06-18T12:13:58Z"
+ },
+ {
+ "name": "Post Run actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3",
+ "conclusion": "success",
+ "number": 7,
+ "started_at": "2026-06-18T12:13:58Z",
+ "completed_at": "2026-06-18T12:13:59Z"
+ },
+ {
+ "name": "Post Run actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd",
+ "conclusion": "success",
+ "number": 8,
+ "started_at": "2026-06-18T12:13:59Z",
+ "completed_at": "2026-06-18T12:13:59Z"
+ },
+ {
+ "name": "Complete job",
+ "conclusion": "success",
+ "number": 9,
+ "started_at": "2026-06-18T12:13:59Z",
+ "completed_at": "2026-06-18T12:13:59Z"
+ }
+ ]
+ },
+ {
+ "id": 82126923512,
+ "name": "Python code quality (depot-ubuntu-latest)",
+ "conclusion": "failure",
+ "started_at": "2026-06-18T12:14:02Z",
+ "completed_at": "2026-06-18T12:16:28Z",
+ "steps": [
+ {
+ "name": "Set up job",
+ "conclusion": "success",
+ "number": 1,
+ "started_at": "2026-06-18T12:14:24Z",
+ "completed_at": "2026-06-18T12:14:27Z"
+ },
+ {
+ "name": "Run actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd",
+ "conclusion": "success",
+ "number": 2,
+ "started_at": "2026-06-18T12:14:27Z",
+ "completed_at": "2026-06-18T12:14:35Z"
+ },
+ {
+ "name": "Set up Python",
+ "conclusion": "success",
+ "number": 3,
+ "started_at": "2026-06-18T12:14:35Z",
+ "completed_at": "2026-06-18T12:14:35Z"
+ },
+ {
+ "name": "Install uv",
+ "conclusion": "success",
+ "number": 4,
+ "started_at": "2026-06-18T12:14:35Z",
+ "completed_at": "2026-06-18T12:14:41Z"
+ },
+ {
+ "name": "Check uv and Python version compatibility",
+ "conclusion": "success",
+ "number": 5,
+ "started_at": "2026-06-18T12:14:41Z",
+ "completed_at": "2026-06-18T12:14:42Z"
+ },
+ {
+ "name": "Install SAML (python3-saml) dependencies",
+ "conclusion": "skipped",
+ "number": 6,
+ "started_at": "2026-06-18T12:14:42Z",
+ "completed_at": "2026-06-18T12:14:42Z"
+ },
+ {
+ "name": "Install Python dependencies",
+ "conclusion": "success",
+ "number": 7,
+ "started_at": "2026-06-18T12:14:42Z",
+ "completed_at": "2026-06-18T12:14:52Z"
+ },
+ {
+ "name": "Download GeoIP database",
+ "conclusion": "success",
+ "number": 8,
+ "started_at": "2026-06-18T12:14:52Z",
+ "completed_at": "2026-06-18T12:14:53Z"
+ },
+ {
+ "name": "Check for syntax errors, import sort, and code style violations",
+ "conclusion": "success",
+ "number": 9,
+ "started_at": "2026-06-18T12:14:53Z",
+ "completed_at": "2026-06-18T12:14:54Z"
+ },
+ {
+ "name": "Check formatting",
+ "conclusion": "success",
+ "number": 10,
+ "started_at": "2026-06-18T12:14:54Z",
+ "completed_at": "2026-06-18T12:14:56Z"
+ },
+ {
+ "name": "Add ty Problem Matcher",
+ "conclusion": "success",
+ "number": 11,
+ "started_at": "2026-06-18T12:14:56Z",
+ "completed_at": "2026-06-18T12:14:56Z"
+ },
+ {
+ "name": "Check ty type checking",
+ "conclusion": "success",
+ "number": 12,
+ "started_at": "2026-06-18T12:14:56Z",
+ "completed_at": "2026-06-18T12:15:42Z"
+ },
+ {
+ "name": "Add mypy Problem Matcher",
+ "conclusion": "success",
+ "number": 13,
+ "started_at": "2026-06-18T12:15:42Z",
+ "completed_at": "2026-06-18T12:15:42Z"
+ },
+ {
+ "name": "Restore mypy cache",
+ "conclusion": "success",
+ "number": 14,
+ "started_at": "2026-06-18T12:15:42Z",
+ "completed_at": "2026-06-18T12:15:46Z"
+ },
+ {
+ "name": "Check static typing",
+ "conclusion": "failure",
+ "number": 15,
+ "started_at": "2026-06-18T12:15:46Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Save mypy cache",
+ "conclusion": "skipped",
+ "number": 16,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Check if \"schema.py\" is up to date",
+ "conclusion": "skipped",
+ "number": 17,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Check hogli manifest completeness",
+ "conclusion": "skipped",
+ "number": 18,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Run hogli framework tests",
+ "conclusion": "skipped",
+ "number": 19,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Run hogli extension tests",
+ "conclusion": "skipped",
+ "number": 20,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Run query-performance-ai tests",
+ "conclusion": "skipped",
+ "number": 21,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Upload test results",
+ "conclusion": "success",
+ "number": 22,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Run dependency detection script tests",
+ "conclusion": "skipped",
+ "number": 23,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Upload test results for dependency detection",
+ "conclusion": "success",
+ "number": 24,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Post Install uv",
+ "conclusion": "skipped",
+ "number": 46,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Post Set up Python",
+ "conclusion": "skipped",
+ "number": 47,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Post Run actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd",
+ "conclusion": "success",
+ "number": 48,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:26Z"
+ },
+ {
+ "name": "Complete job",
+ "conclusion": "success",
+ "number": 49,
+ "started_at": "2026-06-18T12:16:26Z",
+ "completed_at": "2026-06-18T12:16:27Z"
+ }
+ ]
+ },
+ {
+ "id": 82127375450,
+ "name": "Python code quality checks",
+ "conclusion": "failure",
+ "started_at": "2026-06-18T12:16:36Z",
+ "completed_at": "2026-06-18T12:16:39Z",
+ "steps": [
+ {
+ "name": "Set up job",
+ "conclusion": "success",
+ "number": 1,
+ "started_at": "2026-06-18T12:16:37Z",
+ "completed_at": "2026-06-18T12:16:37Z"
+ },
+ {
+ "name": "Check Python CI status",
+ "conclusion": "failure",
+ "number": 2,
+ "started_at": "2026-06-18T12:16:37Z",
+ "completed_at": "2026-06-18T12:16:37Z"
+ },
+ {
+ "name": "Complete job",
+ "conclusion": "success",
+ "number": 3,
+ "started_at": "2026-06-18T12:16:37Z",
+ "completed_at": "2026-06-18T12:16:37Z"
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/logs/pr-64532/analysis.json b/logs/pr-64532/analysis.json
new file mode 100644
index 000000000000..93df9eb1931d
--- /dev/null
+++ b/logs/pr-64532/analysis.json
@@ -0,0 +1,49 @@
+{
+ "analyzed_at": "2026-06-18T12:17:23.431888+00:00",
+ "pr_number": 64532,
+ "runs_analyzed": [
+ {
+ "run_id": "27758632672",
+ "run_number": 174877,
+ "head_sha": "6eee8d8d0bec909cb34102a8f9f637d44f39fe40",
+ "failed_jobs": 2,
+ "unique_errors": 2
+ }
+ ],
+ "error_timeline": [
+ {
+ "signature": "workflow::Python code quality (depot-ubuntu-latest)::Check static typing::failure",
+ "test_file": "Python code quality (depot-ubuntu-latest)",
+ "test_name": "Check static typing",
+ "error_type": "failure",
+ "message": "",
+ "first_seen_run": "27758632672",
+ "first_seen_sha": "6eee8d8d0bec909cb34102a8f9f637d44f39fe40",
+ "last_seen_run": "27758632672",
+ "last_seen_sha": "6eee8d8d0bec909cb34102a8f9f637d44f39fe40",
+ "status": "persistent",
+ "occurrences_by_run": {
+ "27758632672": 1
+ },
+ "likely_culprit_commit": "6eee8d8d0bec909cb34102a8f9f637d44f39fe40",
+ "likely_fix_commit": null
+ },
+ {
+ "signature": "workflow::Python code quality checks::Check Python CI status::failure",
+ "test_file": "Python code quality checks",
+ "test_name": "Check Python CI status",
+ "error_type": "failure",
+ "message": "",
+ "first_seen_run": "27758632672",
+ "first_seen_sha": "6eee8d8d0bec909cb34102a8f9f637d44f39fe40",
+ "last_seen_run": "27758632672",
+ "last_seen_sha": "6eee8d8d0bec909cb34102a8f9f637d44f39fe40",
+ "status": "persistent",
+ "occurrences_by_run": {
+ "27758632672": 1
+ },
+ "likely_culprit_commit": "6eee8d8d0bec909cb34102a8f9f637d44f39fe40",
+ "likely_fix_commit": null
+ }
+ ]
+}
\ No newline at end of file
diff --git a/posthog/admin/admins/data_deletion_request_admin.py b/posthog/admin/admins/data_deletion_request_admin.py
index 43bdffd834c1..538a6f1fd4e2 100644
--- a/posthog/admin/admins/data_deletion_request_admin.py
+++ b/posthog/admin/admins/data_deletion_request_admin.py
@@ -17,9 +17,10 @@ from posthog.models.data_deletion_request import (
ExecutionMode,
RequestStatus,
RequestType,
- compile_hogql_predicate,
+ cached_compile_hogql_predicate,
event_match_params,
event_match_sql_fragment,
+ invalidate_compiled_predicate_cache,
jsonhas_expr,
verify_queued_request,
)
@@ -213,7 +214,7 @@ class DataDeletionRequestForm(forms.ModelForm):
def _append_hogql_predicate(fragment: str, params: dict, obj) -> tuple[str, dict]:
"""Append the compiled HogQL predicate (if any) to ``fragment`` and merge params."""
- hogql_sql, hogql_values = compile_hogql_predicate(obj)
+ hogql_sql, hogql_values = cached_compile_hogql_predicate(obj)
if not hogql_sql:
return fragment, params
combined = f"{fragment} AND ({hogql_sql})".strip() if fragment else f"AND ({hogql_sql})"
@@ -552,6 +553,9 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):
readonly = super().get_readonly_fields(request, obj)
if self._is_locked(obj):
return tuple(readonly) + EDITABLE_FIELDS
+ if obj is not None:
+ # team_id is immutable once the request exists — a request belongs to one team.
+ return (*tuple(readonly), "team_id")
return readonly
def save_model(self, request, obj, form, change):
@@ -561,6 +565,8 @@ class DataDeletionRequestAdmin(admin.ModelAdmin):
elif form.changed_data and CRITERIA_FIELDS & set(form.changed_data):
obj.criteria_updated_by = request.user
obj.criteria_updated_at = timezone.now()
+ # Criteria changed — the cached compiled predicate (used by stats/preview) is stale.
+ invalidate_compiled_predicate_cache(obj.pk)
obj.count = None
obj.part_count = None
obj.parts_size = None
diff --git a/posthog/admin/test_data_deletion_request_admin.py b/posthog/admin/test_data_deletion_request_admin.py
index 4b8f2382589f..96994c27eb9e 100644
--- a/posthog/admin/test_data_deletion_request_admin.py
+++ b/posthog/admin/test_data_deletion_request_admin.py
@@ -554,8 +554,12 @@ class TestDataDeletionRequestAdminEditLock(BaseTest):
def test_editable_statuses_keep_fields_editable(self, _name, status):
obj = self._make_request(status)
readonly = self._readonly_fields(obj)
+ # team_id is immutable once the request exists, so it stays readonly even when editable.
for field in EDITABLE_FIELDS:
- self.assertNotIn(field, readonly)
+ if field == "team_id":
+ self.assertIn(field, readonly)
+ else:
+ self.assertNotIn(field, readonly)
def test_add_view_fields_editable(self):
readonly = self._readonly_fields(None)
diff --git a/posthog/models/data_deletion_request.py b/posthog/models/data_deletion_request.py
index 553334a98458..ce8a90e73529 100644
--- a/posthog/models/data_deletion_request.py
+++ b/posthog/models/data_deletion_request.py
@@ -1,6 +1,7 @@
from dataclasses import dataclass
from django.contrib.postgres.fields import ArrayField
+from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.db import models
from django.utils import timezone
@@ -105,6 +106,46 @@ def compile_hogql_predicate(obj) -> tuple[str, dict]:
return sql, dict(context.values)
+# Compiling a predicate builds the full HogQL schema graph, which is slow. The Django admin
+# recompiles it on every stats/preview render, so cache the result in the shared Django cache
+# (Redis). Keyed by request id and guarded by the predicate text it was compiled from, so a
+# changed predicate never serves a stale fragment even if explicit invalidation is missed. The
+# destructive Dagster deletion path deliberately calls ``compile_hogql_predicate`` directly
+# (never this) so the actual mutation is always built from a freshly compiled predicate.
+_COMPILED_PREDICATE_CACHE_PREFIX = "data_deletion:compiled_predicate:"
+_COMPILED_PREDICATE_CACHE_TTL = 60 * 60 * 24 # 1 day; admin-only, a brief staleness window is fine
+
+
+def _compiled_predicate_cache_key(request_id: object) -> str:
+ return f"{_COMPILED_PREDICATE_CACHE_PREFIX}{request_id}"
+
+
+def cached_compile_hogql_predicate(obj) -> tuple[str, dict]:
+ """Cache-backed ``compile_hogql_predicate`` for the Django admin's stats/preview rendering.
+
+ Only the informational admin path should use this. The Dagster deletion job compiles fresh via
+ ``compile_hogql_predicate`` so the mutation is never built from a stale fragment.
+ """
+ predicate = (getattr(obj, "hogql_predicate", "") or "").strip()
+ if not predicate:
+ return "", {}
+ request_id = getattr(obj, "pk", None) or getattr(obj, "request_id", None)
+ if request_id is None:
+ return compile_hogql_predicate(obj)
+ key = _compiled_predicate_cache_key(request_id)
+ cached = cache.get(key)
+ if cached is not None and cached.get("source") == predicate:
+ return cached["sql"], cached["params"]
+ sql, params = compile_hogql_predicate(obj)
+ cache.set(key, {"source": predicate, "sql": sql, "params": params}, _COMPILED_PREDICATE_CACHE_TTL)
+ return sql, params
+
+
+def invalidate_compiled_predicate_cache(request_id: object) -> None:
+ """Drop the cached compiled predicate. Called when a request's deletion criteria change."""
+ cache.delete(_compiled_predicate_cache_key(request_id))
+
+
def event_match_sql_fragment(obj) -> str:
"""WHERE fragment that narrows to the matching event names.
@@ -325,14 +366,26 @@ class DataDeletionRequest(UUIDModel):
help_text="When execution was most recently attempted (updated on every APPROVED → IN_PROGRESS transition).",
)
+ # The team_id this request was loaded from the DB with (None until loaded). Set by from_db so
+ # clean() can reject retargeting an existing request at a different team. Not a model field.
+ _loaded_team_id: int | None = None
+
class Meta:
ordering = ["-created_at"]
def __str__(self) -> str:
return f"DataDeletionRequest({self.request_type}, team={self.team_id}, status={self.status})"
+ @classmethod
+ def from_db(cls, db, field_names, values):
+ instance = super().from_db(db, field_names, values)
+ instance._loaded_team_id = instance.team_id
+ return instance
+
def clean(self) -> None:
super().clean()
+ if self._loaded_team_id is not None and self.team_id != self._loaded_team_id:
+ raise ValidationError({"team_id": "team_id cannot be changed after the request is created."})
if self.request_type == RequestType.EVENT_REMOVAL:
self._clean_event_removal()
elif self.request_type == RequestType.PROPERTY_REMOVAL:
diff --git a/posthog/models/test/test_data_deletion_request.py b/posthog/models/test/test_data_deletion_request.py
index d3f446d9a173..03da1be2f901 100644
--- a/posthog/models/test/test_data_deletion_request.py
+++ b/posthog/models/test/test_data_deletion_request.py
@@ -1,15 +1,26 @@
import uuid as uuid_lib
+from collections.abc import Callable
from datetime import datetime, timedelta
import pytest
from freezegun import freeze_time
+from unittest.mock import patch
from django.core.exceptions import ValidationError
-
-from posthog.models.data_deletion_request import DataDeletionRequest, RequestType
+from django.test import override_settings
+
+from posthog.models import data_deletion_request as ddr
+from posthog.models.data_deletion_request import (
+ DataDeletionRequest,
+ RequestType,
+ cached_compile_hogql_predicate,
+ invalidate_compiled_predicate_cache,
+)
from posthog.models.organization import Organization
from posthog.models.team import Team
+LOCMEM_CACHE = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache", "LOCATION": "ddr-test"}}
+
TEAM_ID = 99999
@@ -30,6 +41,16 @@ def _base_kwargs(**overrides) -> dict:
return kwargs
+def _recording_compile() -> tuple[list[str], Callable]:
+ calls: list[str] = []
+
+ def fake_compile(obj):
+ calls.append(obj.hogql_predicate)
+ return "equals(1, 1)", {"k": "v"}
+
+ return calls, fake_compile
+
+
@pytest.mark.parametrize(
"events,delete_all_events,match",
[
@@ -426,3 +447,78 @@ def test_event_and_property_removal_rejects_person_fields(request_type, override
request = DataDeletionRequest(**kwargs)
with pytest.raises(ValidationError, match=match):
request.clean()
+
+
+def test_team_id_immutable_after_creation():
+ request = DataDeletionRequest(**_base_kwargs(events=["$pageview"]))
+ request._loaded_team_id = request.team_id # simulate a row loaded from the DB
+ request.team_id = TEAM_ID + 1
+ with pytest.raises(ValidationError, match="team_id cannot be changed"):
+ request.clean()
+
+
+def test_team_id_unchanged_allows_other_edits():
+ request = DataDeletionRequest(**_base_kwargs(events=["$pageview"]))
+ request._loaded_team_id = request.team_id
+ request.events = ["$pageview", "$autocapture"]
+ request.clean() # team_id unchanged → no raise
+
+
+@override_settings(CACHES=LOCMEM_CACHE)
+def test_cached_compile_hogql_predicate_reuses_cache_on_repeat():
+ from django.core.cache import cache
+
+ cache.clear()
+ request = DataDeletionRequest(
+ **_base_kwargs(events=["$pageview"], hogql_predicate="properties.$browser = 'Chrome'")
+ )
+ calls, fake_compile = _recording_compile()
+
+ with patch.object(ddr, "compile_hogql_predicate", side_effect=fake_compile):
+ assert cached_compile_hogql_predicate(request) == ("equals(1, 1)", {"k": "v"})
+ # Second call for the same predicate is served from cache — no recompile.
+ assert cached_compile_hogql_predicate(request) == ("equals(1, 1)", {"k": "v"})
+ assert len(calls) == 1
+
+
+@override_settings(CACHES=LOCMEM_CACHE)
+def test_cached_compile_hogql_predicate_recompiles_when_predicate_text_changes():
+ from django.core.cache import cache
+
+ cache.clear()
+ request = DataDeletionRequest(
+ **_base_kwargs(events=["$pageview"], hogql_predicate="properties.$browser = 'Chrome'")
+ )
+ calls, fake_compile = _recording_compile()
+
+ with patch.object(ddr, "compile_hogql_predicate", side_effect=fake_compile):
+ cached_compile_hogql_predicate(request)
+ # Changing the predicate text recompiles via the source guard, even without explicit clear.
+ request.hogql_predicate = "properties.$browser = 'Firefox'"
+ cached_compile_hogql_predicate(request)
+ assert len(calls) == 2
+
+
+@override_settings(CACHES=LOCMEM_CACHE)
+def test_cached_compile_hogql_predicate_recompiles_after_explicit_invalidation():
+ from django.core.cache import cache
+
+ cache.clear()
+ request = DataDeletionRequest(
+ **_base_kwargs(events=["$pageview"], hogql_predicate="properties.$browser = 'Chrome'")
+ )
+ calls, fake_compile = _recording_compile()
+
+ with patch.object(ddr, "compile_hogql_predicate", side_effect=fake_compile):
+ cached_compile_hogql_predicate(request)
+ # Explicit invalidation forces a recompile on the next call.
+ invalidate_compiled_predicate_cache(request.pk)
+ cached_compile_hogql_predicate(request)
+ assert len(calls) == 2
+
+
+@override_settings(CACHES=LOCMEM_CACHE)
+def test_cached_compile_hogql_predicate_blank_predicate_skips_compile():
+ request = DataDeletionRequest(**_base_kwargs(events=["$pageview"], hogql_predicate=""))
+ with patch.object(ddr, "compile_hogql_predicate", side_effect=AssertionError("should not compile")):
+ assert cached_compile_hogql_predicate(request) == ("", {})