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.

refactor(replay-vision): share the JSONB numeric cast, generalize the range pill (#81176)

Arno Hillen57007ba985b0
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index c0dd4c0ca870..0b0ffaf8aabc 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -6,7 +6,7 @@ from zoneinfo import ZoneInfo
from django.conf import settings
from django.db import transaction
-from django.db.models import Case, CharField, FloatField, Func, IntegerField, Q, QuerySet, Value, When
+from django.db.models import Case, IntegerField, Q, QuerySet, Value, When
from django.db.models.fields.json import KeyTextTransform, KeyTransform
from django.db.models.functions import Cast
from django.http.response import HttpResponseBase
@@ -48,6 +48,8 @@ from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
ReplayObservation,
+ annotate_output_number,
+ jsonb_typeof,
)
from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
@@ -65,30 +67,6 @@ from ee.hogai.utils.untrusted import as_untrusted_data
logger = structlog.get_logger(__name__)
-def _jsonb_typeof(expr: Any) -> Func:
- return Func(expr, function="JSONB_TYPEOF", output_field=CharField())
-
-
-def _annotate_output_number(qs: QuerySet[ReplayObservation], key: str, alias: str) -> QuerySet[ReplayObservation]:
- """Annotate `alias` with `scanner_result.model_output.<key>` as a float, null when the value isn't numeric.
-
- CASE-guard the cast so schema drift or a manual fixup (a `score` stored as a string) can't 500 the query.
- """
- type_alias = f"{alias}_type"
- value_jsonb = KeyTransform(key, KeyTransform("model_output", "scanner_result"))
- value_text = KeyTextTransform(key, KeyTextTransform("model_output", "scanner_result"))
- return qs.annotate(
- **{
- type_alias: _jsonb_typeof(value_jsonb),
- alias: Case(
- When(**{type_alias: "number"}, then=Cast(value_text, FloatField())),
- default=Value(None),
- output_field=FloatField(),
- ),
- }
- )
-
-
class ScannerSnapshotSerializer(serializers.Serializer):
"""Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation."""
@@ -484,17 +462,17 @@ class _ObservationOrderByFilter(OrderByFilter):
return self._order_nulls_last(qs, "label__is_correct", descending)
if key == "result_score":
return self._order_nulls_last(
- _annotate_output_number(qs, "score", "_order_score"), "_order_score", descending
+ annotate_output_number(qs, "score", "_order_score"), "_order_score", descending
)
if key == "result_confidence":
return self._order_nulls_last(
- _annotate_output_number(qs, "confidence", "_order_confidence"), "_order_confidence", descending
+ annotate_output_number(qs, "confidence", "_order_confidence"), "_order_confidence", descending
)
if key == "scanner_version":
version_jsonb = KeyTransform("scanner_version", "scanner_snapshot")
version_text = KeyTextTransform("scanner_version", "scanner_snapshot")
qs = qs.annotate(
- _version_type=_jsonb_typeof(version_jsonb),
+ _version_type=jsonb_typeof(version_jsonb),
_order_version=Case(
When(_version_type="number", then=Cast(version_text, IntegerField())),
default=Value(None),
@@ -648,7 +626,7 @@ class ReplayObservationFilter(django_filters.FilterSet):
# min_score and max_score can arrive together, and re-annotating the same alias raises.
if _SCORE_FILTER_ALIAS in queryset.query.annotations:
return queryset
- return _annotate_output_number(queryset, "score", _SCORE_FILTER_ALIAS)
+ return annotate_output_number(queryset, "score", _SCORE_FILTER_ALIAS)
# Both bounds look up the annotation `_scored` adds, via a literal key in a `**` dict: a plain
# keyword can't be used because django-stubs resolves those against the model's real fields.
diff --git a/products/replay_vision/backend/impact.py b/products/replay_vision/backend/impact.py
index 474823f87c7c..a0d029e34404 100644
--- a/products/replay_vision/backend/impact.py
+++ b/products/replay_vision/backend/impact.py
@@ -3,15 +3,18 @@
from dataclasses import dataclass
from datetime import timedelta
-from django.db.models import Case, CharField, Count, FloatField, Func, Q, QuerySet, Value, When
-from django.db.models.fields.json import KeyTextTransform, KeyTransform
-from django.db.models.functions import Cast, Coalesce
+from django.db.models import Count, Q, QuerySet
+from django.db.models.functions import Coalesce
from django.utils import timezone
from posthog.models.user import User
from products.cohorts.backend.models.cohort import Cohort
-from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ReplayObservation,
+ annotate_output_number,
+)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
DEFAULT_IMPACT_WINDOW_DAYS = 30
@@ -75,21 +78,12 @@ def affected_observations(
raise ValueError("Scorers don't produce tags; use `min_score`/`max_score` instead.")
if not has_scores:
raise ValueError("Scorer impact requires `min_score` and/or `max_score`.")
- score_jsonb = KeyTransform("score", KeyTransform("model_output", "scanner_result"))
- score_text = KeyTextTransform("score", KeyTextTransform("model_output", "scanner_result"))
- # CASE-guard the cast so a non-numeric score (schema drift) doesn't 500 the query.
- qs = base.annotate(
- _score_type=Func(score_jsonb, function="jsonb_typeof", output_field=CharField()),
- _score=Case(
- When(_score_type="number", then=Cast(score_text, FloatField())),
- default=Value(None),
- output_field=FloatField(),
- ),
- )
+ qs = annotate_output_number(base, "score", "_score")
+ # Literal dict keys: django-stubs can't see the helper's annotation, so plain kwargs fail mypy.
if min_score is not None:
- qs = qs.filter(_score__gte=min_score)
+ qs = qs.filter(**{"_score__gte": min_score})
if max_score is not None:
- qs = qs.filter(_score__lte=max_score)
+ qs = qs.filter(**{"_score__lte": max_score})
return qs
raise ValueError(f"Impact is not available for {scanner_type} scanners.")
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.py
index 9a348dc1c0d4..7bcd8dd6d150 100644
--- a/products/replay_vision/backend/models/replay_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -1,4 +1,7 @@
from django.db import models
+from django.db.models import Case, CharField, Expression, FloatField, Func, Value, When
+from django.db.models.fields.json import KeyTextTransform, KeyTransform
+from django.db.models.functions import Cast
from posthog.models.utils import UUIDModel
@@ -160,3 +163,29 @@ class ReplayObservation(UUIDModel):
def __str__(self) -> str:
return f"{self.scanner_id}:{self.session_id} [{self.status}]"
+
+
+def jsonb_typeof(expr: Expression) -> Func:
+ return Func(expr, function="JSONB_TYPEOF", output_field=CharField())
+
+
+def annotate_output_number(
+ qs: "models.QuerySet[ReplayObservation]", key: str, alias: str
+) -> "models.QuerySet[ReplayObservation]":
+ """Annotate `alias` with `scanner_result.model_output.<key>` as a float, null when the value isn't numeric.
+
+ CASE-guard the cast so schema drift or a manual fixup (a `score` stored as a string) can't 500 the query.
+ """
+ type_alias = f"{alias}_type"
+ value_jsonb = KeyTransform(key, KeyTransform("model_output", "scanner_result"))
+ value_text = KeyTextTransform(key, KeyTextTransform("model_output", "scanner_result"))
+ return qs.annotate(
+ **{
+ type_alias: jsonb_typeof(value_jsonb),
+ alias: Case(
+ When(**{type_alias: "number"}, then=Cast(value_text, FloatField())),
+ default=Value(None),
+ output_field=FloatField(),
+ ),
+ }
+ )
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 3054ae67173a..2ab6fdcda110 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -1613,6 +1613,16 @@ class TestReplayObservationViewSet(_VisionAPITestCase):
self.assertEqual(resp.status_code, 200, resp.json())
self.assertEqual([r["session_id"] for r in resp.json()["results"]], ["sess-1", "sess-3", "sess-0"])
+ def test_stats_respect_score_bounds(self) -> None:
+ # The scorer stats embed the filtered queryset into raw SQL, so the annotation-based
+ # filter must survive that path, not just the plain list.
+ scorer = self._create_scorer_with_scores([3.0, 10.0, 0.5, 7.0])
+ resp = self.client.get(f"{self.observations_url(str(scorer.id))}stats/?min_score=7")
+ self.assertEqual(resp.status_code, 200, resp.json())
+ body = resp.json()
+ self.assertEqual(body["status_counts"]["total"], 2)
+ self.assertEqual(body["status_counts"]["succeeded"], 2)
+
def test_order_by_scanner_version_numeric(self) -> None:
snap_v1 = {**_snapshot_for(self.scanner), "scanner_version": 1}
snap_v2 = {**_snapshot_for(self.scanner), "scanner_version": 2}
@@ -2595,6 +2605,36 @@ class TestSessionReplayObservationViewSet(_VisionAPITestCase):
self.assertEqual(filtered["next_observation_id"], str(old.id))
self.assertIsNone(filtered["previous_observation_id"])
+ def test_retrieve_neighbors_honor_score_bounds(self) -> None:
+ scorer = self._create_scanner(
+ name="frustration",
+ scanner_type=ScannerType.SCORER,
+ scanner_config={"prompt": "p", "scale": {"min": 0, "max": 10}},
+ )
+ now = timezone.now()
+ ids = []
+ # created_at ascends with idx, so the default -created_at listing is sess-2, sess-1, sess-0.
+ for idx, score in enumerate([9.0, 2.0, 8.0]):
+ obs = self._create_observation(scorer, f"sess-{idx}")
+ ReplayObservation.objects.filter(pk=obs.id).update(
+ created_at=now - timedelta(minutes=2 - idx),
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=now,
+ scanner_result={
+ "model_output": {"scanner_type": "scorer", "score": score, "reasoning": "r", "confidence": 0.5},
+ "signals_count": 0,
+ },
+ )
+ ids.append(obs.id)
+
+ unfiltered = self.client.get(f"{self.session_observations_url}{ids[2]}/").json()
+ self.assertEqual(unfiltered["next_observation_id"], str(ids[1]))
+
+ # min_score=7 drops the 2.0 row, so next skips to the 9.0 row.
+ filtered = self.client.get(f"{self.session_observations_url}{ids[2]}/?min_score=7").json()
+ self.assertEqual(filtered["next_observation_id"], str(ids[0]))
+ self.assertIsNone(filtered["previous_observation_id"])
+
def test_retrieve_neighbors_honor_order_by(self) -> None:
now = timezone.now()
old = self._create_observation(self.scanner_a, "s-old")
diff --git a/products/replay_vision/frontend/components/NumericRangeFilterPill.test.ts b/products/replay_vision/frontend/components/NumericRangeFilterPill.test.ts
new file mode 100644
index 000000000000..622bab972bff
--- /dev/null
+++ b/products/replay_vision/frontend/components/NumericRangeFilterPill.test.ts
@@ -0,0 +1,31 @@
+import { numericRangeLabel, toNumericBound } from './NumericRangeFilterPill'
+
+describe('NumericRangeFilterPill', () => {
+ describe('toNumericBound', () => {
+ it('passes finite numbers through, including 0', () => {
+ expect(toNumericBound(7)).toBe(7)
+ expect(toNumericBound(0)).toBe(0)
+ expect(toNumericBound(-1.5)).toBe(-1.5)
+ })
+
+ it('maps a cleared input (NaN) to null', () => {
+ // LemonInput type="number" reports an empty field as NaN via valueAsNumber
+ expect(toNumericBound(NaN)).toBeNull()
+ })
+
+ it('maps undefined and non-finite values to null', () => {
+ expect(toNumericBound(undefined)).toBeNull()
+ expect(toNumericBound(Infinity)).toBeNull()
+ expect(toNumericBound(-Infinity)).toBeNull()
+ })
+ })
+
+ describe('numericRangeLabel', () => {
+ it('covers all four bound states', () => {
+ expect(numericRangeLabel('Score', null, null)).toBe('Score')
+ expect(numericRangeLabel('Score', 3, null)).toBe('Score ≥ 3')
+ expect(numericRangeLabel('Score', null, 8)).toBe('Score ≤ 8')
+ expect(numericRangeLabel('Score', 3, 8)).toBe('Score 3 to 8')
+ })
+ })
+})
diff --git a/products/replay_vision/frontend/components/ScoreRangeFilterPill.tsx b/products/replay_vision/frontend/components/NumericRangeFilterPill.tsx
similarity index 73%
rename from products/replay_vision/frontend/components/ScoreRangeFilterPill.tsx
rename to products/replay_vision/frontend/components/NumericRangeFilterPill.tsx
index 62144155338c..2c69ec1dbd35 100644
--- a/products/replay_vision/frontend/components/ScoreRangeFilterPill.tsx
+++ b/products/replay_vision/frontend/components/NumericRangeFilterPill.tsx
@@ -1,47 +1,51 @@
import { LemonButton, LemonButtonWithDropdown, LemonInput } from '@posthog/lemon-ui'
/** Compact summary for the pill face, so an active range is readable without opening the dropdown. */
-export function scoreRangeLabel(min: number | null, max: number | null): string {
+export function numericRangeLabel(label: string, min: number | null, max: number | null): string {
if (min !== null && max !== null) {
- return `Score ${min} to ${max}`
+ return `${label} ${min} to ${max}`
}
if (min !== null) {
- return `Score ≥ ${min}`
+ return `${label} ≥ ${min}`
}
if (max !== null) {
- return `Score ≤ ${max}`
+ return `${label} ≤ ${max}`
}
- return 'Score'
+ return label
}
/** LemonInput type="number" reports an empty field as NaN, so treat anything non-finite as unset. */
-export function toScoreBound(raw: number | undefined): number | null {
+export function toNumericBound(raw: number | undefined): number | null {
return typeof raw === 'number' && Number.isFinite(raw) ? raw : null
}
/**
- * Bounds filter for a scorer's numeric result. Two open-ended inputs rather than an operator
+ * Bounds filter for a numeric observation field. Two open-ended inputs rather than an operator
* dropdown, because that covers "at least", "at most", and a range without a mode to pick first.
*/
-export function ScoreRangeFilterPill({
+export function NumericRangeFilterPill({
+ label,
min,
max,
scaleMin,
scaleMax,
onChange,
+ dataAttr,
}: {
+ label: string
min: number | null
max: number | null
- /** The scanner's configured scale, used as input bounds and as placeholder hints. */
+ /** The field's configured scale, used as input bounds and as placeholder hints. */
scaleMin?: number
scaleMax?: number
onChange: (min: number | null, max: number | null) => void
+ dataAttr?: string
}): JSX.Element {
return (
<LemonButtonWithDropdown
type="secondary"
size="small"
- data-attr="vision-observations-score-filter"
+ data-attr={dataAttr}
dropdown={{
closeOnClickInside: false,
overlay: (
@@ -54,8 +58,8 @@ export function ScoreRangeFilterPill({
min={scaleMin}
max={scaleMax}
placeholder={scaleMin !== undefined ? String(scaleMin) : undefined}
- value={min ?? undefined}
- onChange={(value) => onChange(toScoreBound(value), max)}
+ value={min ?? NaN}
+ onChange={(value) => onChange(toNumericBound(value), max)}
className="flex-1"
/>
</div>
@@ -67,8 +71,8 @@ export function ScoreRangeFilterPill({
min={scaleMin}
max={scaleMax}
placeholder={scaleMax !== undefined ? String(scaleMax) : undefined}
- value={max ?? undefined}
- onChange={(value) => onChange(min, toScoreBound(value))}
+ value={max ?? NaN}
+ onChange={(value) => onChange(min, toNumericBound(value))}
className="flex-1"
/>
</div>
@@ -77,7 +81,9 @@ export function ScoreRangeFilterPill({
fullWidth
center
onClick={() => onChange(null, null)}
- disabledReason={min === null && max === null ? 'No score filter set' : undefined}
+ disabledReason={
+ min === null && max === null ? `No ${label.toLowerCase()} filter set` : undefined
+ }
>
Clear
</LemonButton>
@@ -85,7 +91,7 @@ export function ScoreRangeFilterPill({
),
}}
>
- {scoreRangeLabel(min, max)}
+ {numericRangeLabel(label, min, max)}
</LemonButtonWithDropdown>
)
}
diff --git a/products/replay_vision/frontend/components/ScoreRangeFilterPill.test.ts b/products/replay_vision/frontend/components/ScoreRangeFilterPill.test.ts
deleted file mode 100644
index 7d6a6d2a6588..000000000000
--- a/products/replay_vision/frontend/components/ScoreRangeFilterPill.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { scoreRangeLabel, toScoreBound } from './ScoreRangeFilterPill'
-
-describe('toScoreBound', () => {
- it('passes finite numbers through, including 0', () => {
- expect(toScoreBound(7)).toBe(7)
- expect(toScoreBound(0)).toBe(0)
- expect(toScoreBound(-1.5)).toBe(-1.5)
- })
-
- it('maps a cleared input (NaN) to null', () => {
- // LemonInput type="number" reports an empty field as NaN via valueAsNumber
- expect(toScoreBound(NaN)).toBeNull()
- })
-
- it('maps undefined and non-finite values to null', () => {
- expect(toScoreBound(undefined)).toBeNull()
- expect(toScoreBound(Infinity)).toBeNull()
- expect(toScoreBound(-Infinity)).toBeNull()
- })
-})
-
-describe('scoreRangeLabel', () => {
- it('covers all four bound states', () => {
- expect(scoreRangeLabel(null, null)).toBe('Score')
- expect(scoreRangeLabel(3, null)).toBe('Score ≥ 3')
- expect(scoreRangeLabel(null, 8)).toBe('Score ≤ 8')
- expect(scoreRangeLabel(3, 8)).toBe('Score 3 to 8')
- })
-})
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
index bd4a99d181c2..ee0138b27fda 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
@@ -12,9 +12,9 @@ import { urls } from 'scenes/urls'
import { DateMappingOption } from '~/types'
import { FilterPill } from '../../components/FilterPill'
+import { NumericRangeFilterPill } from '../../components/NumericRangeFilterPill'
import { ObservationResultSummary, ObservationStatusTag } from '../../components/ObservationCard'
import { ObservationRetryButton } from '../../components/ObservationRetryButton'
-import { ScoreRangeFilterPill } from '../../components/ScoreRangeFilterPill'
import type { ReplayObservationApi } from '../../generated/api.schemas'
import { observationDetailUrl } from '../../observations/replayObservationLogic'
import {
@@ -289,12 +289,14 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):
/>
)}
{scannerType === 'scorer' && (
- <ScoreRangeFilterPill
+ <NumericRangeFilterPill
+ label="Score"
min={observationMinScoreFilter}
max={observationMaxScoreFilter}
scaleMin={scoreScale?.min}
scaleMax={scoreScale?.max}
onChange={setObservationScoreRange}
+ dataAttr="vision-observations-score-filter"
/>
)}
{scannerType === 'classifier' && tagFilterOptions.length > 0 && (
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index ed7e257ccbce..61d4be1ee575 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -741,6 +741,19 @@ describe('replayScannerLogic', () => {
expect(String(router.values.searchParams.page)).toBe('3')
})
+ it('round-trips score bounds through the URL without swapping min and max', async () => {
+ await expectLogic(scannedLogic, () => {
+ scannedLogic.actions.setObservationScoreRange(3, 8)
+ }).toFinishAllListeners()
+ expect(String(router.values.searchParams.min_score)).toBe('3')
+ expect(String(router.values.searchParams.max_score)).toBe('8')
+
+ router.actions.push(urls.replayVision('sid'), { min_score: 7, max_score: 9 })
+ await expectLogic(scannedLogic).toFinishAllListeners()
+ expect(scannedLogic.values.observationMinScoreFilter).toBe(7)
+ expect(scannedLogic.values.observationMaxScoreFilter).toBe(9)
+ })
+
it('drops default state from the URL', async () => {
await expectLogic(scannedLogic, () => {
scannedLogic.actions.setObservationsPage(1)
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 072ad5d295d8..ef81863dc1e6 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -1607,7 +1607,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
setObservationVerdictFilter: () => reloadObservationsAndStats(),
setObservationTagFilter: () => reloadObservationsAndStats(),
setObservationScoreRange: async (_, breakpoint) => {
- // Typed into number inputs — debounce so each keystroke of "10" doesn't fire its own request.
+ // Typed into number inputs; debounce so each keystroke of "10" does not fire its own request.
await breakpoint(300)
reloadObservationsAndStats()
},