: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(signals): bound the memory of one inbox ranking sweep pass (#108243)
posthog[bot]9941e2876768
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.pyindex 777bd208e2e5..f441cfac7b49 100644--- a/posthog/settings/object_storage.py+++ b/posthog/settings/object_storage.py@@ -111,7 +111,8 @@ INBOX_RANKING_PROMOTION_MIN_DAYS = get_from_env("INBOX_RANKING_PROMOTION_MIN_DAY# from the deployment's own object store, so this is the only place the served family is chosen.INBOX_RANKING_SERVED_FAMILY = os.getenv("INBOX_RANKING_SERVED_FAMILY", "report_embeddings")# Scorer (products/signals/backend/ranking/scorer.py): report ids per ClickHouse vector read. A-# larger call is paged at this size.+# larger call is paged at this size. The sweep also gives one scorer call at most this many ids, which+# bounds the vectors and matrices one call holds.INBOX_RANKING_SCORING_BATCH_SIZE = get_from_env("INBOX_RANKING_SCORING_BATCH_SIZE", 500, type_cast=int)# Scoring sweep (products/signals/backend/ranking/sweep.py). Off by default: the schedule still# ticks, but the activity returns before it reads or writes anything. The max age keeps the vectordiff --git a/products/signals/backend/ranking/sweep.py b/products/signals/backend/ranking/sweep.pyindex 0834cb9136a8..60cca1131144 100644--- a/products/signals/backend/ranking/sweep.py+++ b/products/signals/backend/ranking/sweep.py@@ -8,9 +8,11 @@ moves `updated_at` with no text change. A new vector lands only when a renderingNothing reads the `ranking_score` artefacts to order the inbox yet."""+import sysimport timeimport uuidimport datetime+import resourcefrom collections import defaultdictfrom collections.abc import Iterator, Sequencefrom typing import Any, cast@@ -32,7 +34,6 @@ from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connections-from products.signals.backend.artefact_schemas import RankingScorefrom products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.ranking import scorerfrom products.signals.backend.ranking.inventory import SCORABLE_STATUSES, spine_report_filter@@ -99,16 +100,36 @@ class ScoreInboxReportsResult:no_vector: int = 0teams: int = 0failed_teams: int = 0- # Teams not started because the time budget ran out. The next tick scores them.+ # Teams with reports not started because the time budget ran out. The next tick scores them.deferred_teams: int = 0+ deferred_reports: int = 0manifest_version: str | None = None# "disabled" or "no manifest". None when the pass ran.skipped_reason: str | None = None-def _batches(items: Sequence[str]) -> Iterator[Sequence[str]]:- for start in range(0, len(items), _POSTGRES_BATCH_SIZE):- yield items[start : start + _POSTGRES_BATCH_SIZE]+class _ScoreStamp(pydantic.BaseModel):+ """The fields of a `ranking_score` artefact that decide if the report is due.++ The full `RankingScore` copies each model's metadata onto every result, so it is tens of KB per+ report in memory. The sweep reads the latest score of every scored report in the window, so a+ full parse grows with the number of scored reports until it exhausts the worker.+ """++ scored_at: datetime.datetime+ embedding_inserted_at: datetime.datetime | None = None+ manifest_version: str+++def _batches(items: Sequence[str], size: int = _POSTGRES_BATCH_SIZE) -> Iterator[Sequence[str]]:+ for start in range(0, len(items), size):+ yield items[start : start + size]+++def _peak_rss_mb() -> int:+ # The peak of the whole worker process, which other activities share, not of this pass only.+ peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss+ return peak // (1024 * 1024) if sys.platform == "darwin" else peak // 1024def _utc(value: datetime.datetime) -> datetime.datetime:@@ -160,9 +181,9 @@ def _scorable_report_teams(return teams-def _latest_scores(report_ids: Sequence[str]) -> dict[str, RankingScore | None]:- """The latest `ranking_score` of each report that has one. A row that no longer parses is None."""- scores: dict[str, RankingScore | None] = {}+def _latest_scores(report_ids: Sequence[str]) -> dict[str, _ScoreStamp | None]:+ """The latest `ranking_score` stamp of each report that has one. A row that no longer parses is None."""+ scores: dict[str, _ScoreStamp | None] = {}for batch in _batches(report_ids):rows = (SignalReportArtefact.objects.filter(@@ -174,13 +195,13 @@ def _latest_scores(report_ids: Sequence[str]) -> dict[str, RankingScore | None]:)for report_id, content in rows:try:- scores[str(report_id)] = RankingScore.model_validate_json(content)+ scores[str(report_id)] = _ScoreStamp.model_validate_json(content)except pydantic.ValidationError:scores[str(report_id)] = Nonereturn scores-def _is_due(score: RankingScore | None, vector_inserted_at: datetime.datetime, manifest_version: str) -> bool:+def _is_due(score: _ScoreStamp | None, vector_inserted_at: datetime.datetime, manifest_version: str) -> bool:return (score is Noneor score.embedding_inserted_at is None@@ -243,27 +264,38 @@ def score_inbox_reports(limit: int | None = None) -> ScoreInboxReportsResult:candidates=len(candidates),teams=len(ids_by_team),manifest_version=manifest_version,+ peak_rss_mb=_peak_rss_mb(),)- scored = no_vector = failed_teams = deferred_teams = 0+ # A scorer call holds the vectors and matrices of all its reports, so one call scores at most one+ # vector read of one team. Each call persists its scores, so a pass that stops keeps its progress.+ chunks = [+ (team_id, batch)+ for team_id, report_ids in ids_by_team.items()+ for batch in _batches(report_ids, settings.INBOX_RANKING_SCORING_BATCH_SIZE)+ ]+ scored = no_vector = deferred_reports = 0+ failed: set[int] = set()+ deferred: set[int] = set()with ph_scoped_capture() as capture:- for team_id, report_ids in ids_by_team.items():+ for team_id, report_ids in chunks:if time.monotonic() >= deadline:- deferred_teams += 1+ deferred.add(team_id)+ deferred_reports += len(report_ids)continuetry:outcomes = scorer.score_reports(- team_id, report_ids, persist=True, now=now, serving=serving, capture=capture+ team_id, list(report_ids), persist=True, now=now, serving=serving, capture=capture)except (scorer.ScoringError, ModelLoadError):# A pass without a served score is worse than no pass.raiseexcept Exception:logger.exception("inbox_ranking_sweep_team_failed", team_id=team_id)- failed_teams += 1+ failed.add(team_id)continuefinally:- # Send the events of each team when it ends, so a killed pass keeps the events of the teams it persisted.+ # Send the events of each call when it ends, so a killed pass keeps the events of the scores it persisted.capture.flush()scored += sum(1 for outcome in outcomes if outcome.score is not None)no_vector += sum(1 for outcome in outcomes if outcome.reason == scorer.NO_VECTOR)@@ -273,8 +305,9 @@ def score_inbox_reports(limit: int | None = None) -> ScoreInboxReportsResult:scored=scored,no_vector=no_vector,teams=len(ids_by_team),- failed_teams=failed_teams,- deferred_teams=deferred_teams,+ failed_teams=len(failed),+ deferred_teams=len(deferred),+ deferred_reports=deferred_reports,manifest_version=manifest_version,)logger.info(@@ -285,7 +318,9 @@ def score_inbox_reports(limit: int | None = None) -> ScoreInboxReportsResult:teams=result.teams,failed_teams=result.failed_teams,deferred_teams=result.deferred_teams,+ deferred_reports=result.deferred_reports,manifest_version=result.manifest_version,+ peak_rss_mb=_peak_rss_mb(),)return resultdiff --git a/products/signals/backend/test/test_ranking_sweep.py b/products/signals/backend/test/test_ranking_sweep.pyindex 0822ac59e995..ed3b48b1ce5d 100644--- a/products/signals/backend/test/test_ranking_sweep.py+++ b/products/signals/backend/test/test_ranking_sweep.py@@ -6,7 +6,7 @@ from types import SimpleNamespacefrom typing import Anyfrom posthog.test.base import BaseTest, ClickhouseTestMixin-from unittest.mock import MagicMock, patch+from unittest.mock import ANY, MagicMock, patchfrom django.test import SimpleTestCase, override_settings@@ -249,7 +249,7 @@ class TestScoreInboxReports(SimpleTestCase):)assert (self.load_serving_set.call_count, self.capture_scopes, self.capture.flush.call_count) == (1, 1, 2)self.logger.info.assert_any_call(- "inbox_ranking_sweep_started", candidates=3, teams=2, manifest_version=MANIFEST+ "inbox_ranking_sweep_started", candidates=3, teams=2, manifest_version=MANIFEST, peak_rss_mb=ANY)assert (result.candidates, result.scored, result.no_vector, result.teams, result.failed_teams) == (3,@@ -269,6 +269,21 @@ class TestScoreInboxReports(SimpleTestCase):assert (result.scored, result.teams, result.failed_teams) == (1, 2, 1)assert self.capture.flush.call_count == 2+ @override_settings(INBOX_RANKING_SCORING_BATCH_SIZE=2)+ def test_a_large_team_is_scored_in_calls_of_at_most_the_batch_size(self) -> None:+ self._candidates((1, "a"), (1, "b"), (1, "c"), (1, "d"), (1, "e"), (2, "f"))++ result = score_inbox_reports()++ assert [(call.args[0], call.args[1]) for call in self.score_reports.call_args_list] == [+ (1, ["a", "b"]),+ (1, ["c", "d"]),+ (1, ["e"]),+ (2, ["f"]),+ ]+ assert self.capture.flush.call_count == 4+ assert (result.scored, result.teams, result.deferred_teams) == (6, 2, 0)+def test_teams_left_when_the_time_budget_runs_out_are_deferred_to_the_next_tick(self) -> None:self._candidates((1, "a"), (2, "b"), (3, "c"))clock = [0.0]@@ -283,7 +298,13 @@ class TestScoreInboxReports(SimpleTestCase):result = score_inbox_reports()assert [call.args[0] for call in self.score_reports.call_args_list] == [1]- assert (result.scored, result.teams, result.failed_teams, result.deferred_teams) == (1, 3, 0, 2)+ assert (result.scored, result.teams, result.failed_teams, result.deferred_teams, result.deferred_reports) == (+ 1,+ 3,+ 0,+ 2,+ 2,+ )@parameterized.expand([("scoring_error", ScoringError("no served score")), ("served_model_load", ModelLoadError("no booster"))]