: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
fix(personhog): clamp person batch size at server limit of 250 (#60712)
Nick Best923c30290e03
diff --git a/posthog/hogql_queries/actor_strategies.py b/posthog/hogql_queries/actor_strategies.pyindex e24e68579f2d..983a5c7e029f 100644--- a/posthog/hogql_queries/actor_strategies.py+++ b/posthog/hogql_queries/actor_strategies.py@@ -1,6 +1,6 @@import uuid as uuid_modfrom datetime import UTC, datetime-from typing import TYPE_CHECKING, Literal, Optional, cast+from typing import Literal, Optional, castfrom django.db import connections@@ -18,18 +18,14 @@ from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginatorfrom posthog.hogql_queries.utils.recordings_helper import RecordingsHelperfrom posthog.models import Teamfrom posthog.models.person import Person, PersonDistinctId+from posthog.models.person.util import (+ PERSONHOG_BATCH_SIZE,+ _batched_get_distinct_ids_for_persons,+ _batched_get_persons_by_uuids,+)from posthog.models.user import Userfrom posthog.person_db_router import PERSONS_DB_FOR_READ-from posthog.personhog_client.metrics import (- PERSONHOG_ROUTING_ERRORS_TOTAL,- PERSONHOG_ROUTING_TOTAL,- PERSONHOG_TEAM_MISMATCH_TOTAL,- get_client_name,-)-from posthog.personhog_client.proto import GetDistinctIdsForPersonsRequest, GetPersonsByUuidsRequest--if TYPE_CHECKING:- from posthog.personhog_client.client import PersonHogClient+from posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_namelogger = structlog.get_logger(__name__)@@ -75,16 +71,13 @@ class PersonStrategy(ActorStrategy):origin = "persons"origin_id = "id"- # batching is needed to prevent timeouts when reading from Postgres- BATCH_SIZE = 1000-def get_actors(self, actor_ids, sort_by_created_at_descending: bool = False) -> dict[str, dict]:from posthog.personhog_client.client import get_personhog_clientclient = get_personhog_client()if client is not None:try:- result = self._get_actors_via_personhog(client, actor_ids, sort_by_created_at_descending)+ result = self._get_actors_via_personhog(actor_ids, sort_by_created_at_descending)PERSONHOG_ROUTING_TOTAL.labels(operation="get_actors", source="personhog", client_name=get_client_name()).inc()@@ -100,42 +93,19 @@ class PersonStrategy(ActorStrategy):def _get_actors_via_personhog(self,- client: "PersonHogClient",actor_ids,sort_by_created_at_descending: bool,) -> dict[str, dict]:actor_ids_list = [str(uid) for uid in actor_ids]team_id = self.team.pk- all_persons = []- for i in range(0, len(actor_ids_list), self.BATCH_SIZE):- batch = actor_ids_list[i : i + self.BATCH_SIZE]- resp = client.get_persons_by_uuids(GetPersonsByUuidsRequest(team_id=team_id, uuids=batch))-- present = [p for p in resp.persons if p.id]- valid = [p for p in present if p.team_id == team_id]-- mismatched = len(present) - len(valid)- if mismatched:- PERSONHOG_TEAM_MISMATCH_TOTAL.labels(operation="get_actors", client_name=get_client_name()).inc(- mismatched- )- logger.warning("personhog_team_mismatch", operation="get_actors", team_id=team_id, dropped=mismatched)-- all_persons.extend(valid)+ all_persons = _batched_get_persons_by_uuids(team_id, actor_ids_list, operation="get_actors")if sort_by_created_at_descending:all_persons.sort(key=lambda p: (-p.created_at, p.uuid))person_ids = [p.id for p in all_persons]- distinct_ids_by_person: dict[int, list[str]] = {}- for i in range(0, len(person_ids), self.BATCH_SIZE):- did_batch = person_ids[i : i + self.BATCH_SIZE]- did_resp = client.get_distinct_ids_for_persons(- GetDistinctIdsForPersonsRequest(team_id=team_id, person_ids=did_batch)- )- for pd in did_resp.person_distinct_ids:- distinct_ids_by_person[pd.person_id] = [d.distinct_id for d in pd.distinct_ids]+ distinct_ids_by_person = _batched_get_distinct_ids_for_persons(team_id, person_ids)return {p.uuid: {@@ -164,8 +134,8 @@ class PersonStrategy(ActorStrategy):all_distinct_ids: list = []with conn.cursor() as cursor:- for i in range(0, len(actor_ids_list), self.BATCH_SIZE):- batch = actor_ids_list[i : i + self.BATCH_SIZE]+ for i in range(0, len(actor_ids_list), PERSONHOG_BATCH_SIZE):+ batch = actor_ids_list[i : i + PERSONHOG_BATCH_SIZE]persons_query = f"""SELECT {person_table}.id, {person_table}.uuid, {person_table}.properties, {person_table}.is_identified, {person_table}.created_at, {person_table}.last_seen_atFROM {person_table}WHERE {person_table}.uuid = ANY(%(uuids)s)@@ -180,8 +150,8 @@ class PersonStrategy(ActorStrategy):all_people.sort(key=lambda p: (-(p[4] or min_dt).timestamp(), str(p[1])))person_ids = [x[0] for x in all_people]- for i in range(0, len(person_ids), self.BATCH_SIZE):- batch = person_ids[i : i + self.BATCH_SIZE]+ for i in range(0, len(person_ids), PERSONHOG_BATCH_SIZE):+ batch = person_ids[i : i + PERSONHOG_BATCH_SIZE]cursor.execute(f"""SELECT {pdi_table}.person_id, {pdi_table}.distinct_idFROM {pdi_table}diff --git a/posthog/hogql_queries/test/test_actor_strategies_personhog.py b/posthog/hogql_queries/test/test_actor_strategies_personhog.pyindex 247a4fce0176..8d02c5fa1fc6 100644--- a/posthog/hogql_queries/test/test_actor_strategies_personhog.py+++ b/posthog/hogql_queries/test/test_actor_strategies_personhog.py@@ -96,7 +96,7 @@ class TestPersonStrategyGetActors(PersonhogTestMixin, BaseTest):persons.append(p)strategy = _make_strategy(self.team)- with patch.object(PersonStrategy, "BATCH_SIZE", 2):+ with patch("posthog.models.person.util.PERSONHOG_BATCH_SIZE", 2):result = strategy.get_actors([str(p.uuid) for p in persons])assert len(result) == 5diff --git a/posthog/hogql_queries/test/test_actors_query_runner.py b/posthog/hogql_queries/test/test_actors_query_runner.pyindex 5f36c06c2972..5fb183401f42 100644--- a/posthog/hogql_queries/test/test_actors_query_runner.py+++ b/posthog/hogql_queries/test/test_actors_query_runner.py@@ -854,7 +854,7 @@ class TestActorsQueryRunner(ClickhouseTestMixin, APIBaseTest):strategy = PersonStrategy(team=self.team, query=query, paginator=paginator)# Temporarily set a small batch size to verify batching works- with patch.object(PersonStrategy, "BATCH_SIZE", 2):+ with patch("posthog.models.person.util.PERSONHOG_BATCH_SIZE", 2):result = strategy.get_actors(person_uuids)self.assertEqual(len(result), 5)diff --git a/posthog/models/person/util.py b/posthog/models/person/util.pyindex 2aa6dec930fc..0a38cdeee58a 100644--- a/posthog/models/person/util.py+++ b/posthog/models/person/util.py@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Optional, TypeVar, Union, castfrom uuid import UUIDfrom zoneinfo import ZoneInfo+from django.conf import settingsfrom django.db.models.query import Prefetch, QuerySetfrom django.db.models.signals import post_delete, post_savefrom django.dispatch import receiver@@ -50,7 +51,7 @@ from posthog.settings import TESTlogger = structlog.get_logger(__name__)-PERSONHOG_BATCH_SIZE = 250+PERSONHOG_BATCH_SIZE: int = settings.PERSONHOG_BATCH_SIZEif TYPE_CHECKING:diff --git a/posthog/settings/personhog.py b/posthog/settings/personhog.pyindex e5723b2fce5c..d01d18e71d14 100644--- a/posthog/settings/personhog.py+++ b/posthog/settings/personhog.py@@ -14,3 +14,9 @@ PERSONHOG_INITIAL_RECONNECT_BACKOFF_MS = get_from_env("PERSONHOG_INITIAL_RECONNEPERSONHOG_MAX_SEND_MESSAGE_LENGTH = get_from_env("PERSONHOG_MAX_SEND_MESSAGE_LENGTH", 4 * 1024 * 1024, type_cast=int)PERSONHOG_MAX_RECV_MESSAGE_LENGTH = get_from_env("PERSONHOG_MAX_RECV_MESSAGE_LENGTH", 128 * 1024 * 1024, type_cast=int)PERSONHOG_CLIENT_IDLE_TIMEOUT_MS = get_from_env("PERSONHOG_CLIENT_IDLE_TIMEOUT_MS", 0, type_cast=int)++# Server enforces a hard limit of 250 IDs per batch lookup request for person records.+_PERSONHOG_MAX_BATCH_SIZE = 250+PERSONHOG_BATCH_SIZE: int = max(+ 1, min(get_from_env("PERSONHOG_BATCH_SIZE", _PERSONHOG_MAX_BATCH_SIZE, type_cast=int), _PERSONHOG_MAX_BATCH_SIZE)+)