Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(replay-vision): assign semantics in batches and read a backfill slice once (#124602)

Tue Haulund33cee34f24f8
diff --git a/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts b/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts
index 0ac1900953de..7039ad3557a1 100644
--- a/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts
+++ b/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts
@@ -54,10 +54,10 @@ describe('recording cleanup (integration)', () => {
`INSERT INTO replay_vision_replayscanner
(id, team_id, name, description, scanner_type, scanner_config, query, sampling_rate,
sampling_mode, provider, model, enabled, emits_signals, scanner_version, last_swept_at,
- search_suggestions, admission_credits_since_refresh, created_at, updated_at)
+ admission_credits_since_refresh, created_at, updated_at)
VALUES ($1, $2, 'cleanup-scanner', '', 'monitor', '{}'::jsonb, '{}'::jsonb, 1.0,
'comprehensive', 'google', 'gemini-3.8-flash', true, false, 1, now(),
- '{}'::jsonb, 0, now(), now())`,
+ 0, now(), now())`,
[scannerId, teamId],
'fixtureScanner'
)
diff --git a/products/replay_vision/backend/embeddings.py b/products/replay_vision/backend/embeddings.py
index 905e3679370b..f8990566b964 100644
--- a/products/replay_vision/backend/embeddings.py
+++ b/products/replay_vision/backend/embeddings.py
@@ -17,17 +17,19 @@ OBSERVATION_EMBEDDINGS_TABLE = (
f"distributed_posthog_document_embeddings_{OBSERVATION_EMBEDDING_MODEL.value.replace('-', '_')}"
)
-# One team's observation embeddings from the given scanners; bind its values with `observation_scope_params`.
-OBSERVATION_SCOPE_PREWHERE = """team_id = %(team_id)s
+# All of one team's observation embeddings; bind its values with `team_embeddings_params`.
+TEAM_EMBEDDINGS_PREWHERE = """team_id = %(team_id)s
AND product = %(product)s
- AND document_type = %(document_type)s
+ AND document_type = %(document_type)s"""
+
+# One team's observation embeddings from the given scanners; bind its values with `observation_scope_params`.
+OBSERVATION_SCOPE_PREWHERE = f"""{TEAM_EMBEDDINGS_PREWHERE}
AND JSONExtractString(metadata, 'scanner_id') IN %(scanner_ids)s"""
+def team_embeddings_params(team_id: int) -> dict[str, Any]:
+ return {"team_id": team_id, "product": EMBEDDING_PRODUCT, "document_type": EMBEDDING_DOCUMENT_TYPE}
+
+
def observation_scope_params(team_id: int, scanner_ids: list[str]) -> dict[str, Any]:
- return {
- "team_id": team_id,
- "product": EMBEDDING_PRODUCT,
- "document_type": EMBEDDING_DOCUMENT_TYPE,
- "scanner_ids": scanner_ids,
- }
+ return {**team_embeddings_params(team_id), "scanner_ids": scanner_ids}
diff --git a/products/replay_vision/backend/semantic_space.py b/products/replay_vision/backend/semantic_space.py
index 36b046ed4b2b..2ff49bad6f91 100644
--- a/products/replay_vision/backend/semantic_space.py
+++ b/products/replay_vision/backend/semantic_space.py
@@ -6,9 +6,18 @@ alike. A young scanner's mean is mostly its own few rows, so until the mean has
vectors at a plain similarity.
"""
+import uuid
+from datetime import UTC, datetime
+
import numpy as np
from posthog.dataclasses import frozen
+from posthog.models.scoping.manager import resolve_effective_team_id
+
+from products.replay_vision.backend.models.replay_scanner_semantics import (
+ ReplayScannerFeedGroup,
+ ReplayScannerSearchTheme,
+)
# text-embedding-3 vectors keep their meaning when cut short and renormalised, and a short one keeps the clusters
# cheap to hold and compare.
@@ -54,13 +63,159 @@ def scanner_space(center_sum: np.ndarray, center_count: int, vector: np.ndarray)
def nearest_cluster(
- sums: np.ndarray, counts: np.ndarray, space: SemanticSpace, centred_threshold: float, raw_threshold: float
+ sums: np.ndarray,
+ counts: np.ndarray,
+ squared_norms: np.ndarray,
+ space: SemanticSpace,
+ centred_threshold: float,
+ raw_threshold: float,
+ eligible: np.ndarray | None = None,
) -> int | None:
- """The index of the cluster whose mean is closest to the vector, or None when none is close enough."""
+ """The index of the eligible cluster whose mean is closest to the vector, or None when none is close enough."""
if not len(counts):
return None
- centroids = unit(sums / counts[:, None] - space.mean)
- similarities = centroids @ unit(space.vector - space.mean)
+ direction = unit(space.vector - space.mean)
+ # Each centred mean's projection and length come from the sums and their cached squared norms, so a scanner with
+ # thousands of clusters costs one pass over the sums rather than a new matrix of centroids.
+ dots = sums @ np.stack([direction, space.mean], axis=1)
+ projections = dots[:, 0] / counts
+ lengths_squared = squared_norms / counts**2
+ if space.centring:
+ projections -= float(space.mean @ direction)
+ lengths_squared += float(space.mean @ space.mean) - 2 * dots[:, 1] / counts
+ # The expansion subtracts near-equal terms when a cluster's mean sits close to the scanner mean, so those few
+ # lengths are taken directly instead.
+ if space.centring and len(close := np.nonzero(lengths_squared < 1e-3 * squared_norms / counts**2)[0]):
+ lengths_squared[close] = np.einsum(
+ "ij,ij->i", sums[close] / counts[close, None] - space.mean, sums[close] / counts[close, None] - space.mean
+ )
+ lengths = np.sqrt(np.maximum(lengths_squared, 0))
+ similarities = np.divide(projections, lengths, out=np.full_like(projections, -np.inf), where=lengths > 1e-6)
+ if eligible is not None:
+ similarities[~eligible] = -np.inf
best = int(np.argmax(similarities))
threshold = centred_threshold if space.centring else raw_threshold
return best if similarities[best] >= threshold else None
+
+
+class ClusterArrays:
+ """Clusters as arrays with spare capacity, with each sum's squared norm kept current for `nearest_cluster`."""
+
+ def __init__(self, ids: list[uuid.UUID], sums: list[np.ndarray], counts: list[int], last: list[datetime]) -> None:
+ self.size = len(ids)
+ capacity = max(16, self.size * 2)
+ self.ids = list(ids)
+ self._sums = np.zeros((capacity, SEMANTIC_DIMENSIONS), dtype=np.float32)
+ self._counts = np.zeros(capacity, dtype=np.float32)
+ self._last = np.zeros(capacity, dtype=np.float64)
+ self._squares = np.zeros(capacity, dtype=np.float32)
+ if self.size:
+ self._sums[: self.size] = sums
+ self._counts[: self.size] = counts
+ self._last[: self.size] = [at.timestamp() for at in last]
+ self._squares[: self.size] = np.einsum("ij,ij->i", self.sums, self.sums)
+
+ def __len__(self) -> int:
+ return self.size
+
+ @property
+ def capacity(self) -> int:
+ return len(self._counts)
+
+ @property
+ def sums(self) -> np.ndarray:
+ return self._sums[: self.size]
+
+ @property
+ def counts(self) -> np.ndarray:
+ return self._counts[: self.size]
+
+ @property
+ def last(self) -> np.ndarray:
+ return self._last[: self.size]
+
+ @property
+ def squares(self) -> np.ndarray:
+ return self._squares[: self.size]
+
+ def nearest(
+ self, space: SemanticSpace, active_since: datetime, centred_threshold: float, raw_threshold: float
+ ) -> int | None:
+ """The closest cluster that took a member since `active_since`, or None when none is close enough."""
+ eligible = self.last >= active_since.timestamp()
+ return nearest_cluster(
+ self.sums,
+ self.counts,
+ self.squares,
+ space,
+ centred_threshold,
+ raw_threshold,
+ None if eligible.all() else eligible,
+ )
+
+ def add(self, cluster_id: uuid.UUID, vector: np.ndarray, at: datetime) -> int:
+ if self.size == self.capacity:
+ self._sums = np.concatenate([self._sums, np.zeros_like(self._sums)])
+ self._counts = np.concatenate([self._counts, np.zeros_like(self._counts)])
+ self._last = np.concatenate([self._last, np.zeros_like(self._last)])
+ self._squares = np.concatenate([self._squares, np.zeros_like(self._squares)])
+ index = self.size
+ self.ids.append(cluster_id)
+ self._sums[index] = vector
+ self._counts[index] = 1.0
+ self._last[index] = at.timestamp()
+ self._squares[index] = float(vector @ vector)
+ self.size += 1
+ return index
+
+ def join(self, index: int, vector: np.ndarray, at: datetime) -> None:
+ self._sums[index] += vector
+ self._squares[index] = float(self._sums[index] @ self._sums[index])
+ self._counts[index] += 1
+ # The backfill replays old rows while the consumer adds new ones, so the latest member time never moves back.
+ self._last[index] = max(self._last[index], at.timestamp())
+
+ def last_member_at(self, index: int) -> datetime:
+ return datetime.fromtimestamp(self._last[index], tz=UTC)
+
+ def keep(self, indices: np.ndarray) -> None:
+ """Keep only the clusters at these indices, in this order."""
+ if len(indices) == self.size:
+ return
+ self.ids = [self.ids[i] for i in indices]
+ for array in (self._sums, self._counts, self._last, self._squares):
+ array[: len(indices)] = array[: self.size][indices]
+ self.size = len(indices)
+
+
+class ClusterWrites:
+ """The cluster rows one batch of assignments created or changed, upserted once when the batch ends."""
+
+ def __init__(
+ self, model: type[ReplayScannerFeedGroup] | type[ReplayScannerSearchTheme], team_id: int, scanner_id: str
+ ) -> None:
+ self._model = model
+ self._team_id = team_id
+ # A bulk insert skips the save that moves a child environment's row to its project, so the id is resolved here.
+ self._row_team_id = resolve_effective_team_id(team_id)
+ self._scanner_id = scanner_id
+ self._rows: dict[uuid.UUID, ReplayScannerFeedGroup | ReplayScannerSearchTheme] = {}
+
+ def record(self, clusters: ClusterArrays, index: int) -> None:
+ # Values are absolute: every writer holds the centre lock, and a cache behind Postgres reloads before it assigns.
+ self._rows[clusters.ids[index]] = self._model(
+ id=clusters.ids[index],
+ team_id=self._row_team_id,
+ scanner_id=self._scanner_id,
+ vector_sum=pack(clusters.sums[index]),
+ member_count=int(clusters.counts[index]),
+ last_member_at=clusters.last_member_at(index),
+ )
+
+ def save(self) -> None:
+ self._model.objects.for_team(self._team_id).bulk_create(
+ list(self._rows.values()), # type: ignore[arg-type]
+ update_conflicts=True,
+ unique_fields=["id"],
+ update_fields=["vector_sum", "member_count", "last_member_at"],
+ )
diff --git a/products/replay_vision/backend/tests/test_watch_semantics.py b/products/replay_vision/backend/tests/test_watch_semantics.py
index 023e0ccba040..aeda370f5e00 100644
--- a/products/replay_vision/backend/tests/test_watch_semantics.py
+++ b/products/replay_vision/backend/tests/test_watch_semantics.py
@@ -25,13 +25,21 @@ from products.replay_vision.backend.models.replay_scanner_semantics import (
ReplayScannerSearchTheme,
ReplayScannerSemanticCenter,
)
-from products.replay_vision.backend.semantic_space import SEMANTIC_DIMENSIONS, pack, semantic_vector
+from products.replay_vision.backend.semantic_space import (
+ SEMANTIC_DIMENSIONS,
+ SemanticSpace,
+ nearest_cluster,
+ pack,
+ scanner_space,
+ semantic_vector,
+ unit,
+)
from products.replay_vision.backend.tests.helpers import axis_anchors, snapshot_for
from products.replay_vision.backend.watch_feed_groups import feed_group_cache
from products.replay_vision.backend.watch_rank import ANCHOR_VERSION
-from products.replay_vision.backend.watch_semantics import assign_semantics
+from products.replay_vision.backend.watch_semantics import SemanticItem, assign_semantics, assign_semantics_batch
from products.replay_vision.backend.watch_semantics_backfill import backfill_team_semantics
-from products.replay_vision.backend.watch_themes import belongs_in_theme, finalize_label, name_theme
+from products.replay_vision.backend.watch_themes import belongs_in_theme, finalize_label, name_theme, naming_candidates
_THEMES = "products.replay_vision.backend.watch_themes"
_BACKFILL = "products.replay_vision.backend.watch_semantics_backfill"
@@ -76,6 +84,29 @@ class TestThemeRules(SimpleTestCase):
def test_label_shape(self, _name: str, raw: str, expected: str) -> None:
assert finalize_label(raw) == expected
+ @parameterized.expand([("raw", False), ("centred", True)])
+ def test_nearest_cluster_matches_comparing_every_centred_mean(self, _name: str, centring: bool) -> None:
+ rng = np.random.default_rng(7)
+ sums = rng.normal(size=(200, SEMANTIC_DIMENSIONS)).astype(np.float32)
+ counts = rng.integers(1, 40, size=200).astype(np.float32)
+ vector = unit(rng.normal(size=SEMANTIC_DIMENSIONS).astype(np.float32))
+ mean = (
+ unit(rng.normal(size=SEMANTIC_DIMENSIONS).astype(np.float32)) * 0.3 if centring else np.zeros_like(vector)
+ )
+ space = SemanticSpace(vector=vector, mean=mean, centring=centring)
+
+ expected = int(np.argmax(unit(sums / counts[:, None] - mean) @ unit(vector - mean)))
+
+ assert nearest_cluster(sums, counts, np.einsum("ij,ij->i", sums, sums), space, -1.0, -1.0) == expected
+
+ def test_a_cluster_whose_mean_matches_the_scanner_mean_still_takes_its_own_vector(self) -> None:
+ common, rare = np.eye(SEMANTIC_DIMENSIONS, dtype=np.float32)[:2]
+ sums = np.stack([common * 10_000, rare])
+ counts = np.array([10_000, 1], dtype=np.float32)
+ space = scanner_space(common * 10_000 + rare, 10_001, common)
+
+ assert nearest_cluster(sums, counts, np.einsum("ij,ij->i", sums, sums), space, 0.65, 0.90) == 0
+
class TestAssignSemantics(BaseTest):
def setUp(self) -> None:
@@ -124,19 +155,47 @@ class TestAssignSemantics(BaseTest):
def _counts(self, model: type[ReplayScannerFeedGroup] | type[ReplayScannerSearchTheme]) -> list[int]:
return sorted(model.objects.for_team(self.team.id).values_list("member_count", flat=True))
- @parameterized.expand([(ScannerOrigin.CONFIGURED,), (ScannerOrigin.INLINE,)])
- def test_close_observations_share_a_group_and_a_theme_and_a_redelivery_counts_once(self, origin: str) -> None:
+ @parameterized.expand(
+ [
+ ("configured", ScannerOrigin.CONFIGURED, False),
+ ("inline", ScannerOrigin.INLINE, False),
+ # One chunk holds a group created earlier in the same chunk, so the result matches one call per row.
+ ("one_batch", ScannerOrigin.CONFIGURED, True),
+ ]
+ )
+ def test_close_observations_share_a_group_and_a_theme_and_a_redelivery_counts_once(
+ self, _name: str, origin: str, batch: bool
+ ) -> None:
self.scanner = self._scanner(ScannerType.SUMMARIZER, name="refunds", origin=origin)
first, close, far = self._observation(), self._observation(), self._observation()
routine = self._observation(category="routine")
+ vectors = [(first, _vector(1.0)), (close, _vector(1.0, 0.1)), (far, _vector(0.0, 1.0)), (routine, _vector(1.0))]
- joined = [self._assign(first, _vector(1.0)), self._assign(close, _vector(1.0, 0.1))]
+ if batch:
+ assigned = assign_semantics_batch(
+ team_id=self.team.id,
+ scanner_id=str(self.scanner.id),
+ items=[SemanticItem(observation_id=str(o.id), vector=v, now=timezone.now()) for o, v in vectors],
+ )
+ joined: list[Any] = [assigned[str(first.id)], assigned[str(close.id)]]
+ far_assignment: Any = assigned[str(far.id)]
+ routine_assignment: Any = assigned[str(routine.id)]
+ else:
+ joined = [self._assign(first, _vector(1.0)), self._assign(close, _vector(1.0, 0.1))]
+ far_assignment = self._assign(far, _vector(0.0, 1.0))
+ # A message may spell the id in another case, and the row must still be found.
+ routine_assignment = assign_semantics(
+ team_id=self.team.id,
+ scanner_id=str(self.scanner.id),
+ observation_id=str(routine.id).upper(),
+ vector=_vector(1.0),
+ now=timezone.now(),
+ )
assert joined[0].group_id == joined[1].group_id
assert joined[0].theme.theme_id == joined[1].theme.theme_id
assert self._assign(first, _vector(1.0)) is None
- assert self._assign(far, _vector(0.0, 1.0)).group_id != joined[0].group_id
+ assert far_assignment.group_id != joined[0].group_id
# A routine row joins a feed group, so a viewer who counts it as an issue finds it grouped, but never a theme.
- routine_assignment = self._assign(routine, _vector(1.0))
assert routine_assignment.group_id == joined[0].group_id
assert routine_assignment.theme is None
@@ -214,14 +273,20 @@ class TestAssignSemantics(BaseTest):
assert self._counts(ReplayScannerFeedGroup) == [1, 2]
- def test_the_backfill_fills_only_what_a_ranked_row_is_missing(self) -> None:
+ # An embedding stored long after its observation was created falls outside the slice's bounded read.
+ @parameterized.expand([("embedded_on_time", False), ("embedded_late", True)])
+ def test_the_backfill_fills_only_what_a_ranked_row_is_missing(self, _name: str, late: bool) -> None:
grouped = self._observation()
ReplayObservation.objects.filter(id=grouped.id).update(
watch_rank={**_rank(), "group": "kept"}, status="succeeded", completed_at=timezone.now()
)
vector = np.array([1.0, 0.0, 0.0], dtype=np.float32)
+
+ def stored(_team_id: int, ids: list[str], _since: Any, until: Any) -> dict[str, np.ndarray]:
+ return {} if late and until is not None else dict.fromkeys(ids, vector)
+
with (
- patch(f"{_BACKFILL}._stored_vectors", return_value={str(grouped.id): vector}),
+ patch(f"{_BACKFILL}.stored_vectors_between", side_effect=stored),
patch(f"{_BACKFILL}.anchor_vectors", AsyncMock(return_value=axis_anchors())),
):
backfill_team_semantics(self.team.id, timezone.now() - timedelta(days=1))
@@ -257,6 +322,26 @@ class TestAssignSemantics(BaseTest):
due = [self._assign(self._observation(), _vector(1.0)).theme.name_due for _ in range(5)]
assert due == [False, False, False, False, True]
+ def test_only_themes_a_suggestion_can_show_are_due_a_name(self) -> None:
+ def theme(member_count: int, rename_at: int) -> ReplayScannerSearchTheme:
+ return ReplayScannerSearchTheme.objects.for_team(self.team.id).create(
+ team=self.team,
+ scanner=self.scanner,
+ vector_sum=pack(semantic_vector(_vector(1.0))),
+ member_count=member_count,
+ rename_at_member_count=rename_at,
+ last_member_at=timezone.now(),
+ )
+
+ # The eight largest fill every suggestion slot and are named already, so the due ninth never shows.
+ for size in range(20, 28):
+ theme(size, rename_at=size * 2)
+ theme(10, rename_at=5)
+ assert list(naming_candidates(self.team.id, timezone.now())) == []
+
+ shown = theme(30, rename_at=5)
+ assert list(naming_candidates(self.team.id, timezone.now())) == [shown]
+
def test_naming_writes_the_label_once_per_doubling_and_retries_a_failed_call(self) -> None:
for _ in range(5):
assignment = self._assign(
diff --git a/products/replay_vision/backend/watch_feed_groups.py b/products/replay_vision/backend/watch_feed_groups.py
index 4fb86f7f467c..86935a21002d 100644
--- a/products/replay_vision/backend/watch_feed_groups.py
+++ b/products/replay_vision/backend/watch_feed_groups.py
@@ -11,19 +11,12 @@ import uuid
from collections import OrderedDict
from datetime import datetime, timedelta
-from django.db.models import F
-from django.db.models.functions import Greatest
-
import numpy as np
+from posthog.models.utils import uuid7
+
from products.replay_vision.backend.models.replay_scanner_semantics import ReplayScannerFeedGroup
-from products.replay_vision.backend.semantic_space import (
- SEMANTIC_DIMENSIONS,
- SemanticSpace,
- nearest_cluster,
- pack,
- unpack,
-)
+from products.replay_vision.backend.semantic_space import ClusterArrays, ClusterWrites, SemanticSpace, unpack
FEED_GROUP_MIN_SIMILARITY = 0.65
FEED_GROUP_MIN_RAW_SIMILARITY = 0.90
@@ -34,100 +27,53 @@ MAX_CACHED_GROUPS_PER_SCANNER = 20_000
MAX_CACHED_GROUPS = 100_000
-class _ScannerGroups:
- """One scanner's active groups as arrays with spare capacity, and the centre member count they reflect."""
+class _ScannerGroups(ClusterArrays):
+ """One scanner's active groups, and the centre member count they reflect."""
def __init__(self, groups: list[ReplayScannerFeedGroup], version: int) -> None:
- self.size = len(groups)
- capacity = max(16, self.size * 2)
- self.ids: list[uuid.UUID] = [group.id for group in groups]
- self._sums = np.zeros((capacity, SEMANTIC_DIMENSIONS), dtype=np.float32)
- self._counts = np.zeros(capacity, dtype=np.float32)
- self._last = np.zeros(capacity, dtype=np.float64)
- for index, group in enumerate(groups):
- self._sums[index] = unpack(group.vector_sum)
- self._counts[index] = group.member_count
- self._last[index] = group.last_member_at.timestamp()
+ super().__init__(
+ [group.id for group in groups],
+ [unpack(group.vector_sum) for group in groups],
+ [group.member_count for group in groups],
+ [group.last_member_at for group in groups],
+ )
self.version = version
- def __len__(self) -> int:
- return self.size
-
- @property
- def capacity(self) -> int:
- return len(self._counts)
-
- @property
- def sums(self) -> np.ndarray:
- return self._sums[: self.size]
-
- @property
- def counts(self) -> np.ndarray:
- return self._counts[: self.size]
-
- @property
- def last(self) -> np.ndarray:
- return self._last[: self.size]
-
- def add(self, group_id: uuid.UUID, vector: np.ndarray, at: datetime) -> None:
- if self.size == len(self._counts):
- self._sums = np.concatenate([self._sums, np.zeros_like(self._sums)])
- self._counts = np.concatenate([self._counts, np.zeros_like(self._counts)])
- self._last = np.concatenate([self._last, np.zeros_like(self._last)])
- self.ids.append(group_id)
- self._sums[self.size] = vector
- self._counts[self.size] = 1.0
- self._last[self.size] = at.timestamp()
- self.size += 1
-
def trim(self, now: datetime) -> None:
"""Drop groups that stopped taking members, then the least recent ones above the per-scanner cap."""
keep = np.nonzero(self.last >= (now - FEED_GROUP_ACTIVE_WINDOW).timestamp())[0]
if len(keep) > MAX_CACHED_GROUPS_PER_SCANNER:
keep = keep[np.argsort(self.last[keep])[-MAX_CACHED_GROUPS_PER_SCANNER:]]
- if len(keep) == self.size:
- return
- self.ids = [self.ids[i] for i in keep]
- self._sums[: len(keep)] = self.sums[keep]
- self._counts[: len(keep)] = self.counts[keep]
- self._last[: len(keep)] = self.last[keep]
- self.size = len(keep)
+ self.keep(keep)
class FeedGroupCache:
def __init__(self) -> None:
self._scanners: OrderedDict[str, _ScannerGroups] = OrderedDict()
- def assign(self, *, team_id: int, scanner_id: str, space: SemanticSpace, version: int, now: datetime) -> uuid.UUID:
+ def assign(
+ self,
+ *,
+ team_id: int,
+ scanner_id: str,
+ space: SemanticSpace,
+ version: int,
+ now: datetime,
+ writes: ClusterWrites,
+ ) -> uuid.UUID:
"""Put one observation in its scanner's closest active group, or start a group. Call under the centre lock,
- with the centre's member count before this observation joins."""
+ with the centre's member count before this observation joins, and save `writes` before the lock is released."""
groups = self._load(team_id, scanner_id, version, now)
- best = nearest_cluster(
- groups.sums, groups.counts, space, FEED_GROUP_MIN_SIMILARITY, FEED_GROUP_MIN_RAW_SIMILARITY
+ best = groups.nearest(
+ space, now - FEED_GROUP_ACTIVE_WINDOW, FEED_GROUP_MIN_SIMILARITY, FEED_GROUP_MIN_RAW_SIMILARITY
)
if best is None:
- group = ReplayScannerFeedGroup.objects.for_team(team_id).create(
- team_id=team_id,
- scanner_id=scanner_id,
- vector_sum=pack(space.vector),
- member_count=1,
- last_member_at=now,
- )
- groups.add(group.id, space.vector, now)
- group_id = group.id
+ best = groups.add(uuid7(), space.vector, now)
else:
- group_id = groups.ids[best]
- groups.sums[best] += space.vector
- groups.counts[best] += 1
- groups.last[best] = max(groups.last[best], now.timestamp())
- # The backfill replays old rows while the consumer adds new ones, so the latest member time never moves back.
- ReplayScannerFeedGroup.objects.for_team(team_id).filter(id=group_id).update(
- vector_sum=pack(groups.sums[best]),
- member_count=F("member_count") + 1,
- last_member_at=Greatest("last_member_at", now),
- )
+ groups.join(best, space.vector, now)
+ writes.record(groups, best)
groups.version = version + 1
- return group_id
+ return groups.ids[best]
def forget(self, scanner_id: str) -> None:
"""Drop a scanner's groups, so an assignment whose transaction rolled back never leaves them ahead of Postgres."""
diff --git a/products/replay_vision/backend/watch_rank_backfill.py b/products/replay_vision/backend/watch_rank_backfill.py
index 0169fcb5d35d..fbb683da4d56 100644
--- a/products/replay_vision/backend/watch_rank_backfill.py
+++ b/products/replay_vision/backend/watch_rank_backfill.py
@@ -31,7 +31,9 @@ from posthog.exceptions import ClickHouseAtCapacity
from products.replay_vision.backend.embeddings import (
OBSERVATION_EMBEDDINGS_TABLE,
OBSERVATION_SCOPE_PREWHERE,
+ TEAM_EMBEDDINGS_PREWHERE,
observation_scope_params,
+ team_embeddings_params,
)
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.watch_rank import (
@@ -76,32 +78,51 @@ def _stored_vectors(
team_id: int, scanner_id: str, observation_ids: list[str], since: datetime
) -> dict[str, np.ndarray]:
"""Each observation's stored unit vector, for one batch of a scanner's observations, waiting out a full cluster."""
+ return _waiting_out_capacity(
+ team_id,
+ f"{OBSERVATION_SCOPE_PREWHERE} AND timestamp >= %(since)s",
+ {**observation_scope_params(team_id, [scanner_id]), "since": since, "ids": observation_ids},
+ )
+
+
+def stored_vectors_between(
+ team_id: int, observation_ids: list[str], since: datetime, until: datetime | None
+) -> dict[str, np.ndarray]:
+ """Each observation's stored unit vector, across all of a team's scanners, from embeddings stored since `since`
+ and before `until` when given. One read covers a whole slice of a team's history, so ClickHouse scans each
+ stretch of time once."""
+ upper = "" if until is None else " AND timestamp < %(until)s"
+ return _waiting_out_capacity(
+ team_id,
+ f"{TEAM_EMBEDDINGS_PREWHERE} AND timestamp >= %(since)s{upper}",
+ {**team_embeddings_params(team_id), "since": since, "until": until, "ids": observation_ids},
+ )
+
+
+def _waiting_out_capacity(team_id: int, prewhere: str, params: dict[str, Any]) -> dict[str, np.ndarray]:
for attempt in range(_CAPACITY_RETRY_ATTEMPTS - 1):
try:
- return _read_stored_vectors(team_id, scanner_id, observation_ids, since)
+ return _read_stored_vectors(team_id, prewhere, params)
except ClickHouseAtCapacity:
delay = _CAPACITY_RETRY_BASE_S * 2**attempt
wait = random.uniform(delay, 2 * delay)
logger.info("replay_vision.watch_rank_backfill.capacity_wait", team_id=team_id, attempt=attempt, wait=wait)
time.sleep(wait)
- return _read_stored_vectors(team_id, scanner_id, observation_ids, since)
+ return _read_stored_vectors(team_id, prewhere, params)
-def _read_stored_vectors(
- team_id: int, scanner_id: str, observation_ids: list[str], since: datetime
-) -> dict[str, np.ndarray]:
+def _read_stored_vectors(team_id: int, prewhere: str, params: dict[str, Any]) -> dict[str, np.ndarray]:
with tags_context(product=Product.REPLAY_VISION, query_type="replay_vision_watch_rank_backfill"):
- # nosemgrep: clickhouse-fstring-param-audit - table name and scope are module constants
+ # nosemgrep: clickhouse-fstring-param-audit - table name and prewhere are built from module constants
rows = sync_execute(
f"""
SELECT document_id, any(embedding)
FROM {OBSERVATION_EMBEDDINGS_TABLE}
- PREWHERE {OBSERVATION_SCOPE_PREWHERE}
- AND timestamp >= %(since)s
+ PREWHERE {prewhere}
WHERE document_id IN %(ids)s
GROUP BY document_id
""",
- {**observation_scope_params(team_id, [scanner_id]), "since": since, "ids": observation_ids},
+ params,
team_id=team_id,
readonly=True,
ch_user=ClickHouseUser.REPLAY_VISION,
diff --git a/products/replay_vision/backend/watch_semantics.py b/products/replay_vision/backend/watch_semantics.py
index 5dabd8c9dede..46955d6c8131 100644
--- a/products/replay_vision/backend/watch_semantics.py
+++ b/products/replay_vision/backend/watch_semantics.py
@@ -3,17 +3,20 @@
Every ranked row gets a group, not only issues, so a viewer who counts different anchors as issues finds those rows
already grouped.
-The embedding consumer and the semantics backfill both call `assign_semantics`. It locks the scanner's semantic
-centre for the whole assignment, so two observations of one scanner never race on its clusters, and writes both ids
-to the observation's rank in one update, so a redelivered message finds them already there.
+The embedding consumer assigns one observation per message, and the semantics backfill assigns a scanner's rows in
+chunks, both through `assign_semantics_batch`. It locks the scanner's semantic centre for the whole chunk, so two
+writers never race on its clusters, and writes both ids to each observation's rank in the same transaction, so a
+redelivered message finds them already there.
"""
import uuid
+from collections.abc import Sequence
from datetime import datetime, timedelta
+from itertools import batched
from typing import Any
from django.db import transaction
-from django.db.models import F, Func, JSONField, Value
+from django.db.models import Case, F, Func, JSONField, Value, When
import numpy as np
@@ -29,6 +32,7 @@ from products.replay_vision.backend.models.replay_scanner_semantics import (
from products.replay_vision.backend.scanner_access import scanners_for_reading_observations
from products.replay_vision.backend.semantic_space import (
SEMANTIC_DIMENSIONS,
+ ClusterWrites,
pack,
scanner_space,
semantic_vector,
@@ -36,12 +40,13 @@ from products.replay_vision.backend.semantic_space import (
)
from products.replay_vision.backend.watch_feed_groups import feed_group_cache
from products.replay_vision.backend.watch_rank import current_rank
-from products.replay_vision.backend.watch_themes import ThemeAssignment, assign_theme, belongs_in_theme
+from products.replay_vision.backend.watch_themes import ThemeAssignment, ThemeBatch, belongs_in_theme
# Clusters with no member for this long are deleted, since the feed's longest window no longer reaches them.
SEMANTIC_RETENTION = timedelta(days=90)
# Pruning runs on one in this many assignments of a scanner, which keeps it rare and still bounds the tables.
_PRUNE_EVERY = 500
+_MERGE_CHUNK = 500
@frozen
@@ -50,10 +55,30 @@ class SemanticAssignment:
theme: ThemeAssignment | None
+@frozen
+class SemanticItem:
+ observation_id: str
+ vector: list[float] | np.ndarray
+ now: datetime
+
+
def assign_semantics(
*, team_id: int, scanner_id: str, observation_id: str, vector: list[float], now: datetime
) -> SemanticAssignment | None:
"""None when the observation has no current rank, already has its clusters, or is gone."""
+ assigned = assign_semantics_batch(
+ team_id=team_id,
+ scanner_id=scanner_id,
+ items=[SemanticItem(observation_id=observation_id, vector=vector, now=now)],
+ )
+ return assigned.get(observation_id)
+
+
+def assign_semantics_batch(
+ *, team_id: int, scanner_id: str, items: Sequence[SemanticItem]
+) -> dict[str, SemanticAssignment]:
+ """Assign one scanner's observations oldest first under a single centre lock, with one write per table, keyed by
+ observation id. An observation with no current rank, with its clusters already, or gone is left out."""
scanner = (
# Inline scans group and theme like configured scanners, so a question asked often enough becomes a theme.
scanners_for_reading_observations(team_id)
@@ -61,8 +86,9 @@ def assign_semantics(
.values("scanner_type", "prompt_valence", "scanner_config")
.first()
)
- if scanner is None:
- return None
+ if scanner is None or not items:
+ return {}
+ assigned: dict[str, SemanticAssignment] = {}
try:
with transaction.atomic():
center, _ = (
@@ -73,74 +99,113 @@ def assign_semantics(
defaults={"team_id": team_id, "vector_sum": pack(np.zeros(SEMANTIC_DIMENSIONS, dtype=np.float32))},
)
)
- row = (
- ReplayObservation.objects.filter(team_id=team_id, id=observation_id)
- .values("watch_rank", "scanner_result", "scanner_snapshot")
- .first()
- )
- if row is None:
- return None
- rank = current_rank({"watch_rank": row["watch_rank"]})
- if rank is None or rank.get("group"):
- return None
-
- v = semantic_vector(vector)
- center_sum = unpack(center.vector_sum)
- space = scanner_space(center_sum, center.member_count, v)
- group_id = feed_group_cache.assign(
- team_id=team_id, scanner_id=scanner_id, space=space, version=center.member_count, now=now
- )
- theme = None
- output = (row["scanner_result"] or {}).get("model_output") or {}
- # A theme name surfaces as a suggestion to anyone who can read the scanner, so an observation scanned
- # under experiment targeting, which only that experiment's viewers may read, never joins one.
- if (
- not _experiment_scoped(row["scanner_snapshot"])
- and not _valence_unknown_for_row(
- scanner["scanner_type"],
- scanner["prompt_valence"],
- scanner["scanner_config"],
- row["scanner_snapshot"],
- )
- and belongs_in_theme(
- category=rank["category"],
- scanner_type=scanner["scanner_type"],
- valence=scanner["prompt_valence"],
- output=output,
+ keys = [_as_uuid(item.observation_id) for item in items]
+ rows = {
+ row["id"]: row
+ for row in ReplayObservation.objects.filter(
+ team_id=team_id, id__in=[key for key in keys if key]
+ ).values("id", "watch_rank", "scanner_result", "scanner_snapshot")
+ }
+ center_sum = unpack(center.vector_sum).copy()
+ member_count = center.member_count
+ group_writes = ClusterWrites(ReplayScannerFeedGroup, team_id, scanner_id)
+ themes: ThemeBatch | None = None
+ for item, key in zip(items, keys):
+ row = rows.get(key) if key else None
+ rank = current_rank({"watch_rank": row["watch_rank"]}) if row else None
+ if row is None or rank is None or rank.get("group"):
+ continue
+ v = semantic_vector(item.vector)
+ space = scanner_space(center_sum, member_count, v)
+ group_id = feed_group_cache.assign(
+ team_id=team_id,
+ scanner_id=scanner_id,
+ space=space,
+ version=member_count,
+ now=item.now,
+ writes=group_writes,
)
- ):
- theme = assign_theme(team_id=team_id, scanner_id=scanner_id, space=space, now=now)
-
- center.vector_sum = pack(center_sum + v)
- center.member_count += 1
+ theme = None
+ output = (row["scanner_result"] or {}).get("model_output") or {}
+ # A theme name surfaces as a suggestion to anyone who can read the scanner, so an observation scanned
+ # under experiment targeting, which only that experiment's viewers may read, never joins one.
+ if (
+ not _experiment_scoped(row["scanner_snapshot"])
+ and not _valence_unknown_for_row(
+ scanner["scanner_type"],
+ scanner["prompt_valence"],
+ scanner["scanner_config"],
+ row["scanner_snapshot"],
+ )
+ and belongs_in_theme(
+ category=rank["category"],
+ scanner_type=scanner["scanner_type"],
+ valence=scanner["prompt_valence"],
+ output=output,
+ )
+ ):
+ themes = themes or ThemeBatch(team_id, scanner_id, item.now)
+ theme = themes.assign(space, item.now)
+ center_sum += v
+ member_count += 1
+ assigned[item.observation_id] = SemanticAssignment(group_id=group_id, theme=theme)
+
+ if not assigned:
+ return {}
+ group_writes.save()
+ if themes:
+ themes.save()
+ pruning_due = member_count // _PRUNE_EVERY > center.member_count // _PRUNE_EVERY
+ center.vector_sum = pack(center_sum)
+ center.member_count = member_count
center.save(update_fields=["vector_sum", "member_count"])
- if center.member_count % _PRUNE_EVERY == 0:
- _prune(team_id, scanner_id, now)
-
- merge_watch_rank(
- team_id, observation_id, {"group": str(group_id)} | ({"theme": str(theme.theme_id)} if theme else {})
+ if pruning_due:
+ _prune(team_id, scanner_id, items[-1].now)
+ merge_watch_ranks(
+ team_id,
+ {
+ observation_id: {"group": str(assignment.group_id)}
+ | ({"theme": str(assignment.theme.theme_id)} if assignment.theme else {})
+ for observation_id, assignment in assigned.items()
+ },
)
except Exception:
feed_group_cache.forget(scanner_id)
raise
- return SemanticAssignment(group_id=group_id, theme=theme)
+ return assigned
+
+
+def _as_uuid(observation_id: str) -> uuid.UUID | None:
+ # A message's document id is an unchecked string, so its spelling may differ from the UUID Postgres returns.
+ try:
+ return uuid.UUID(observation_id)
+ except ValueError:
+ return None
-def merge_watch_rank(team_id: int, observation_id: str, keys: dict[str, Any]) -> None:
- """Add keys to an observation's rank without rewriting what another writer put there, and drop the retired
+def merge_watch_ranks(team_id: int, keys_by_observation: dict[str, dict[str, Any]]) -> None:
+ """Add keys to each observation's rank without rewriting what another writer put there, and drop the retired
duplicate link."""
without_duplicate = Func(
F("watch_rank"), Value("duplicate_of"), template="(%(expressions)s)", arg_joiner=" - ", output_field=JSONField()
)
- ReplayObservation.objects.filter(team_id=team_id, id=observation_id).update(
- watch_rank=Func(
- without_duplicate,
- Value(keys, output_field=JSONField()),
- template="%(expressions)s",
- arg_joiner=" || ",
+ # Postgres tries each CASE branch in turn per row, so one update stays at a few hundred observations.
+ for chunk in batched(keys_by_observation.items(), _MERGE_CHUNK, strict=False):
+ keys = Case(
+ *(
+ When(id=observation_id, then=Value(observation_keys, output_field=JSONField()))
+ for observation_id, observation_keys in chunk
+ ),
+ default=Value({}, output_field=JSONField()),
output_field=JSONField(),
)
- )
+ ReplayObservation.objects.filter(
+ team_id=team_id, id__in=[observation_id for observation_id, _ in chunk]
+ ).update(
+ watch_rank=Func(
+ without_duplicate, keys, template="%(expressions)s", arg_joiner=" || ", output_field=JSONField()
+ )
+ )
def _valence_unknown_for_row(
diff --git a/products/replay_vision/backend/watch_semantics_backfill.py b/products/replay_vision/backend/watch_semantics_backfill.py
index 0eeab105695a..945b31aad73a 100644
--- a/products/replay_vision/backend/watch_semantics_backfill.py
+++ b/products/replay_vision/backend/watch_semantics_backfill.py
@@ -1,11 +1,15 @@
"""Brings observations ranked before the consumer wrote everything it writes today up to date: category scores,
anchor similarities, feed groups and search themes, so the feed and the suggestions start from history."""
-from datetime import datetime
+import uuid
+from collections import defaultdict
+from datetime import datetime, timedelta
+from itertools import batched
-from django.db.models import Exists, F, OuterRef, Q
+from django.db.models import Exists, OuterRef, Q
from django.utils import timezone
+import numpy as np
import structlog
from asgiref.sync import async_to_sync
@@ -13,18 +17,32 @@ from posthog.dataclasses import frozen
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.replay_observation_anchor_similarity import ReplayObservationAnchorSimilarity
-from products.replay_vision.backend.models.replay_scanner_semantics import ReplayScannerSearchTheme
-from products.replay_vision.backend.watch_rank import ANCHOR_VERSION, anchor_vectors, classify, save_anchor_similarities
-from products.replay_vision.backend.watch_rank_backfill import _VECTOR_CHUNK, _stored_vectors
-from products.replay_vision.backend.watch_semantics import assign_semantics, merge_watch_rank
-from products.replay_vision.backend.watch_themes import THEME_ACTIVE_WINDOW, name_theme
+from products.replay_vision.backend.watch_rank import (
+ ANCHOR_VERSION,
+ AnchorReading,
+ WatchCategory,
+ anchor_vectors,
+ classify,
+ save_anchor_similarities,
+)
+from products.replay_vision.backend.watch_rank_backfill import stored_vectors_between
+from products.replay_vision.backend.watch_semantics import SemanticItem, assign_semantics_batch, merge_watch_ranks
+from products.replay_vision.backend.watch_themes import name_theme, naming_candidates
logger = structlog.get_logger(__name__)
+# Rows per ClickHouse read, across all of a team's scanners, oldest first.
+_SLICE_ROWS = 5_000
+# An embedding lands a few minutes after its observation, so a slice reads a little past its newest row.
+_EMBEDDING_LAG = timedelta(hours=2)
+# Observations per centre lock, kept small so a live consumer message for the same scanner waits seconds at most.
+_ASSIGN_CHUNK = 100
+
@frozen
class _Pending:
observation_id: str
+ scanner_id: str
created_at: datetime
needs_group: bool
needs_scores: bool
@@ -39,8 +57,8 @@ class SemanticBackfillResult:
def backfill_team_semantics(team_id: int, since: datetime, *, dry_run: bool = False) -> SemanticBackfillResult:
- """Replay a team's ranked observations oldest first, as the consumer would have seen them, then name every
- active theme that reached its naming size."""
+ """Replay a team's ranked observations oldest first, as the consumer would have seen them, then name the themes
+ the Search tab can suggest."""
has_similarities = Exists(
ReplayObservationAnchorSimilarity.objects.for_team(team_id).filter(
observation_id=OuterRef("id"), anchor_version=ANCHOR_VERSION
@@ -53,72 +71,94 @@ def backfill_team_semantics(team_id: int, since: datetime, *, dry_run: bool = Fa
.annotate(has_similarities=has_similarities)
.filter(Q(watch_rank__group__isnull=True) | Q(watch_rank__scores__isnull=True) | Q(has_similarities=False))
)
- scanner_ids = [str(scanner_id) for scanner_id in pending.values_list("scanner_id", flat=True).distinct()]
if dry_run:
return SemanticBackfillResult(observations=pending.count(), assigned=0, named=0)
anchors = async_to_sync(anchor_vectors)(team_id)
observations = 0
assigned = 0
- # One scanner at a time, so memory stays at one scanner's pending rows however large the team's window is.
- for scanner_id in scanner_ids:
- scanner_rows = [
+ # One page per query and per slice, because a pooled connection buffers a whole result however it is iterated.
+ after: tuple[datetime, uuid.UUID] | None = None
+ while True:
+ page = pending.order_by("created_at", "id")
+ if after:
+ page = page.filter(Q(created_at__gt=after[0]) | Q(created_at=after[0], id__gt=after[1]))
+ values = list(
+ page.values_list(
+ "id", "scanner_id", "created_at", "watch_rank__group", "watch_rank__scores", "has_similarities"
+ )[:_SLICE_ROWS]
+ )
+ if not values:
+ break
+ slice_rows = [
_Pending(
observation_id=str(observation_id),
+ scanner_id=str(scanner_id),
created_at=created_at,
- needs_group=not (rank or {}).get("group"),
- needs_scores=(rank or {}).get("scores") is None,
+ needs_group=group is None,
+ needs_scores=scores is None,
needs_similarities=not has_row,
)
- for observation_id, created_at, rank, has_row in pending.filter(scanner_id=scanner_id)
- .order_by("created_at")
- .values_list("id", "created_at", "watch_rank", "has_similarities")
- .iterator(chunk_size=2_000)
+ for observation_id, scanner_id, created_at, group, scores, has_row in values
]
- observations += len(scanner_rows)
- for start in range(0, len(scanner_rows), _VECTOR_CHUNK):
- chunk = scanner_rows[start : start + _VECTOR_CHUNK]
- vectors = _stored_vectors(team_id, scanner_id, [row.observation_id for row in chunk], since)
- readings = {
- row.observation_id: classify(vectors[row.observation_id], anchors)
- for row in chunk
- if row.observation_id in vectors and (row.needs_scores or row.needs_similarities)
- }
- save_anchor_similarities(
- team_id,
- {
- row.observation_id: readings[row.observation_id].similarities
- for row in chunk
- if row.needs_similarities and row.observation_id in readings
- },
+ observations += len(slice_rows)
+ assigned += _backfill_slice(team_id, slice_rows, anchors)
+ if len(values) < _SLICE_ROWS:
+ break
+ after = (values[-1][2], values[-1][0])
+ return SemanticBackfillResult(observations=observations, assigned=assigned, named=_name_suggestable_themes(team_id))
+
+
+def _backfill_slice(team_id: int, slice_rows: list[_Pending], anchors: dict[WatchCategory, np.ndarray]) -> int:
+ ids = [row.observation_id for row in slice_rows]
+ since = slice_rows[0].created_at
+ vectors = stored_vectors_between(team_id, ids, since, slice_rows[-1].created_at + _EMBEDDING_LAG)
+ # A scan delayed by a backlog embeds long after its observation was created, so rows the bounded read missed get
+ # one read with no upper bound.
+ if late := [observation_id for observation_id in ids if observation_id not in vectors]:
+ vectors |= stored_vectors_between(team_id, late, since, None)
+ if missing := sum(observation_id not in vectors for observation_id in late):
+ logger.info("replay_vision.watch_semantics_backfill.no_vector", team_id=team_id, observations=missing)
+ readings: dict[str, AnchorReading] = {
+ row.observation_id: classify(vectors[row.observation_id], anchors)
+ for row in slice_rows
+ if row.observation_id in vectors and (row.needs_scores or row.needs_similarities)
+ }
+ save_anchor_similarities(
+ team_id,
+ {
+ row.observation_id: readings[row.observation_id].similarities
+ for row in slice_rows
+ if row.needs_similarities and row.observation_id in readings
+ },
+ )
+ merge_watch_ranks(
+ team_id,
+ {
+ row.observation_id: {"scores": readings[row.observation_id].rank.scores}
+ for row in slice_rows
+ if row.needs_scores and row.observation_id in readings
+ },
+ )
+ by_scanner: dict[str, list[SemanticItem]] = defaultdict(list)
+ for row in slice_rows:
+ if row.needs_group and row.observation_id in vectors:
+ by_scanner[row.scanner_id].append(
+ SemanticItem(observation_id=row.observation_id, vector=vectors[row.observation_id], now=row.created_at)
)
- for row in chunk:
- vector = vectors.get(row.observation_id)
- if vector is None:
- continue
- if row.needs_scores:
- merge_watch_rank(team_id, row.observation_id, {"scores": readings[row.observation_id].rank.scores})
- if row.needs_group:
- assignment = assign_semantics(
- team_id=team_id,
- scanner_id=scanner_id,
- observation_id=row.observation_id,
- vector=vector.tolist(),
- now=row.created_at,
- )
- assigned += assignment is not None
+ assigned = 0
+ for scanner_id, items in by_scanner.items():
+ for chunk in batched(items, _ASSIGN_CHUNK, strict=False):
+ assigned += len(assign_semantics_batch(team_id=team_id, scanner_id=scanner_id, items=chunk))
+ return assigned
- named = 0
+
+def _name_suggestable_themes(team_id: int) -> int:
now = timezone.now()
- due = (
- ReplayScannerSearchTheme.objects.for_team(team_id)
- .filter(member_count__gte=F("rename_at_member_count"), last_member_at__gte=now - THEME_ACTIVE_WINDOW)
- .order_by("-member_count")
- .values_list("id", flat=True)
- )
- for theme_id in list(due):
+ named = 0
+ for theme_id in list(naming_candidates(team_id, now).order_by("-member_count").values_list("id", flat=True)):
try:
named += async_to_sync(name_theme)(team_id, theme_id, now) is not None
except Exception:
logger.exception("replay_vision.watch_semantics_backfill.naming_failed", team_id=team_id)
- return SemanticBackfillResult(observations=observations, assigned=assigned, named=named)
+ return named
diff --git a/products/replay_vision/backend/watch_themes.py b/products/replay_vision/backend/watch_themes.py
index a1701a7eefbc..18d409524bd0 100644
--- a/products/replay_vision/backend/watch_themes.py
+++ b/products/replay_vision/backend/watch_themes.py
@@ -11,7 +11,7 @@ from datetime import datetime, timedelta
from typing import Any
from django.core.cache import cache
-from django.db.models import F, Window
+from django.db.models import F, QuerySet, Window
from django.db.models.functions import RowNumber
import numpy as np
@@ -21,19 +21,23 @@ from google.genai import types
from pydantic import BaseModel, Field
from posthog.dataclasses import frozen
+from posthog.models.utils import uuid7
from products.replay_vision.backend.consent import is_ai_data_processing_approved
from products.replay_vision.backend.distinct_ids import replay_vision_distinct_id
from products.replay_vision.backend.gemini_client import AI_PRODUCT, replay_gemini_client
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.replay_scanner import PromptValence, ReplayScanner, ScannerType
-from products.replay_vision.backend.models.replay_scanner_semantics import ReplayScannerSearchTheme
+from products.replay_vision.backend.models.replay_scanner_semantics import (
+ THEME_FIRST_RENAME_AT,
+ ReplayScannerSearchTheme,
+)
from products.replay_vision.backend.observation_formatting import explanation_text
from products.replay_vision.backend.semantic_space import (
SEMANTIC_DIMENSIONS,
+ ClusterArrays,
+ ClusterWrites,
SemanticSpace,
- nearest_cluster,
- pack,
unit,
unpack,
)
@@ -52,6 +56,8 @@ MAX_ACTIVE_THEMES = 2_000
MAX_SUGGESTED_QUERIES = 4
# A cross-scanner view takes at most this many suggestions from one scanner, so one busy scanner never fills it.
_PER_SCANNER_SUGGESTIONS = 2
+# A spare candidate per suggestion lets a scanner fall back to its next theme when one is a duplicate.
+_SUGGESTION_CANDIDATES = MAX_SUGGESTED_QUERIES * 2
# Two themes whose mean meanings are this close tell one story, so the list shows only the larger one.
SUGGESTION_MAX_SIMILARITY = 0.92
THEME_NAME_SAMPLES = 8
@@ -110,33 +116,70 @@ def belongs_in_theme(*, category: str, scanner_type: str, valence: str, output:
return True
-def assign_theme(*, team_id: int, scanner_id: str, space: SemanticSpace, now: datetime) -> ThemeAssignment:
- """Put one observation in its scanner's closest active theme, or start a theme. Call under the centre lock."""
- themes = list(
+class ThemeBatch:
+ """A scanner's active themes, read once for a batch of assignments under the centre lock and saved once."""
+
+ def __init__(self, team_id: int, scanner_id: str, now: datetime) -> None:
+ themes = list(
+ ReplayScannerSearchTheme.objects.for_team(team_id)
+ .filter(scanner_id=scanner_id, last_member_at__gte=now - THEME_ACTIVE_WINDOW)
+ .order_by("-last_member_at")
+ .values_list("id", "vector_sum", "member_count", "rename_at_member_count", "last_member_at")[
+ :MAX_ACTIVE_THEMES
+ ]
+ )
+ self._rename_at = {theme_id: rename_at for theme_id, _, _, rename_at, _ in themes}
+ self._clusters = ClusterArrays(
+ [theme_id for theme_id, *_ in themes],
+ [unpack(vector_sum) for _, vector_sum, *_ in themes],
+ [member_count for _, _, member_count, *_ in themes],
+ [last_member_at for *_, last_member_at in themes],
+ )
+ self._writes = ClusterWrites(ReplayScannerSearchTheme, team_id, scanner_id)
+
+ def assign(self, space: SemanticSpace, now: datetime) -> ThemeAssignment:
+ """Put one observation in its scanner's closest active theme, or start a theme."""
+ best = self._clusters.nearest(space, now - THEME_ACTIVE_WINDOW, THEME_MIN_SIMILARITY, THEME_MIN_RAW_SIMILARITY)
+ if best is None:
+ best = self._clusters.add(uuid7(), space.vector, now)
+ else:
+ self._clusters.join(best, space.vector, now)
+ self._writes.record(self._clusters, best)
+ theme_id = self._clusters.ids[best]
+ rename_at = self._rename_at.get(theme_id, THEME_FIRST_RENAME_AT)
+ return ThemeAssignment(theme_id=theme_id, name_due=int(self._clusters.counts[best]) >= rename_at)
+
+ def save(self) -> None:
+ self._writes.save()
+
+
+def _scanner_rank() -> Window:
+ """Each theme's rank by size within its scanner, so suggestions and naming agree on which themes a scanner shows."""
+ return Window(RowNumber(), partition_by=[F("scanner_id")], order_by=[F("member_count").desc(), "id"])
+
+
+def naming_candidates(
+ team_id: int, now: datetime, scanner_id: uuid.UUID | None = None
+) -> QuerySet[ReplayScannerSearchTheme]:
+ """Themes due a name among those a suggestion could show, so the daily naming budget never goes to themes nobody
+ sees."""
+ active = ReplayScannerSearchTheme.objects.for_team(team_id).filter(last_member_at__gte=now - THEME_ACTIVE_WINDOW)
+ if scanner_id is not None:
+ active = active.filter(scanner_id=scanner_id)
+ # The rank comes from all active themes, since a filter beside it would rank only the due ones.
+ shown = active.annotate(scanner_rank=_scanner_rank()).filter(scanner_rank__lte=_SUGGESTION_CANDIDATES)
+ return active.filter(id__in=shown.values("id"), member_count__gte=F("rename_at_member_count"))
+
+
+def _is_naming_candidate(team_id: int, theme_id: uuid.UUID, now: datetime) -> bool:
+ # Ranking only the theme's own scanner keeps this check cheap, since the consumer runs it for every due member.
+ scanner_id = (
ReplayScannerSearchTheme.objects.for_team(team_id)
- .filter(scanner_id=scanner_id, last_member_at__gte=now - THEME_ACTIVE_WINDOW)
- .order_by("-last_member_at")
- .only("id", "vector_sum", "member_count", "rename_at_member_count", "last_member_at")[:MAX_ACTIVE_THEMES]
- )
- best = nearest_cluster(
- np.array([unpack(theme.vector_sum) for theme in themes], dtype=np.float32).reshape(-1, SEMANTIC_DIMENSIONS),
- np.array([theme.member_count for theme in themes], dtype=np.float32),
- space,
- THEME_MIN_SIMILARITY,
- THEME_MIN_RAW_SIMILARITY,
+ .filter(id=theme_id)
+ .values_list("scanner_id", flat=True)
+ .first()
)
- if best is None:
- theme = ReplayScannerSearchTheme.objects.for_team(team_id).create(
- team_id=team_id, scanner_id=scanner_id, vector_sum=pack(space.vector), member_count=1, last_member_at=now
- )
- else:
- theme = themes[best]
- theme.vector_sum = pack(unpack(theme.vector_sum) + space.vector)
- theme.member_count += 1
- # The backfill replays old rows while the consumer adds new ones, so the latest member time never moves back.
- theme.last_member_at = max(theme.last_member_at, now)
- theme.save(update_fields=["vector_sum", "member_count", "last_member_at"])
- return ThemeAssignment(theme_id=theme.id, name_due=theme.member_count >= theme.rename_at_member_count)
+ return scanner_id is not None and naming_candidates(team_id, now, scanner_id).filter(id=theme_id).exists()
def _claim_naming(team_id: int, theme_id: uuid.UUID) -> int | None:
@@ -215,6 +258,8 @@ async def name_theme(team_id: int, theme_id: uuid.UUID, now: datetime) -> str |
# Consent and budget come before the claim, so a theme that cannot be named now is tried again on its next member.
if not await sync_to_async(is_ai_data_processing_approved)(team_id):
return None
+ if not await sync_to_async(_is_naming_candidate)(team_id, theme_id, now):
+ return None
if not await sync_to_async(_reserve_naming_budget)(team_id, now):
logger.info("replay_vision.watch_themes.naming_budget_spent", team_id=team_id)
return None
@@ -263,13 +308,13 @@ def theme_suggestions(team_id: int, scanner_ids: list[str], now: datetime) -> li
"""The names of the largest active themes among the given scanners, as example searches."""
per_scanner_cap = MAX_SUGGESTED_QUERIES if len(scanner_ids) == 1 else _PER_SCANNER_SUGGESTIONS
# Each scanner's own top themes are ranked first, so one scanner with many themes never crowds out the rest.
- themes = (
+ named = (
ReplayScannerSearchTheme.objects.for_team(team_id)
.filter(scanner_id__in=scanner_ids, last_member_at__gte=now - THEME_ACTIVE_WINDOW)
.exclude(name="")
- .annotate(
- scanner_rank=Window(RowNumber(), partition_by=[F("scanner_id")], order_by=[F("member_count").desc(), "id"])
- )
+ )
+ themes = (
+ named.annotate(scanner_rank=_scanner_rank())
# A spare candidate per slot lets a scanner fall back to its next theme when one is a duplicate.
.filter(scanner_rank__lte=per_scanner_cap * 2)
.order_by("-member_count", "id")