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(query): drop the http-level query coalescer (#100667)

Andy Zhao965aec0c5e29
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 4891b4847d55..419f6764b989 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -41,7 +41,6 @@ from posthog.api.monitoring import (
Feature as MonitoringFeature,
monitor,
)
-from posthog.api.query_coalescer import QueryCoalescingMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.services.query import process_query_model
from posthog.api.streaming import sse_streaming_response
@@ -208,7 +207,7 @@ def required_scopes_for_query_payload(query: object) -> list[str] | None:
return None
-class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
+class QueryViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
# NOTE: Do we need to override the scopes for the "create"
scope_object = "query"
serializer_class = _FallbackSerializer
diff --git a/posthog/api/query_coalescer.py b/posthog/api/query_coalescer.py
deleted file mode 100644
index 1d38085da668..000000000000
--- a/posthog/api/query_coalescer.py
+++ /dev/null
@@ -1,438 +0,0 @@
-import re
-import time
-import uuid
-import hashlib
-import threading
-from enum import StrEnum
-from typing import TYPE_CHECKING, Optional
-from urllib.parse import parse_qs, urlencode
-
-from django.http import HttpRequest, HttpResponse
-
-import orjson
-import structlog
-import posthoganalytics
-from prometheus_client import Counter, Histogram
-from redis.exceptions import RedisError
-from rest_framework.exceptions import Throttled
-
-from posthog import (
- redis as posthog_redis,
- settings,
-)
-
-logger = structlog.get_logger(__name__)
-
-LOCK_KEY_PREFIX = "http_qc"
-DONE_KEY_PREFIX = "http_qc_done"
-ERROR_KEY_PREFIX = "http_qc_err"
-CHANNEL_PREFIX = "http_qc_ch"
-LOCK_TTL_SECONDS = 60
-POLL_INTERVAL_SECONDS = 0.2
-HEARTBEAT_INTERVAL_SECONDS = 5
-# Keep short: followers poll done_key/error_key every POLL_INTERVAL as a
-# fallback for missed pub/sub signals. A long TTL lets a NEW round's
-# followers read a stale result from the PREVIOUS round (same query, but
-# possibly outdated for force_blocking requests).
-DONE_TTL_SECONDS = 5
-ERROR_TTL_SECONDS = 5
-
-_RELEASE_LOCK_SCRIPT = """
-if redis.call("get", KEYS[1]) == ARGV[1] then
- return redis.call("del", KEYS[1])
-end
-return 0
-"""
-
-_EXTEND_LOCK_SCRIPT = """
-if redis.call("get", KEYS[1]) == ARGV[1] then
- return redis.call("expire", KEYS[1], ARGV[2])
-end
-return 0
-"""
-
-query_coalesce_counter = Counter(
- "posthog_query_coalesce_total",
- "Query coalescing outcomes",
- labelnames=["outcome"],
-)
-
-query_coalesce_wait_histogram = Histogram(
- "posthog_query_coalesce_wait_seconds",
- "Time followers spent waiting for leader result",
- buckets=[0.1, 0.5, 1, 2, 5, 10, 20, 30, 60],
-)
-
-
-class CoalesceSignal(StrEnum):
- DONE = "done"
- ERROR = "error"
- TIMEOUT = "timeout"
- CRASHED = "crashed"
-
-
-class _Heartbeat:
- def __init__(self, redis, lock_key: str, lock_value: str, channel_key: str):
- self._stop = threading.Event()
- self._thread = threading.Thread(target=self._run, args=(redis, lock_key, lock_value, channel_key), daemon=True)
- self._thread.start()
-
- def _run(self, redis, lock_key: str, lock_value: str, channel_key: str) -> None:
- while not self._stop.wait(HEARTBEAT_INTERVAL_SECONDS):
- try:
- redis.eval(_EXTEND_LOCK_SCRIPT, 1, lock_key, lock_value, LOCK_TTL_SECONDS)
- redis.publish(channel_key, "heartbeat")
- except RedisError:
- break
-
- def stop(self) -> None:
- self._stop.set()
- self._thread.join(timeout=2)
-
-
-class QueryCoalescer:
- """Query coalescer.
-
- One request (leader) acquires a Redis lock and executes the query.
- Concurrent requests (followers) subscribe to a pub/sub channel and wait
- for the leader to signal done/error, or detect a crash via lock disappearing.
- """
-
- def __init__(self, coalescing_key: str, *, dry_run: bool = False):
- self.coalescing_key = coalescing_key
- self._dry_run = dry_run
- self._lock_value: str = uuid.uuid4().hex
- self._is_leader: bool = False
- self._heartbeat: Optional[_Heartbeat] = None
- self._redis = posthog_redis.get_client()
-
- @property
- def is_leader(self) -> bool:
- return self._is_leader
-
- @property
- def _lock_key(self) -> str:
- return f"{LOCK_KEY_PREFIX}:{self.coalescing_key}"
-
- @property
- def _done_key(self) -> str:
- return f"{DONE_KEY_PREFIX}:{self.coalescing_key}"
-
- @property
- def _error_key(self) -> str:
- return f"{ERROR_KEY_PREFIX}:{self.coalescing_key}"
-
- @property
- def _channel_key(self) -> str:
- return f"{CHANNEL_PREFIX}:{self.coalescing_key}"
-
- def try_acquire(self) -> bool:
- """Attempt to become leader. Returns True if acquired, starts heartbeat."""
- acquired = self._redis.set(self._lock_key, self._lock_value, nx=True, ex=LOCK_TTL_SECONDS)
- self._is_leader = bool(acquired)
- if self._is_leader:
- self._heartbeat = _Heartbeat(self._redis, self._lock_key, self._lock_value, self._channel_key)
- query_coalesce_counter.labels(outcome="leader").inc()
- elif self._dry_run:
- query_coalesce_counter.labels(outcome="follower_dry_run").inc()
- else:
- query_coalesce_counter.labels(outcome="follower").inc()
- return self._is_leader
-
- def wait_for_signal(self, max_wait: float) -> CoalesceSignal:
- """Block until leader signals completion.
-
- Subscribes to a Redis pub/sub channel. The leader publishes
- done/error for instant wake-up and heartbeats for liveness.
- If no message arrives within 2 heartbeat intervals the leader
- is assumed crashed.
- """
- start = time.monotonic()
- last_message = start
- crash_timeout = 2 * HEARTBEAT_INTERVAL_SECONDS
- pubsub = self._redis.pubsub(ignore_subscribe_messages=True)
- pubsub.subscribe(self._channel_key)
-
- try:
- while (time.monotonic() - start) < max_wait:
- if self._redis.get(self._done_key):
- query_coalesce_wait_histogram.observe(time.monotonic() - start)
- query_coalesce_counter.labels(outcome="follower_done").inc()
- return CoalesceSignal.DONE
-
- if self._redis.get(self._error_key):
- query_coalesce_wait_histogram.observe(time.monotonic() - start)
- query_coalesce_counter.labels(outcome="follower_error").inc()
- return CoalesceSignal.ERROR
-
- # If we haven't received a heartbeat in some time, then the leader crashed.
- if (time.monotonic() - last_message) > crash_timeout:
- query_coalesce_counter.labels(outcome="follower_crashed").inc()
- return CoalesceSignal.CRASHED
-
- if pubsub.get_message(timeout=POLL_INTERVAL_SECONDS) is not None:
- last_message = time.monotonic()
-
- query_coalesce_counter.labels(outcome="follower_timeout").inc()
- return CoalesceSignal.TIMEOUT
- finally:
- try:
- pubsub.unsubscribe()
- pubsub.close()
- except Exception:
- pass
-
- def get_error_response(self) -> Optional[dict]:
- """Read stored HTTP error response. Returns {"status": int, "body": str} or None."""
- try:
- value = self._redis.get(self._error_key)
- if value is None:
- return None
- return orjson.loads(value)
- except (RedisError, orjson.JSONDecodeError):
- return None
-
- def store_success_response(self, status_code: int, content: bytes, content_type: str) -> None:
- """Store full HTTP success response for followers to replay."""
- try:
- payload = orjson.dumps(
- {
- "status": status_code,
- "body": content.decode("utf-8") if isinstance(content, bytes) else content,
- "content_type": content_type,
- }
- )
- self._redis.set(self._done_key, payload, ex=DONE_TTL_SECONDS)
- self._redis.publish(self._channel_key, CoalesceSignal.DONE)
- except RedisError:
- pass
-
- def get_success_response(self) -> Optional[dict]:
- """Read stored HTTP success response. Returns {"status": int, "body": str, "content_type": str} or None."""
- try:
- value = self._redis.get(self._done_key)
- if value is None:
- return None
- parsed = orjson.loads(value)
- if isinstance(parsed, dict) and "status" in parsed:
- return parsed
- return None
- except (RedisError, orjson.JSONDecodeError) as e:
- logger.warning(
- "query_coalescing_get_success_response_error", error=str(e), coalescing_key=self.coalescing_key
- )
- return None
-
- def store_error_response(self, status_code: int, content: bytes) -> None:
- """Store HTTP error response for followers to replay."""
- try:
- payload = orjson.dumps(
- {
- "status": status_code,
- "body": content.decode("utf-8") if isinstance(content, bytes) else content,
- }
- )
- self._redis.set(self._error_key, payload, ex=ERROR_TTL_SECONDS)
- self._redis.publish(self._channel_key, CoalesceSignal.ERROR)
- except RedisError:
- pass
-
- def signal_error(self) -> None:
- """Signal followers that the leader encountered an error.
-
- Stores a minimal error marker in Redis and publishes ERROR.
- The marker is needed so late-subscribing followers can detect the
- error via polling. Without it they receive no signal at all and
- hit the crash timeout.
- """
- try:
- self._redis.set(self._error_key, b'{"error": true}', ex=ERROR_TTL_SECONDS)
- self._redis.publish(self._channel_key, CoalesceSignal.ERROR)
- except RedisError:
- pass
-
- def cleanup(self) -> None:
- """Stop heartbeat and release lock. Call in finally block."""
- if self._heartbeat:
- self._heartbeat.stop()
- self._heartbeat = None
- if self._is_leader and self._lock_value:
- try:
- self._redis.eval(_RELEASE_LOCK_SCRIPT, 1, self._lock_key, self._lock_value)
- except RedisError:
- pass
-
-
-_TEAM_ID_RE = re.compile(r"^/api/(?:environments|projects)/(\d+)/")
-
-_COALESCE_PATH_PATTERNS = [
- re.compile(r"^/api/(?:environments|projects)/\d+/query/$"),
- re.compile(r"^/api/(?:environments|projects)/\d+/insights/\d+/$"),
-]
-
-
-class QueryCoalescingMiddleware:
- """Coalesce concurrent identical query requests.
-
- For matched endpoints, only one request (leader) executes while
- concurrent identical requests (followers) wait and get the same response.
- """
-
- def __init__(self, get_response):
- self.get_response = get_response
-
- def __call__(self, request: HttpRequest) -> HttpResponse:
- if request.method not in ("GET", "POST"):
- return self.get_response(request)
-
- if not any(p.match(request.path) for p in _COALESCE_PATH_PATTERNS):
- return self.get_response(request)
-
- team_id = self._extract_team_id(request.path)
- if not team_id:
- return self.get_response(request)
-
- enabled = posthoganalytics.feature_enabled("http-query-coalescing", str(team_id))
-
- key = self._compute_key(team_id, request)
- coalescer = QueryCoalescer(key, dry_run=not enabled)
-
- try:
- is_leader = coalescer.try_acquire()
- except RedisError:
- logger.warning("query_coalescing_middleware_redis_error", msg="redis unavailable, skipping coalescing")
- return self.get_response(request)
-
- if is_leader:
- return self._handle_leader(request, coalescer)
-
- if not enabled:
- return self.get_response(request)
-
- return self._handle_follower(request, coalescer)
-
- def _handle_leader(self, request: HttpRequest, coalescer: QueryCoalescer) -> HttpResponse:
- log = logger.bind(coalescing_key=coalescer.coalescing_key)
- try:
- response = self.get_response(request)
- # Force render DRF responses so we can capture the body
- if hasattr(response, "render") and callable(response.render):
- response.render()
- content_type = response.get("Content-Type", "application/json")
- if response.status_code < 400 or response.status_code >= 500:
- # Coalesce successes (2xx) and server errors (5xx).
- # 4xx are user-specific (permissions, validation) and must not be shared.
- coalescer.store_success_response(response.status_code, response.content, content_type)
- else:
- log.warning(
- "query_coalescing_middleware_leader_error",
- status_code=response.status_code,
- path=request.path,
- )
- coalescer.signal_error()
- return response
- except Exception as e:
- log.warning("query_coalescing_middleware_leader_exception", path=request.path, error=str(e))
- coalescer.signal_error()
- raise
- finally:
- coalescer.cleanup()
-
- def _handle_follower(self, request: HttpRequest, coalescer: QueryCoalescer) -> HttpResponse:
- log = logger.bind(coalescing_key=coalescer.coalescing_key)
- log.info("query_coalescing_middleware_follower_waiting")
-
- signal = coalescer.wait_for_signal(max_wait=settings.QUERY_COALESCING_MAX_WAIT_SECONDS)
-
- if signal == CoalesceSignal.DONE:
- data = coalescer.get_success_response()
- if data:
- log.info("query_coalescing_middleware_follower_done")
- # Attach cached response for the view mixin to gate behind permissions
- request.META["_coalesced_response"] = data
- return self.get_response(request)
- log.warning("query_coalescing_middleware_follower_done_read_failed")
-
- if signal == CoalesceSignal.ERROR:
- log.info("query_coalescing_middleware_follower_error")
- elif signal == CoalesceSignal.TIMEOUT:
- log.warning("query_coalescing_middleware_follower_timeout")
- elif signal == CoalesceSignal.CRASHED:
- log.warning("query_coalescing_middleware_follower_crashed")
-
- # Fall through: execute the request normally
- log.info("query_coalescing_middleware_follower_fallthrough", signal=signal)
- return self.get_response(request)
-
- @staticmethod
- def _extract_team_id(path: str) -> int | None:
- match = _TEAM_ID_RE.match(path)
- if not match:
- return None
- return int(match.group(1))
-
- # Fields that are unique per request and should not affect coalescing
- _IGNORED_KEY_FIELDS = {"client_query_id", "session_id"}
-
- @staticmethod
- def _compute_key(team_id: int, request: HttpRequest) -> str:
- if request.method == "GET":
- params = parse_qs(request.META.get("QUERY_STRING", ""))
- for field in QueryCoalescingMiddleware._IGNORED_KEY_FIELDS:
- params.pop(field, None)
- normalized = urlencode(sorted(params.items()), doseq=True).encode()
- else:
- try:
- data = orjson.loads(request.body)
- if isinstance(data, dict):
- for field in QueryCoalescingMiddleware._IGNORED_KEY_FIELDS:
- data.pop(field, None)
- normalized = orjson.dumps(data, option=orjson.OPT_SORT_KEYS)
- except ValueError:
- normalized = request.body
-
- raw = f"{team_id}:{request.method}:{request.path}:{normalized.decode()}"
- return hashlib.sha256(raw.encode()).hexdigest()
-
-
-if TYPE_CHECKING:
- from rest_framework.views import APIView
-
- _MixinBase = APIView
-else:
- _MixinBase = object
-
-
-class QueryCoalescingMixin(_MixinBase):
- """DRF ViewSet mixin that gates coalesced responses behind permission checks.
-
- The QueryCoalescingMiddleware attaches cached response data to
- request.META["_coalesced_response"] for followers. This mixin runs DRF's
- initial() (auth + permissions + throttling) before returning the
- cached response, ensuring the request is authorized.
- """
-
- def dispatch(self, request, *args, **kwargs):
- coalesced = request.META.get("_coalesced_response")
- if coalesced is None:
- return super().dispatch(request, *args, **kwargs)
-
- self.args = args
- self.kwargs = kwargs
- self.headers = self.default_response_headers
- request = self.initialize_request(request, *args, **kwargs)
- self.request = request
- try:
- self.initial(request, *args, **kwargs)
- except Throttled:
- pass # Serving cached response, no backend load — safe to skip throttle
- except Exception as exc:
- response = self.handle_exception(exc)
- self.response = self.finalize_response(request, response, *args, **kwargs)
- return self.response
-
- return HttpResponse(
- coalesced["body"],
- status=coalesced["status"],
- content_type=coalesced.get("content_type", "application/json"),
- )
diff --git a/posthog/api/routing.py b/posthog/api/routing.py
index 5456cea98c3d..f89e9c5384e0 100644
--- a/posthog/api/routing.py
+++ b/posthog/api/routing.py
@@ -175,8 +175,7 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
calling super() would otherwise leak the token.
Note: a subclass that overrides `dispatch` itself without super() would
- also bypass this cleanup; in this codebase only `query_coalescer.py`
- overrides dispatch and it does call super().
+ also bypass this cleanup.
ContextVars in sync Django are thread-local and the same worker thread
is reused across requests, so a leaked token would let scope from one
diff --git a/posthog/api/test/test_query_coalescing.py b/posthog/api/test/test_query_coalescing.py
deleted file mode 100644
index fef56970f235..000000000000
--- a/posthog/api/test/test_query_coalescing.py
+++ /dev/null
@@ -1,494 +0,0 @@
-import time
-import threading
-from typing import Any
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
-from unittest import mock
-
-from django.test import TestCase
-
-from parameterized import parameterized
-from redis.exceptions import RedisError
-from rest_framework.exceptions import PermissionDenied, Throttled
-
-from posthog import redis as posthog_redis
-from posthog.api.query_coalescer import (
- DONE_KEY_PREFIX,
- ERROR_KEY_PREFIX,
- LOCK_KEY_PREFIX,
- CoalesceSignal,
- QueryCoalescer,
- query_coalesce_counter,
-)
-
-
-class TestQueryCoalescer(TestCase):
- def setUp(self):
- self.redis = posthog_redis.get_client()
- self.key = f"test_{id(self)}_{time.monotonic_ns()}"
-
- def tearDown(self):
- self.redis.delete(f"{LOCK_KEY_PREFIX}:{self.key}")
- self.redis.delete(f"{DONE_KEY_PREFIX}:{self.key}")
- self.redis.delete(f"{ERROR_KEY_PREFIX}:{self.key}")
-
- def _set_lock(self, value="leader"):
- self.redis.set(f"{LOCK_KEY_PREFIX}:{self.key}", value, ex=60)
-
- def _lock_exists(self) -> bool:
- return self.redis.get(f"{LOCK_KEY_PREFIX}:{self.key}") is not None
-
- # -- Lock lifecycle --
-
- def test_acquire_succeeds_when_no_lock(self):
- coalescer = QueryCoalescer(self.key)
- self.assertTrue(coalescer.try_acquire())
- self.assertTrue(coalescer.is_leader)
- self.assertTrue(self._lock_exists())
- coalescer.cleanup()
-
- def test_acquire_fails_when_lock_held(self):
- self._set_lock("other")
- coalescer = QueryCoalescer(self.key)
- self.assertFalse(coalescer.try_acquire())
- self.assertFalse(coalescer.is_leader)
-
- def test_cleanup_releases_lock(self):
- coalescer = QueryCoalescer(self.key)
- coalescer.try_acquire()
- coalescer.cleanup()
- self.assertFalse(self._lock_exists())
-
- def test_cleanup_preserves_other_leaders_lock(self):
- old = QueryCoalescer(self.key)
- old.try_acquire()
- # Simulate old lock expired, new leader acquired
- self.redis.delete(f"{LOCK_KEY_PREFIX}:{self.key}")
- new = QueryCoalescer(self.key)
- new.try_acquire()
- old.cleanup()
- self.assertTrue(self._lock_exists())
- new.cleanup()
-
- # -- Store / retrieve --
-
- def test_store_and_get_error_response(self):
- coalescer = QueryCoalescer(self.key)
- coalescer.try_acquire()
- coalescer.store_error_response(400, b'{"detail":"bad request"}')
- result = coalescer.get_error_response()
- assert result is not None
- self.assertEqual(result["status"], 400)
- self.assertEqual(result["body"], '{"detail":"bad request"}')
- coalescer.cleanup()
-
- def test_get_error_response_returns_none_when_missing(self):
- coalescer = QueryCoalescer(self.key)
- self.assertIsNone(coalescer.get_error_response())
-
- def test_store_and_get_success_response(self):
- coalescer = QueryCoalescer(self.key)
- coalescer.try_acquire()
- coalescer.store_success_response(200, b'{"results": [1, 2, 3]}', "application/json")
- result = coalescer.get_success_response()
- assert result is not None
- self.assertEqual(result["status"], 200)
- self.assertEqual(result["body"], '{"results": [1, 2, 3]}')
- self.assertEqual(result["content_type"], "application/json")
- coalescer.cleanup()
-
- def test_get_success_response_returns_none_when_missing(self):
- coalescer = QueryCoalescer(self.key)
- self.assertIsNone(coalescer.get_success_response())
-
- # -- Concurrent leader + follower --
-
- def test_concurrent_leader_and_follower(self):
- results: dict[str, Any] = {}
- barrier = threading.Barrier(2, timeout=5)
-
- follower_polling = threading.Event()
-
- def run_leader():
- c = QueryCoalescer(self.key)
- acquired = c.try_acquire()
- results["leader_acquired"] = acquired
- barrier.wait()
- follower_polling.wait(timeout=5)
- c.store_success_response(200, b'{"ok": true}', "application/json")
- c.cleanup()
-
- def run_follower():
- barrier.wait()
- c = QueryCoalescer(self.key)
- acquired = c.try_acquire()
- results["follower_acquired"] = acquired
- follower_polling.set()
- signal = c.wait_for_signal(max_wait=5)
- results["follower_signal"] = signal
-
- leader_thread = threading.Thread(target=run_leader)
- follower_thread = threading.Thread(target=run_follower)
- leader_thread.start()
- follower_thread.start()
- leader_thread.join(timeout=10)
- follower_thread.join(timeout=10)
-
- self.assertTrue(results["leader_acquired"])
- self.assertFalse(results["follower_acquired"])
- self.assertEqual(results["follower_signal"], CoalesceSignal.DONE)
-
- def test_concurrent_leader_error_and_follower(self):
- results: dict[str, Any] = {}
- barrier = threading.Barrier(2, timeout=5)
- follower_polling = threading.Event()
-
- def run_leader():
- c = QueryCoalescer(self.key)
- c.try_acquire()
- barrier.wait()
- follower_polling.wait(timeout=5)
- c.store_error_response(500, b'{"detail":"server error"}')
- c.cleanup()
-
- def run_follower():
- barrier.wait()
- c = QueryCoalescer(self.key)
- c.try_acquire()
- follower_polling.set()
- signal = c.wait_for_signal(max_wait=5)
- results["signal"] = signal
- if signal == CoalesceSignal.ERROR:
- results["error_data"] = c.get_error_response()
-
- leader_thread = threading.Thread(target=run_leader)
- follower_thread = threading.Thread(target=run_follower)
- leader_thread.start()
- follower_thread.start()
- leader_thread.join(timeout=10)
- follower_thread.join(timeout=10)
-
- self.assertEqual(results["signal"], CoalesceSignal.ERROR)
- self.assertEqual(results["error_data"]["status"], 500)
- self.assertEqual(results["error_data"]["body"], '{"detail":"server error"}')
-
- # -- Metrics --
-
- def test_leader_increments_counter(self):
- from posthog.api.query_coalescer import query_coalesce_counter
-
- before = query_coalesce_counter.labels(outcome="leader")._value.get()
- coalescer = QueryCoalescer(self.key)
- coalescer.try_acquire()
- after = query_coalesce_counter.labels(outcome="leader")._value.get()
- self.assertEqual(after, before + 1)
- coalescer.cleanup()
-
- def test_follower_increments_counter(self):
- from posthog.api.query_coalescer import query_coalesce_counter
-
- self._set_lock()
- before = query_coalesce_counter.labels(outcome="follower")._value.get()
- coalescer = QueryCoalescer(self.key)
- coalescer.try_acquire()
- after = query_coalesce_counter.labels(outcome="follower")._value.get()
- self.assertEqual(after, before + 1)
-
- def test_dry_run_follower_increments_counter(self):
- self._set_lock()
- before = query_coalesce_counter.labels(outcome="follower_dry_run")._value.get()
- coalescer = QueryCoalescer(self.key, dry_run=True)
- self.assertFalse(coalescer.try_acquire())
- after = query_coalesce_counter.labels(outcome="follower_dry_run")._value.get()
- self.assertEqual(after, before + 1)
-
- def test_new_leader_preserves_done_key_from_previous_round(self):
- """A new leader acquiring the lock must not delete the
- done_key stored by the previous leader, otherwise followers of the
- previous round will see no data."""
- leader_a = QueryCoalescer(self.key)
- leader_a.try_acquire()
- leader_a.store_success_response(200, b'{"ok": true}', "application/json")
- leader_a.cleanup()
-
- # Leader B acquires the same key (simulates a new identical request)
- leader_b = QueryCoalescer(self.key)
- leader_b.try_acquire()
-
- # A lingering follower from round A should still be able to read the done_key
- follower_a = QueryCoalescer(self.key)
- result = follower_a.get_success_response()
- assert result is not None, "done_key was deleted by new leader"
- self.assertEqual(result["status"], 200)
- leader_b.cleanup()
-
- def test_signal_error_stores_error_key_for_polling(self):
- """signal_error() must store an error marker in Redis so that
- late-subscribing followers can detect it via polling instead of
- hitting the crash timeout."""
- leader = QueryCoalescer(self.key)
- leader.try_acquire()
- leader.signal_error()
- leader.cleanup()
-
- follower = QueryCoalescer(self.key)
- error_value = self.redis.get(f"{ERROR_KEY_PREFIX}:{self.key}")
- assert error_value is not None, "signal_error did not store error_key"
- self.assertIsNone(follower.get_success_response())
-
- # -- Redis failure --
-
- def test_redis_failure_on_acquire_raises(self):
- coalescer = QueryCoalescer(self.key)
- with mock.patch.object(coalescer._redis, "set", side_effect=RedisError("down")):
- with self.assertRaises(RedisError):
- coalescer.try_acquire()
-
-
-class TestQueryCoalescingMiddleware(ClickhouseTestMixin, APIBaseTest):
- def _query_url(self):
- return f"/api/environments/{self.team.id}/query/"
-
- def _query_payload(self):
- return {"query": {"kind": "EventsQuery", "select": ["event"]}}
-
- def test_leader_executes_and_stores_response(self):
- _create_event(team=self.team, event="test_event", distinct_id="user1")
- flush_persons_and_events()
-
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = True
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- self.assertEqual(response.status_code, 200)
- mock_coalescer.store_success_response.assert_called_once()
- mock_coalescer.cleanup.assert_called_once()
-
- def test_leader_signals_error_on_4xx(self):
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = True
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- ):
- response = self.client.post(
- self._query_url(),
- {"query": {"kind": "EventsQuery", "select": ["nonexistent_column_xyz"]}},
- )
-
- self.assertGreaterEqual(response.status_code, 400)
- self.assertLess(response.status_code, 500)
- # 4xx should signal error without storing response
- mock_coalescer.signal_error.assert_called_once()
- mock_coalescer.store_success_response.assert_not_called()
- mock_coalescer.cleanup.assert_called_once()
-
- def test_dry_run_follower_executes_normally(self):
- _create_event(team=self.team, event="test_event", distinct_id="user1")
- flush_persons_and_events()
-
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = False
- mock_coalescer._dry_run = True
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=False),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- self.assertEqual(response.status_code, 200)
- events = [row[0] for row in response.json()["results"]]
- self.assertIn("test_event", events)
- mock_coalescer.wait_for_signal.assert_not_called()
-
- def test_follower_gets_replayed_success_response(self):
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = False
- mock_coalescer._dry_run = False
- mock_coalescer.wait_for_signal.return_value = CoalesceSignal.DONE
- mock_coalescer.get_success_response.return_value = {
- "status": 200,
- "body": '{"results": [["test_event"]], "is_cached": true}',
- "content_type": "application/json",
- }
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- self.assertEqual(response.status_code, 200)
- self.assertIn("test_event", response.json()["results"][0][0])
-
- def test_follower_falls_through_on_error_signal(self):
- _create_event(team=self.team, event="test_event", distinct_id="user1")
- flush_persons_and_events()
-
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = False
- mock_coalescer._dry_run = False
- mock_coalescer.wait_for_signal.return_value = CoalesceSignal.ERROR
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- # Follower executes independently on ERROR signal (leader had 4xx)
- self.assertEqual(response.status_code, 200)
- events = [row[0] for row in response.json()["results"]]
- self.assertIn("test_event", events)
-
- def test_follower_falls_through_on_timeout(self):
- _create_event(team=self.team, event="test_event", distinct_id="user1")
- flush_persons_and_events()
-
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = False
- mock_coalescer._dry_run = False
- mock_coalescer.wait_for_signal.return_value = CoalesceSignal.TIMEOUT
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- self.assertEqual(response.status_code, 200)
- events = [row[0] for row in response.json()["results"]]
- self.assertIn("test_event", events)
-
- def test_follower_falls_through_on_crash(self):
- _create_event(team=self.team, event="test_event", distinct_id="user1")
- flush_persons_and_events()
-
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = False
- mock_coalescer._dry_run = False
- mock_coalescer.wait_for_signal.return_value = CoalesceSignal.CRASHED
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- self.assertEqual(response.status_code, 200)
- events = [row[0] for row in response.json()["results"]]
- self.assertIn("test_event", events)
-
- def test_redis_failure_falls_through(self):
- _create_event(team=self.team, event="test_event", distinct_id="user1")
- flush_persons_and_events()
-
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.side_effect = RedisError("down")
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- self.assertEqual(response.status_code, 200)
- events = [row[0] for row in response.json()["results"]]
- self.assertIn("test_event", events)
-
- def test_non_matching_path_skips_coalescing(self):
- with mock.patch("posthog.api.query_coalescer.QueryCoalescer") as mock_cls:
- self.client.get(f"/api/environments/{self.team.id}/annotations/")
- mock_cls.assert_not_called()
-
- def test_follower_gets_replayed_5xx_response(self):
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = False
- mock_coalescer._dry_run = False
- mock_coalescer.wait_for_signal.return_value = CoalesceSignal.DONE
- mock_coalescer.get_success_response.return_value = {
- "status": 500,
- "body": '{"type": "server_error", "detail": "Internal server error"}',
- "content_type": "application/json",
- }
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- self.assertEqual(response.status_code, 500)
- self.assertEqual(response.json()["detail"], "Internal server error")
-
- def test_follower_permission_denied_returns_403_not_500(self):
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = False
- mock_coalescer._dry_run = False
- mock_coalescer.wait_for_signal.return_value = CoalesceSignal.DONE
- mock_coalescer.get_success_response.return_value = {
- "status": 200,
- "body": '{"results": [["test_event"]]}',
- "content_type": "application/json",
- }
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- mock.patch(
- "posthog.api.query.QueryViewSet.check_permissions",
- side_effect=PermissionDenied(),
- ),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- self.assertEqual(response.status_code, 403)
-
- def test_follower_throttled_still_serves_cached_response(self):
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = False
- mock_coalescer._dry_run = False
- mock_coalescer.wait_for_signal.return_value = CoalesceSignal.DONE
- mock_coalescer.get_success_response.return_value = {
- "status": 200,
- "body": '{"results": [["test_event"]]}',
- "content_type": "application/json",
- }
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer),
- mock.patch(
- "posthog.api.query.QueryViewSet.check_throttles",
- side_effect=Throttled(),
- ),
- ):
- response = self.client.post(self._query_url(), self._query_payload())
-
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.json()["results"], [["test_event"]])
-
- @parameterized.expand(
- [
- ("query", "/api/environments/{team_id}/query/"),
- ("insights_pk", "/api/environments/{team_id}/insights/123/"),
- ]
- )
- def test_matching_paths_trigger_coalescing(self, _name, path_template):
- path = path_template.format(team_id=self.team.id)
- mock_coalescer = mock.MagicMock()
- mock_coalescer.try_acquire.return_value = True
-
- with (
- mock.patch("posthog.api.query_coalescer.posthoganalytics.feature_enabled", return_value=True),
- mock.patch("posthog.api.query_coalescer.QueryCoalescer", return_value=mock_coalescer) as mock_cls,
- ):
- self.client.post(path, {"query": {"kind": "EventsQuery", "select": ["event"]}})
- mock_cls.assert_called_once()
diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.py
index 9676c97dcabd..6d37692da373 100644
--- a/posthog/settings/__init__.py
+++ b/posthog/settings/__init__.py
@@ -149,8 +149,6 @@ PROM_PUSHGATEWAY_ADDRESS: str | None = os.getenv("PROM_PUSHGATEWAY_ADDRESS", Non
HOGQL_INCREASED_MAX_EXECUTION_TIME: int = get_from_env("HOGQL_INCREASED_MAX_EXECUTION_TIME", 600, type_cast=int)
-QUERY_COALESCING_MAX_WAIT_SECONDS: int = get_from_env("QUERY_COALESCING_MAX_WAIT_SECONDS", 300, type_cast=int)
-
# Extend and override these settings with EE's ones
if "ee.apps.EnterpriseConfig" in INSTALLED_APPS:
from ee.settings import * # noqa: F401, F403
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index fe7ccaaf620d..7219e3872bc6 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -187,7 +187,6 @@ MIDDLEWARE = [
# Must run immediately after AuthenticationMiddleware so downstream middleware
# (activity logging, structlog binding, etc.) sees the swapped staff user on /admin/* paths.
"posthog.middleware.AdminImpersonationMiddleware",
- "posthog.api.query_coalescer.QueryCoalescingMiddleware",
"posthog.middleware.SocialAuthExceptionMiddleware",
"posthog.middleware.SessionAgeMiddleware",
"posthog.middleware.KnownLoginDeviceCookieMiddleware",
diff --git a/products/context_layer/backend/store.py b/products/context_layer/backend/store.py
index f14326bff9d5..2e92eab004ac 100644
--- a/products/context_layer/backend/store.py
+++ b/products/context_layer/backend/store.py
@@ -149,7 +149,7 @@ def _lock_key(organization_id: uuid.UUID | str) -> str:
# Renewal and release must check ownership and act atomically: after TTL expiry
# another writer may hold the key, and a plain get-then-expire/delete could
-# extend or drop that writer's lock. Same scripts as posthog/api/query_coalescer.py.
+# extend or drop that writer's lock.
_RENEW_LOCK_SCRIPT = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("pexpire", KEYS[1], ARGV[2])
diff --git a/products/customer_analytics/backend/presentation/views/accounts_table_query.py b/products/customer_analytics/backend/presentation/views/accounts_table_query.py
index 34061363a85c..1bb1c440859b 100644
--- a/products/customer_analytics/backend/presentation/views/accounts_table_query.py
+++ b/products/customer_analytics/backend/presentation/views/accounts_table_query.py
@@ -19,7 +19,6 @@ from posthog.schema import (
from posthog.api.documentation import _FallbackSerializer
from posthog.api.mixins import PydanticModelMixin
from posthog.api.query import QueryViewSet
-from posthog.api.query_coalescer import QueryCoalescingMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -47,7 +46,6 @@ class AccountsTableQueryRequest(BaseModel):
class AccountsTableQueryViewSet(
- QueryCoalescingMixin,
TeamAndOrgViewSetMixin,
PydanticModelMixin,
viewsets.ViewSet,
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 4bcdbafcade8..b8a3d0876a02 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -42,7 +42,6 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.monitoring import Feature, monitor
from posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_param
-from posthog.api.query_coalescer import QueryCoalescingMixin
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.services.query import process_query_model
from posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializer
@@ -1709,7 +1708,6 @@ Background calculation can be tracked using the `query_status` response field.""
destroy=extend_schema(parameters=[INSIGHT_ID_PATH_PARAMETER]),
)
class InsightViewSet(
- QueryCoalescingMixin,
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
TaggedItemViewSetMixin,
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index c355f77e3ea1..1e0aaa0f4766 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -362,14 +362,6 @@ export const getInsightsListUrl = (projectId: string, params?: InsightsListParam
: `/api/projects/${projectId}/insights/`
}
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const insightsList = async (
projectId: string,
params?: InsightsListParams,
@@ -397,14 +389,6 @@ export const getInsightsCreateUrl = (projectId: string, params?: InsightsCreateP
: `/api/projects/${projectId}/insights/`
}
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const insightsCreate = async (
projectId: string,
insightApi?: NonReadonly<InsightApi>,
@@ -435,14 +419,6 @@ export const getInsightsRetrieveUrl = (projectId: string, id: number | string, p
: `/api/projects/${projectId}/insights/${id}/`
}
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const insightsRetrieve = async (
projectId: string,
id: number | string,
@@ -471,14 +447,6 @@ export const getInsightsUpdateUrl = (projectId: string, id: number | string, par
: `/api/projects/${projectId}/insights/${id}/`
}
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const insightsUpdate = async (
projectId: string,
id: number | string,
@@ -514,14 +482,6 @@ export const getInsightsPartialUpdateUrl = (
: `/api/projects/${projectId}/insights/${id}/`
}
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const insightsPartialUpdate = async (
projectId: string,
id: number | string,
@@ -623,14 +583,6 @@ export const getInsightsAnalyzeRetrieveUrl = (
: `/api/projects/${projectId}/insights/${id}/analyze/`
}
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const insightsAnalyzeRetrieve = async (
projectId: string,
id: number,
@@ -663,14 +615,6 @@ export const getInsightsSuggestionsRetrieveUrl = (
: `/api/projects/${projectId}/insights/${id}/suggestions/`
}
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const insightsSuggestionsRetrieve = async (
projectId: string,
id: number,
@@ -703,14 +647,6 @@ export const getInsightsSuggestionsCreateUrl = (
: `/api/projects/${projectId}/insights/${id}/suggestions/`
}
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const insightsSuggestionsCreate = async (
projectId: string,
id: number,
@@ -926,14 +862,6 @@ export const getInsightsCancelCreateUrl = (projectId: string, params?: InsightsC
: `/api/projects/${projectId}/insights/cancel/`
}
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const insightsCancelCreate = async (
projectId: string,
insightApi?: NonReadonly<InsightApi>,
diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.ts
index c86f54ae8cd1..d74699b47d50 100644
--- a/products/product_analytics/frontend/generated/api.zod.ts
+++ b/products/product_analytics/frontend/generated/api.zod.ts
@@ -191,50 +191,18 @@ export const ElementsPartialUpdateBody = /* @__PURE__ */ zod.object({
order: zod.number().min(elementsPartialUpdateBodyOrderMin).max(elementsPartialUpdateBodyOrderMax).nullish(),
})
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const InsightsCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const InsightsUpdateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const InsightsPartialUpdateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const InsightsSuggestionsCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
@@ -318,14 +286,6 @@ export const InsightsBulkUpdateTagsCreateBody = /* @__PURE__ */ zod.object({
.describe('Tag names to add, remove, or set.'),
})
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const InsightsCancelCreateBody = /* @__PURE__ */ zod
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
diff --git a/services/mcp/src/generated/product_analytics/api.ts b/services/mcp/src/generated/product_analytics/api.ts
index 0cd79a339582..1692f0bef227 100644
--- a/services/mcp/src/generated/product_analytics/api.ts
+++ b/services/mcp/src/generated/product_analytics/api.ts
@@ -56,14 +56,6 @@ export const ElementsStatsRetrieveQueryParams = () => zod.object({
sampling_factor: zod.number().optional().describe('Sampling factor between 0 and 1'),
})
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const InsightsListParams = () => zod.object({
project_id: zod
.string()
@@ -170,14 +162,6 @@ export const InsightsListQueryParams = () => zod.object({
),
})
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const InsightsCreateParams = () => zod.object({
project_id: zod
.string()
@@ -224,14 +208,6 @@ export const InsightsCreateBody = () => zod
})
.describe('Simplified serializer to speed response times when loading large amounts of objects.')
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const InsightsRetrieveParams = () => zod.object({
id: zod
.union([zod.number(), zod.string()])
@@ -287,14 +263,6 @@ export const InsightsRetrieveQueryParams = () => zod.object({
),
})
-/**
- * DRF ViewSet mixin that gates coalesced responses behind permission checks.
- *
- * The QueryCoalescingMiddleware attaches cached response data to
- * request.META["_coalesced_response"] for followers. This mixin runs DRF's
- * initial() (auth + permissions + throttling) before returning the
- * cached response, ensuring the request is authorized.
- */
export const InsightsPartialUpdateParams = () => zod.object({
id: zod
.union([zod.number(), zod.string()])