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(replay-vision): measure the search embedding failure rate (#101087)

posthog[bot]05bd5c381c57
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 257860f650f7..b3c29fd43fe8 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -72,6 +72,7 @@ from products.replay_vision.backend.search import (
MAX_SEARCH_LIMIT,
ObservationSearchFilters,
ObservationSearchResult,
+ is_transient_embedding_error,
parse_date_bound,
query_vector_for,
search_observations,
@@ -1387,9 +1388,11 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
)
try:
query_vector = query_vector_for(self.team, validated["q"])
- except (requests.ConnectionError, requests.Timeout):
- # The embedding worker is unreachable or slow, so the caller can retry. A rejected request
- # (requests.HTTPError) is a bug, not retryable, and should surface as a 500.
+ except requests.RequestException as error:
+ # The embedding worker is unreachable, slow, or failing, so the caller can retry. A rejected
+ # request is a bug on our side, not retryable, and should surface as a 500.
+ if not is_transient_embedding_error(error):
+ raise
logger.warning("replay_vision.observation_search.embedding_failed", team_id=self.team_id, exc_info=True)
raise EmbeddingUnavailableError()
filters = ObservationSearchFilters.from_raw(
diff --git a/products/replay_vision/backend/search.py b/products/replay_vision/backend/search.py
index 0797f0f4b611..59e0f02ae0fe 100644
--- a/products/replay_vision/backend/search.py
+++ b/products/replay_vision/backend/search.py
@@ -15,6 +15,7 @@ from zoneinfo import ZoneInfo
from django.core.cache import cache
from django.db.models import F
+import requests
from asgiref.sync import sync_to_async
from posthog.hogql import ast
@@ -59,6 +60,8 @@ _MATCHED_CONTENT_MAX_CHARS = 1500
# worker round trip.
_QUERY_VECTOR_CACHE_TTL_S = 3600
# Bound the synchronous embedding call: it pins a request thread, and a searcher will not wait longer.
+# requests applies this per read rather than to the whole response, so a worker that dribbles its body
+# out can still outlast it.
_EMBEDDING_TIMEOUT_S = 10.0
# The cosine-distance scan is exact (brute-force), so cap how many of a team's most-recent embedding rows it
# ranks over. Set well above realistic per-team volume so it only bites a runaway team, keeping latency
@@ -335,6 +338,17 @@ def _query_vector_cache_key(text: str) -> str:
return f"replay_vision:query_vector:{OBSERVATION_EMBEDDING_MODEL.value}:{digest}"
+def is_transient_embedding_error(error: Exception) -> bool:
+ """True for an embedding failure that a later call can clear, which is what a caller offers a retry for.
+
+ `ChunkedEncodingError` is what requests raises when the response body stops part way, so a worker that
+ dies mid-transfer belongs with the other transport failures despite the name. A 5xx is the worker itself
+ failing, so it joins them. A 4xx is a bad request, and a repeat of it is rejected the same way."""
+ if isinstance(error, requests.ConnectionError | requests.Timeout | requests.exceptions.ChunkedEncodingError):
+ return True
+ return isinstance(error, requests.HTTPError) and getattr(error.response, "status_code", 0) >= 500
+
+
def query_vector_for(team: Team, text: str) -> list[float]:
"""Embed search text, serving repeats from cache. Raises the embedding client's transport errors."""
key = _query_vector_cache_key(text)
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 025d94e4e1a4..37a7f4444289 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -3650,14 +3650,15 @@ class TestObservationSearchAction(_VisionAPITestCase):
# `requests` exceptions — an `httpx` mock here would exercise a handler that can never fire.
@parameterized.expand(
[
- ("unreachable", requests.ConnectionError),
- ("slow", requests.Timeout),
+ ("unreachable", requests.ConnectionError("embedding service down")),
+ ("slow", requests.Timeout("embedding service down")),
+ ("failing", requests.HTTPError("boom", response=MagicMock(status_code=502))),
]
)
- def test_search_returns_503_when_embedding_unavailable(self, _name: str, exception_class: type) -> None:
+ def test_search_returns_503_when_embedding_unavailable(self, _name: str, exception: Exception) -> None:
with patch(
"products.replay_vision.backend.search.generate_embedding",
- side_effect=exception_class("embedding service down"),
+ side_effect=exception,
):
resp = self.client.get(f"{self.search_url}?q=anything")
self.assertEqual(resp.status_code, 503)
diff --git a/products/replay_vision/frontend/search/observationSearchLogic.test.ts b/products/replay_vision/frontend/search/observationSearchLogic.test.ts
index 10f26254492d..268366764578 100644
--- a/products/replay_vision/frontend/search/observationSearchLogic.test.ts
+++ b/products/replay_vision/frontend/search/observationSearchLogic.test.ts
@@ -1,5 +1,6 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { urls } from 'scenes/urls'
@@ -155,6 +156,55 @@ describe('observationSearchLogic', () => {
logic.unmount()
})
+ it.each([
+ ['a failed', () => [500, { detail: 'embedding service down' }], { succeeded: false, error_status: 500 }],
+ ['a successful', undefined, { succeeded: true, result_count: 1 }],
+ ])('%s search is captured, so the failure rate is measurable', async (_name, mockResponse, expected) => {
+ if (mockResponse) {
+ searchSpy.mockImplementation(mockResponse as () => any)
+ }
+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
+ const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })
+ logic.mount()
+ router.actions.push(urls.replayVision(), { tab: 'search' })
+ logic.actions.setQuery('rage clicks')
+ await expectLogic(logic, () => logic.actions.search()).toFinishAllListeners()
+
+ expect(captureSpy).toHaveBeenCalledWith(
+ 'replay vision observation search completed',
+ expect.objectContaining({ ...expected, scope: 'cross-scanner' })
+ )
+ captureSpy.mockRestore()
+ logic.unmount()
+ })
+
+ it('a superseded failure is dropped, so the rate counts only the searches a person waited for', async () => {
+ searchSpy.mockImplementation(() => [500, { detail: 'embedding service down' }])
+ const captureSpy = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined as any)
+ const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')
+ const logic = observationSearchLogic({ scannerId: null, teamId: 1, userId: 'user-1' })
+ logic.mount()
+ router.actions.push(urls.replayVision(), { tab: 'search' })
+
+ logic.actions.setQuery('rage clicks')
+ logic.actions.search()
+ // The second search starts while the first request is in flight, which supersedes the first.
+ logic.actions.setQuery('coupon rejected at checkout')
+ logic.actions.search()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(searchSpy).toHaveBeenCalledTimes(2)
+ const outcomes = captureSpy.mock.calls.filter(
+ ([event]) => event === 'replay vision observation search completed'
+ )
+ expect(outcomes).toHaveLength(1)
+ expect(outcomes[0][1]).toMatchObject({ succeeded: false, error_status: 500 })
+ expect(toastSpy).toHaveBeenCalledTimes(1)
+ captureSpy.mockRestore()
+ toastSpy.mockRestore()
+ logic.unmount()
+ })
+
it('an AI consent error points the user at the organization setting', async () => {
searchSpy.mockImplementation(() => [400, { code: 'ai_data_processing_not_approved', detail: 'off' }])
const toastSpy = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')
diff --git a/products/replay_vision/frontend/search/observationSearchLogic.ts b/products/replay_vision/frontend/search/observationSearchLogic.ts
index 8020e6c1e2a5..8a1fc8e5dfe3 100644
--- a/products/replay_vision/frontend/search/observationSearchLogic.ts
+++ b/products/replay_vision/frontend/search/observationSearchLogic.ts
@@ -13,6 +13,7 @@ import {
} from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
@@ -128,6 +129,18 @@ export type observationSearchLogicType = MakeLogicType<
observationSearchLogicMeta
>
+// This event carries no query property. The text is free and can hold customer names or emails.
+// The `q` URL parameter still reaches analytics through `$current_url`, as it does for every event on this page.
+function captureSearchOutcome(
+ scannerId: string | null,
+ outcome: { succeeded: boolean; result_count?: number; error_status?: number; error_code?: string }
+): void {
+ posthog.capture('replay vision observation search completed', {
+ ...outcome,
+ scope: scannerId ? 'scanner' : 'cross-scanner',
+ })
+}
+
export const observationSearchLogic = kea<observationSearchLogicType>([
path(['products', 'replay_vision', 'frontend', 'search', 'observationSearchLogic']),
props({} as ObservationSearchLogicProps),
@@ -287,11 +300,21 @@ export const observationSearchLogic = kea<observationSearchLogicType>([
})
// Drop out-of-order responses. The newest search owns the results.
breakpoint()
- actions.searchSuccess(response.results ?? [], query, response.truncated ?? false)
+ const results = response.results ?? []
+ captureSearchOutcome(props.scannerId, { succeeded: true, result_count: results.length })
+ actions.searchSuccess(results, query, response.truncated ?? false)
} catch (error: any) {
if (error instanceof Error && isBreakpoint(error)) {
throw error
}
+ // Drop out-of-order failures, like the success path above. A newer search owns the outcome,
+ // so an older failure must not skew the capture, raise a toast, or stop the spinner.
+ breakpoint()
+ captureSearchOutcome(props.scannerId, {
+ succeeded: false,
+ error_status: error?.status,
+ error_code: error?.code,
+ })
if (error?.code === AI_CONSENT_REQUIRED_CODE) {
lemonToast.error('AI data processing is turned off for your organization.', {
button: {