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): semantic search summaries (#81980)

Hayne Ryubc1f34c21026
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 337f0f0f8c8d..0c228f10b5e7 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7675,23 +7675,23 @@ snapshots:
scenes-app-replay-vision--scanner-calibration--dark:
hash: v1.k794b7964.552e7aeeaa303f346e08cc00e50e01e8ae73b11037189f30ee352c2539c079cc.netD6AKXfx9ScvYD3N4ZNR4wxXAKdtRUxavYrnrURTA
scenes-app-replay-vision--scanner-calibration--light:
- hash: v1.k794b7964.052104891cea7a902b874826c922e3688d23053b0ebb2128b1c0dbca7ab2a32b.LofDLlNAhm2-XL4aPULNJ7Wwduy_ZItRnWWQdAvir1k
+ hash: v1.k794b7964.5f789c567e58a3cd35605bf065c1a9255d95f83165b949187f5d01e7acb4c160.0GgyP2BXCRlcNhWwh6XBCc4BuwIEtTyCgQuuhxgE-hg
scenes-app-replay-vision--scanner-configuration--dark:
- hash: v1.k794b7964.6ccd7edeaa1ca21973cdd4db3c9270adfba38841de505035a3450b485ee0accd.0_nUNj0v4Xv_lV4FsJIMxePHpu3lv4jgfcNh0VMxvsI
+ hash: v1.k794b7964.5aef47cd525ba7221271cb6410b02da46828082fe5a1db36bb488b423f56437e.1QAwMoNXCezsVD3-7Ku7yF6dJ8oY7DDM9_p2ryIUJNs
scenes-app-replay-vision--scanner-configuration--light:
- hash: v1.k794b7964.7b4aac492018e4b4b7e267ea6b9eb3afdca3bdb380cffe217c3a35ca115633f7.aNrewc17QuCb7XiC_K2d6_2o3LbvWZ_V7K1mogzASbg
+ hash: v1.k794b7964.4266104722d3421ed510869f79a6e560b935154515f198434c7b91227170edee.hayqLplWOzESW4aaYZKAP79HxpyAdO6oHlSL3vzc1xE
scenes-app-replay-vision--scanner-configuration-lite-standard-pro--dark:
- hash: v1.k794b7964.9178a54f8ed46d377a064544b3a715566d9f5d26a86d47873c0b05e56cbaeeb7._hSa4Mpof7PAwqz8pymlqsZSitkrhp77OVc92KVb0W8
+ hash: v1.k794b7964.05172f889023334afb1fddcc58c3eb170344899a1eb32e4c8f85ecab3529bc84.5X8XonSfuJMU6ug2AsCwHXOK2rNTnPBw7rhnQu4z5C4
scenes-app-replay-vision--scanner-configuration-lite-standard-pro--light:
- hash: v1.k794b7964.2b25fe709d4ed8209b695ceb99502831f7a824a1265255064b94c45be897d47f.-QU4HBV07wI8N4xj_twCWqRkecqxjVzepmnIbs8lsP0
+ hash: v1.k794b7964.fe47b567472aca099287254f0fc3e0b65c74693b2ad9edb3b7ba82ca01bb12ea.X5_Z4WXF1XMmjV3dFGzRvQG21G7IQpDZT4KLewDQszU
scenes-app-replay-vision--scanner-configuration-tier-names--dark:
- hash: v1.k794b7964.1cbb6ff2103365a2c2c0b4a250c25f518667ccdd3ec579bac44f0edb841d3fc7.z5RZjRLvjPqlt7Koy61ANS_3C67zOHP7Mc7FvKGucP0
+ hash: v1.k794b7964.ed44783674d2aa014cbc884127c06f48472f95affa90a77d14a552d98e5bf02a.YJH8P86Vimm3Db3ncEsyvtmEgkUOYYOj7dDxJJhoq1E
scenes-app-replay-vision--scanner-configuration-tier-names--light:
- hash: v1.k794b7964.1b3757504deeeb68d21ffdab3f8ca532a0aed50f0c898876b550d7de862cb238.TssiDaxgE6EHc1ssQ8lIwO8gatmYG8g9MrhHleNZ6Xs
+ hash: v1.k794b7964.7c7692624d6a13ed669aad1d9f104593c63ba92be2a8b7ac85f2043e9996e65f.fKTECnVqB2iTH1EgtFlG2XXd4OpY7KEfQfPTEzCj0uw
scenes-app-replay-vision--scanner-digests--dark:
- hash: v1.k794b7964.cfb6e46fefd93430d17c650dfceeb62bc813855dd034c2a815db8559686dbeab.4iB6ZrgxCuEO7AoLgZCuqcAMX6eqMa42Fn3j6N6n5Xg
+ hash: v1.k794b7964.ddee2b8f57aaf57e689892befa66005662738f66ae96bbb93983aa143d87ef6a.G9z4gqIEcRspPtgOoldwNywiZEN9bAFSv5ATG2x2rIY
scenes-app-replay-vision--scanner-digests--light:
- hash: v1.k794b7964.7160d1eb03abff790b4ed77db80e5913c3359d80bca9d7f6863321575816e639.Qq99zfKOxqgP8Eu0DmH_s3K_ekEAOzo8VZe7TZVn67I
+ hash: v1.k794b7964.ee2d72857663580a0b80f8843cfacb67140875121f24b6930c88216f9a6221a1.tgkD9mpOzzN03lVkzZrO7ef20O2pWDA5EUj7y2ZnsYI
scenes-app-replay-vision--scanner-editor-budget--dark:
hash: v1.k794b7964.37379538a705b9cfdaae3992ffbb357d3f7277abc9b77000c37e5d65d2d9a182.tIr_lkCBHvvxOjUsNFJ_VwNzAkD_MY2q-fN7anGin90
scenes-app-replay-vision--scanner-editor-budget--light:
@@ -7717,13 +7717,13 @@ snapshots:
scenes-app-replay-vision--scanner-editor-triggers--light:
hash: v1.k794b7964.1325a276c040c4fdec27fd9d75ecde45e08d343f4e76806a03819747f4c52973.6k8EbsIyUMKtWUuUvV-ElrJCGK5_-iSXLT4bi_fp3Gg
scenes-app-replay-vision--scanner-observations--dark:
- hash: v1.k794b7964.836bbeb03dc8a6a02c7489875920b0e0098cc696580490eb7163b36eb8e835f3.r_NXe4vOXdXkB7NxFQuoq9N4a3BlD6DMwP5HHCX4c70
+ hash: v1.k794b7964.1c4f12edea407ace873a4bf2adc1d5221fbebe6b69dda32714336cbd4eaf92ce.RYiMHfZAt3C3lo5Vf7pi2vNZzuL25UjOe7l2_aDUra4
scenes-app-replay-vision--scanner-observations--light:
- hash: v1.k794b7964.1fab12ebf8c2d2d1e08b0e3227e7bad181d9e2ceae48887dc31e9e69a8cbd8bb.sXQJChzPj8ntCrbu1aAZWuxpu9OJYBbOINykErLaeQo
+ hash: v1.k794b7964.f0551bd49f4f37ff94a346960a244b02dbdbe6798826c7c53c4d5541ebe99e74.7zBopcC7VvU8XUZehEBxzdUHTxfM1m64uoZcBXkMlXo
scenes-app-replay-vision--scanner-on-demand--dark:
- hash: v1.k794b7964.28d2e6262234073c713fa9d589a87c901380463ee20c3a716ef64d61fec1b838.0KN54tARtI6lbifsHuYDgc7wHtMokFDGIEOWVLJ-HSk
+ hash: v1.k794b7964.2a0ea0198da6166d9fb3daf278d4de9b3ec80a0e8b9234cf8a831c12424fb7d0.awEhTQe1f-gzSwOsUJz_uv7FaRwajBLmO-pgng3Gs9U
scenes-app-replay-vision--scanner-on-demand--light:
- hash: v1.k794b7964.c7fb3bef0e6746a00dee5acf2ea13684f9ceaafbf719a292c7c83ba6f1e66ce0.wXTvBQVYYqTn1h9VeKathC07umJLHQVSRaSI95Ddupo
+ hash: v1.k794b7964.d6b1a876ab50b940e9bcbe27164922f5c564a01c25c56bbc8955255a2d47173f.DOdeCbLwHWJmW1H1uAYkxdvHS2rpSR6froY4FXuOW7s
scenes-app-replay-vision--scanner-scan-drought--dark:
hash: v1.k794b7964.76130f9b73097aff10e53cb7edf5f4b90a445c5cc67c7979c3dffeac0d015b85.pJLj_cTQ5R0crsCU5AfXRXX5YgFBAMTPW50F_cfPgLU
scenes-app-replay-vision--scanner-scan-drought--light:
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index bb2c37f1abe0..28d1cae3d5eb 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -536,6 +536,23 @@ class _TeamBucketRateThrottle(PersonalApiKeyOrUserRateThrottle):
return self.cache_format % {"scope": self.scope, "ident": ident}
+class _UserBucketRateThrottle(PersonalApiKeyOrUserRateThrottle):
+ """One bucket per credential (personal API key hash, else user) even on team-scoped views, for
+ endpoints where one user must not be able to drain the whole team's budget.
+
+ The parent's cache key idents a session-authenticated request on a team view by team id, which
+ would collapse every member of the team into one bucket.
+ """
+
+ def get_cache_key(self, request: "Request", view: "APIView") -> str:
+ if request.user.is_authenticated:
+ api_key = PersonalAPIKeyAuthentication.find_key_with_source(request, request_data={})
+ ident = hash_key_value(api_key[0]) if api_key is not None else request.user.pk
+ else:
+ ident = self.get_ident(request)
+ return self.cache_format % {"scope": self.scope, "ident": ident}
+
+
# The heatmap page pre-flight makes one outbound fetch of a caller-supplied page per uncached probe,
# holding a web worker for as long as that page takes to answer, so its budget is about worker
# occupancy rather than about protecting our own datastores. A legitimate caller needs one probe per
@@ -667,6 +684,21 @@ class ReplayVisionEstimateSustainedRateThrottle(_TeamBucketRateThrottle):
rate = "200/hour"
+# Each observation search makes a synchronous embedding request and a brute-force cosine scan over
+# the team's embedding rows, and its primary caller is the session-authenticated Search tab, which
+# the default Burst/Sustained throttles bypass. The burst bucket is per credential so one user
+# iterating on queries can't lock the Search tab for the rest of the team; the sustained bucket is
+# per team so the total spend stays capped regardless of how many users or keys share it.
+class ReplayVisionSearchBurstRateThrottle(_UserBucketRateThrottle):
+ scope = "replay_vision_search_burst"
+ rate = "30/minute"
+
+
+class ReplayVisionSearchSustainedRateThrottle(_TeamBucketRateThrottle):
+ scope = "replay_vision_search_sustained"
+ rate = "300/hour"
+
+
class _AIThrottleBase(UserRateThrottle):
action_name: str
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index 56e4d75f5945..75d277e22f23 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -34,7 +34,7 @@
e.`$window_id` AS `$window_id`,
if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
if(equals(e.event, 'user did things'), 1, 0) AS step_1,
- ([e__person.properties___fish] AS value) AS prop_basic,
+ ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,
prop_basic AS prop
FROM events AS e
LEFT OUTER JOIN
@@ -44,16 +44,6 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -121,17 +111,7 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
GROUP BY breakdown
@@ -188,8 +168,8 @@
e.uuid AS uuid,
e.`$session_id` AS `$session_id`,
e.`$window_id` AS `$window_id`,
- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_0,
- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_1
+ if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,
+ if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1
FROM events AS e
LEFT OUTER JOIN
(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
@@ -198,16 +178,6 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -324,24 +294,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -373,24 +326,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 496b41419704..75bcfa4f8d53 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -1,4 +1,5 @@
import json
+import math
import uuid
from dataclasses import dataclass
from typing import Any, cast, get_args
@@ -11,6 +12,7 @@ from django.db.models.fields.json import KeyTextTransform, KeyTransform
from django.db.models.functions import Cast
from django.http.response import HttpResponseBase
+import requests
import structlog
import django_filters
from django_filters.rest_framework import DjangoFilterBackend
@@ -24,24 +26,27 @@ from drf_spectacular.utils import (
from pydantic import ValidationError as PydanticValidationError
from rest_framework import mixins, serializers, status, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound, PermissionDenied, Throttled, ValidationError
+from rest_framework.exceptions import APIException, NotFound, PermissionDenied, Throttled, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
+from posthog.api.embedding_worker import generate_embedding
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.streaming import sse_streaming_response
from posthog.event_usage import report_user_action
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.rate_limit import ReplayVisionSearchBurstRateThrottle, ReplayVisionSearchSustainedRateThrottle
from posthog.renderers import ServerSentEventRenderer
from posthog.utils import relative_date_parse
from products.replay_vision.backend.api.errors import ReplayVisionErrorSerializer
-from products.replay_vision.backend.api.filters import MultiChoiceFilter, OrderByFilter, ordering_enum
+from products.replay_vision.backend.api.filters import MultiChoiceFilter, OrderByFilter, ordering_enum, split_csv
from products.replay_vision.backend.api.observation_progress import stream_observation_progress
from products.replay_vision.backend.api.observation_stats import compute_observation_stats
from products.replay_vision.backend.consent import is_ai_data_processing_approved
+from products.replay_vision.backend.embeddings import OBSERVATION_EMBEDDING_MODEL
from products.replay_vision.backend.error_kinds import ERROR_REASON_HELP_TEXT
from products.replay_vision.backend.models.replay_observation import (
IN_FLIGHT_STATUSES,
@@ -60,6 +65,14 @@ from products.replay_vision.backend.scanner_access import (
scanner_for_reading_observations,
)
from products.replay_vision.backend.scanning import RetryOutcome, retry_observation
+from products.replay_vision.backend.search import (
+ DEFAULT_SEARCH_LIMIT,
+ MAX_SEARCH_LIMIT,
+ RANK_OVERFETCH_FACTOR,
+ ObservationSearchFilters,
+ fetch_ranked_observations,
+ rank_observations,
+)
from products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdict
from products.replay_vision.backend.temporal.types import ScannerResult, ScannerSnapshot
from products.tasks.backend.facade import api as tasks_facade
@@ -69,6 +82,14 @@ from ee.hogai.utils.untrusted import as_untrusted_data
logger = structlog.get_logger(__name__)
+class EmbeddingUnavailableError(APIException):
+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE
+ default_detail = (
+ "Search is unavailable right now because the embedding service didn't respond. Try again in a moment."
+ )
+ default_code = "embedding_unavailable"
+
+
class ScannerSnapshotSerializer(serializers.Serializer):
"""Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation."""
@@ -1065,6 +1086,92 @@ class ReplayObservationViewSet(
return Response(ReplayObservationLabelSerializer(label).data)
+class ObservationSearchQuerySerializer(serializers.Serializer):
+ q = serializers.CharField(
+ max_length=2000,
+ help_text="Natural-language description of what to find, e.g. 'users confused by the pricing page'.",
+ )
+ scanner_id = serializers.UUIDField(
+ required=False,
+ help_text="Search a single scanner's observations. Defaults to every scanner you can read.",
+ )
+ verdict = serializers.CharField(
+ required=False,
+ help_text="Comma-separated monitor verdicts to keep, e.g. `yes,inconclusive`.",
+ )
+ tags = serializers.CharField(
+ required=False,
+ help_text="Comma-separated classifier tags to keep. Matching is case- and format-insensitive. "
+ "Unlike `verdict`, tags are not validated against a fixed list, so an unknown tag matches nothing.",
+ )
+ min_score = serializers.FloatField(
+ required=False, help_text="Keep only scorer observations with a score at or above this value."
+ )
+ max_score = serializers.FloatField(
+ required=False, help_text="Keep only scorer observations with a score at or below this value."
+ )
+ limit = serializers.IntegerField(
+ required=False,
+ min_value=1,
+ max_value=MAX_SEARCH_LIMIT,
+ default=DEFAULT_SEARCH_LIMIT,
+ help_text=f"Maximum number of results (default {DEFAULT_SEARCH_LIMIT}, at most {MAX_SEARCH_LIMIT}).",
+ )
+
+ def validate_verdict(self, value: str) -> str:
+ # Same contract as the list endpoint's verdict filter: an unknown verdict is a 400, not a silent empty result.
+ invalid = sorted({v for v in split_csv(value) if v not in _MONITOR_VERDICTS})
+ if invalid:
+ raise serializers.ValidationError(f"Invalid value(s) {invalid}; allowed: {sorted(_MONITOR_VERDICTS)}.")
+ return value
+
+ def validate_min_score(self, value: float) -> float:
+ return self._finite_score(value)
+
+ def validate_max_score(self, value: float) -> float:
+ return self._finite_score(value)
+
+ @staticmethod
+ def _finite_score(value: float) -> float:
+ # FloatField accepts `nan` and `inf`, which would reach the ClickHouse parameter binding.
+ if not math.isfinite(value):
+ raise serializers.ValidationError("Must be a finite number.")
+ return value
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ min_score, max_score = attrs.get("min_score"), attrs.get("max_score")
+ # An empty-by-construction range is a caller mistake; a 400 here is cheaper than an embedding
+ # call plus a ClickHouse scan that can only return nothing.
+ if min_score is not None and max_score is not None and min_score > max_score:
+ raise serializers.ValidationError("`min_score` cannot be greater than `max_score`.")
+ return attrs
+
+
+class ObservationSearchResultSerializer(serializers.Serializer):
+ observation = ReplayObservationSerializer(help_text="The matching observation.")
+ distance = serializers.FloatField(
+ help_text="Cosine distance between the search text and the observation's closest embedding. Lower is a "
+ "closer match. Only comparable to other results in the same response.",
+ )
+ matched_content = serializers.CharField(
+ allow_blank=True,
+ help_text="Excerpt of the observation text that best matched the search, truncated. Empty for "
+ "observations analyzed before excerpts were stored.",
+ )
+
+
+class ObservationSearchResponseSerializer(serializers.Serializer):
+ results = ObservationSearchResultSerializer(many=True, help_text="Matching observations, most relevant first.")
+ truncated = serializers.BooleanField(
+ help_text="True when more matches may exist beyond `results`, so the response is a top slice "
+ "rather than everything that matched."
+ )
+
+
+def _csv_values(raw: str | None) -> list[str] | None:
+ return split_csv(raw) or None if raw else None
+
+
@extend_schema_view(
list=extend_schema(
parameters=[
@@ -1079,7 +1186,8 @@ class ReplayObservationViewSet(
),
)
class SessionReplayObservationViewSet(ReplayObservationViewSet):
- """Read-only access to a session's observations across every scanner the caller can read, for the replay-page dock."""
+ """A session's observations across every scanner the caller can read, plus the team-level semantic
+ `search` action, which resolves its own scanner scope instead of this queryset."""
# The dock fetches one session's observations; `session_id` is required and enforced in
# safely_get_queryset, so this viewset needs none of the base's optional list filters.
@@ -1115,6 +1223,102 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
def stats(self, request: Request, **kwargs: Any) -> Response: # type: ignore[override]
raise NotFound()
+ @extend_schema(
+ parameters=[ObservationSearchQuerySerializer],
+ responses={
+ 200: ObservationSearchResponseSerializer,
+ 503: OpenApiResponse(
+ response=ReplayVisionErrorSerializer, description="The embedding service did not respond."
+ ),
+ },
+ )
+ @action(
+ detail=False,
+ methods=["GET"],
+ throttle_classes=[ReplayVisionSearchBurstRateThrottle, ReplayVisionSearchSustainedRateThrottle],
+ )
+ def search(self, request: Request, **kwargs: Any) -> Response:
+ """Rank observations by semantic similarity to the search text, optionally filtered by exact outcome
+ (verdict, score, tags)."""
+ params = ObservationSearchQuerySerializer(data=request.query_params)
+ params.is_valid(raise_exception=True)
+ validated = params.validated_data
+
+ scanner_ids = self._searchable_scanner_ids(validated.get("scanner_id"))
+ if not scanner_ids:
+ return self._search_response([])
+ # Gate before the embedding call so an opted-out org gets an actionable 400, not an opaque failure.
+ if not is_ai_data_processing_approved(self.team.id):
+ raise ValidationError(
+ "Your organization needs to allow AI analysis before you can search Replay Vision observations."
+ )
+ try:
+ # Short timeout: this sync call pins a request thread, and search users don't wait long.
+ embedding_response = generate_embedding(
+ self.team, validated["q"], model=OBSERVATION_EMBEDDING_MODEL.value, timeout=10.0
+ )
+ 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.
+ logger.warning("replay_vision.observation_search.embedding_failed", team_id=self.team_id, exc_info=True)
+ raise EmbeddingUnavailableError()
+ filters = ObservationSearchFilters.from_raw(
+ verdict=_csv_values(validated.get("verdict")),
+ tags=_csv_values(validated.get("tags")),
+ min_score=validated.get("min_score"),
+ max_score=validated.get("max_score"),
+ )
+ limit = validated["limit"]
+ # Over-fetch, then slice back down after hydration drops rows (see RANK_OVERFETCH_FACTOR).
+ rank_limit = limit * RANK_OVERFETCH_FACTOR
+ matches = rank_observations(
+ self.team,
+ cast(User, request.user),
+ scanner_ids,
+ embedding_response.embedding,
+ rank_limit,
+ filters,
+ )
+ match_by_id = {match.observation_id: match for match in matches}
+ observations = fetch_ranked_observations(
+ self.team_id, scanner_ids, [match.observation_id for match in matches], self.user_access_control
+ )
+ # ClickHouse filling its limit means it may hold further matches it never ranked.
+ truncated = len(matches) >= rank_limit or len(observations) > limit
+ return self._search_response(
+ [
+ {
+ "observation": obs,
+ "distance": match_by_id[str(obs.id)].distance,
+ "matched_content": match_by_id[str(obs.id)].matched_content,
+ }
+ for obs in observations[:limit]
+ ],
+ truncated=truncated,
+ )
+
+ def _search_response(self, results: list[dict[str, Any]], truncated: bool = False) -> Response:
+ serializer = ObservationSearchResponseSerializer(
+ {"results": results, "truncated": truncated}, context=self.get_serializer_context()
+ )
+ return Response(serializer.data)
+
+ def _searchable_scanner_ids(self, scanner_id: uuid.UUID | None) -> list[str]:
+ # Observations expose recording-derived output, so searching them requires session_recording read.
+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
+ raise PermissionDenied("Searching replay observations requires session_recording read access.")
+ if scanner_id is not None:
+ scanner = scanner_for_reading_observations(self.team_id, scanner_id)
+ # Not-found doubles as no-access so the response never leaks the scanner or its experiment.
+ if (
+ scanner is None
+ or not self.user_access_control.check_access_level_for_object(scanner, "viewer")
+ or not can_read_targeted_experiment(self.user_access_control, self.team_id, scanner)
+ ):
+ raise NotFound("Scanner not found.")
+ return [str(scanner.id)]
+ return [str(sid) for sid in readable_observation_scanner_ids(self.user_access_control, self.team_id)]
+
@extend_schema(exclude=True)
@action(detail=True, methods=["GET"], url_path="progress", renderer_classes=[ServerSentEventRenderer])
def progress(self, request: Request, **kwargs: Any) -> HttpResponseBase:
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
index 09995197a0de..401c9109af7d 100644
--- a/products/replay_vision/backend/max_tools.py
+++ b/products/replay_vision/backend/max_tools.py
@@ -1,5 +1,4 @@
import uuid
-from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, ClassVar
from django.db import transaction
@@ -11,12 +10,8 @@ from posthoganalytics import capture_exception
from pydantic import BaseModel, Field
from rest_framework.exceptions import Throttled
-from posthog.hogql import ast
-from posthog.hogql.query import execute_hogql_query
-
from posthog.api.embedding_worker import async_generate_embedding
from posthog.clickhouse.client.connection import ClickHouseUser
-from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.exceptions import QuotaLimitExceeded
from posthog.models.team import Team
from posthog.models.user import User
@@ -30,11 +25,7 @@ from products.replay_vision.backend.api.trigger import WorkflowStartOutcome, sta
from products.replay_vision.backend.api.vision_actions import VisionActionSerializer
from products.replay_vision.backend.billing import CREDITS_PER_DOLLAR, observation_credits_for_model
from products.replay_vision.backend.consent import is_ai_data_processing_approved
-from products.replay_vision.backend.embeddings import (
- EMBEDDING_DOCUMENT_TYPE,
- EMBEDDING_PRODUCT,
- OBSERVATION_EMBEDDING_MODEL,
-)
+from products.replay_vision.backend.embeddings import OBSERVATION_EMBEDDING_MODEL
from products.replay_vision.backend.impact import compute_scanner_impact, create_affected_cohort
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel
@@ -64,8 +55,14 @@ from products.replay_vision.backend.scanning import (
run_inline_scan,
scan_existing_scanner,
)
+from products.replay_vision.backend.search import (
+ DEFAULT_SEARCH_LIMIT,
+ MAX_SEARCH_LIMIT,
+ RANK_OVERFETCH_FACTOR,
+ ObservationSearchFilters,
+ rank_observations,
+)
from products.replay_vision.backend.tag_suggestions import suggest_classifier_tags
-from products.replay_vision.backend.tags import clickhouse_slugify_sql, slugify_tag
from products.replay_vision.backend.temporal.metrics import record_scanner_limit_reached
from ee.hogai.tool import MaxTool
@@ -153,15 +150,6 @@ scanner it came from, verdict/score/tags, and the reasoning snippet. Cite the ma
synthesize the reasons rather than restating each row.
"""
-# Default and hard cap on how many observations the search returns to Max's context.
-DEFAULT_SEARCH_LIMIT = 20
-MAX_SEARCH_LIMIT = 50
-# 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
-# predictable without an HNSW index (which our mandatory tenant/scanner metadata filters wouldn't engage anyway).
-_MAX_CANDIDATE_ROWS = 50_000
-
-
VALID_SCANNER_TYPES = {t.value for t in ScannerType}
@@ -385,73 +373,6 @@ class SummarizeReplayVisionSummariesTool(ReplayVisionGatesMixin, MaxTool):
return content, {"scanner_id": scanner_id, "summary_count": len(lines)}
-# Slugify each stored metadata tag before `hasAny`, so the case/format-insensitive match works against rows
-# whose fixed-vocab tags were stamped verbatim — no backfill. The caller passes already-slugified values in
-# `{tags}`. Built from hardcoded literals only (no user/LLM input), preserving the `_append_filter` invariant.
-_TAGS_FILTER_CLAUSE = (
- f"hasAny(arrayMap(t -> {clickhouse_slugify_sql('t')}, JSONExtract(metadata, 'tags', 'Array(String)')), {{tags}})"
-)
-
-
-@dataclass(frozen=True)
-class _ObservationFilters:
- """Exact-outcome filters, applied inside the ClickHouse ranking query against the embedding metadata
- (monitor `verdict`, scorer `score`, classifier `tags` are stamped onto each embedding row at write time)."""
-
- verdict: list[str] | None = None
- tags: list[str] | None = None
- min_score: float | None = None
- max_score: float | None = None
-
- def where_clauses(self, placeholders: dict[str, "ast.Expr"]) -> list[str]:
- """HogQL predicates over `metadata`, registering their values into `placeholders`. The metadata key is
- absent for scanner types that don't carry it, so each predicate naturally matches only the right type.
-
- Every clause MUST be added via `_append_filter` — that helper is the only path that pairs a
- hardcoded-literal clause string with a parameterized placeholder. Never append a clause built from
- anything other than a static string literal; user/LLM-controlled input belongs in `value`, not in
- `clause`."""
- clauses: list[str] = []
- if self.verdict:
- self._append_filter(
- clauses, placeholders, "verdict", self.verdict, "JSONExtractString(metadata, 'verdict') IN {verdict}"
- )
- if self.tags:
- self._append_filter(clauses, placeholders, "tags", self.tags, _TAGS_FILTER_CLAUSE)
- if self.min_score is not None:
- self._append_filter(
- clauses,
- placeholders,
- "min_score",
- self.min_score,
- "JSONHas(metadata, 'score') AND JSONExtractFloat(metadata, 'score') >= {min_score}",
- )
- if self.max_score is not None:
- self._append_filter(
- clauses,
- placeholders,
- "max_score",
- self.max_score,
- "JSONHas(metadata, 'score') AND JSONExtractFloat(metadata, 'score') <= {max_score}",
- )
- return clauses
-
- @staticmethod
- def _append_filter(
- clauses: list[str],
- placeholders: dict[str, "ast.Expr"],
- key: str,
- value: Any,
- clause: str,
- ) -> None:
- """Register one filter atomically: the value goes into `placeholders` (parameterized), the clause is
- the hardcoded literal that references it. The structure/value split lives in one place so callers
- can't half-do it — any future filter must come through here, which makes the "clause is a static
- literal" invariant impossible to break by accident."""
- placeholders[key] = ast.Constant(value=value)
- clauses.append(clause)
-
-
class SearchObservationsArgs(BaseModel):
query: str = Field(
max_length=2000,
@@ -513,15 +434,7 @@ class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):
if not query or not query.strip():
return "No search query provided. Please describe what to look for.", {"error": "empty_query"}
- # Slugify Max's tag guess ("Frustrated Or Confused" -> "frustrated_or_confused") so it matches the
- # normalized stored side; order-preserving dedup, dropping anything that slugs to empty.
- normalized_tags = list(dict.fromkeys(s for t in (tags or []) if (s := slugify_tag(t)))) or None
- # Verdicts are a closed lowercase enum (yes/no/inconclusive) stored verbatim, so lowercase Max's input
- # to absorb a casing slip ("Yes") that would otherwise silently match nothing.
- normalized_verdict = list(dict.fromkeys(v.strip().lower() for v in (verdict or []) if v.strip())) or None
- filters = _ObservationFilters(
- verdict=normalized_verdict, tags=normalized_tags, min_score=min_score, max_score=max_score
- )
+ filters = ObservationSearchFilters.from_raw(verdict, tags, min_score, max_score)
try:
return await self._search(str(resolved_id) if resolved_id else None, query.strip(), filters, limit)
except Exception as e:
@@ -534,7 +447,7 @@ class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):
return "Something went wrong searching the observations. Please try again.", {"error": "search_failed"}
async def _search(
- self, scanner_id: str | None, query: str, filters: "_ObservationFilters", limit: int | None
+ self, scanner_id: str | None, query: str, filters: ObservationSearchFilters, limit: int | None
) -> tuple[str, dict[str, Any]]:
# The embedding call is a 30s-bounded HTTP request; awaiting `async_generate_embedding` lets the event
# loop schedule other work instead of pinning a Django DB-pool thread for the full network RTT. The DB
@@ -594,14 +507,20 @@ class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):
capped_limit: int,
query: str,
query_vector: list[float],
- filters: "_ObservationFilters",
+ filters: ObservationSearchFilters,
) -> tuple[str, dict[str, Any]]:
"""Sync ClickHouse rank + ORM fetch + format — runs after the embedding HTTP call has resolved."""
empty = (f"No recordings from {scope_label} matched that search yet.", {"result_count": 0})
# Filter + rank in one ClickHouse query: the structured outcome filters run against the embedding
# metadata, so the semantic ranking only ever sees recordings that already match the exact outcome.
- ordered_ids = self._rank_observation_ids(scanner_ids, query_vector, capped_limit, filters)
+ # Over-fetch, then cut back down after the loop below drops rows (see RANK_OVERFETCH_FACTOR).
+ ordered_ids = [
+ match.observation_id
+ for match in rank_observations(
+ self._team, self._user, scanner_ids, query_vector, capped_limit * RANK_OVERFETCH_FACTOR, filters
+ )
+ ]
if not ordered_ids:
return empty
@@ -624,6 +543,8 @@ class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):
lines: list[str] = []
matched_ids: list[str] = []
for observation_id in ordered_ids:
+ if len(matched_ids) >= capped_limit:
+ break
obs = observations.get(observation_id)
if obs is None:
continue
@@ -665,60 +586,6 @@ class SearchReplayVisionObservationsTool(ReplayVisionGatesMixin, MaxTool):
readable = readable_observation_scanner_ids(self.user_access_control, self._team.id)
return [str(sid) for sid in readable], "your Replay Vision scanners", True
- def _rank_observation_ids(
- self, scanner_ids: list[str], query_vector: list[float], limit: int, filters: "_ObservationFilters"
- ) -> list[str]:
- """Closest observation ids by cosine distance, restricted to the given scanners — and to the structured
- outcome filters — via the embedding metadata, so filter and rank happen in a single query.
-
- `min(...)` collapses an observation's multiple renderings (the summarizer's per-facet rows) to its
- single best-matching distance, so each observation appears once.
-
- The distance scan is exact (brute-force), so we bound it: the inner query takes the most recent
- `_MAX_CANDIDATE_ROWS` matching embedding rows before ranking. Below that volume (all teams at launch
- scale) it's a no-op; a high-volume team is capped to its most recent embeddings, keeping latency
- predictable at the cost of not ranking its oldest observations.
- """
- placeholders: dict[str, ast.Expr] = {
- "embedding": ast.Constant(value=query_vector),
- "model_name": ast.Constant(value=OBSERVATION_EMBEDDING_MODEL.value),
- "product": ast.Constant(value=EMBEDDING_PRODUCT),
- "document_type": ast.Constant(value=EMBEDDING_DOCUMENT_TYPE),
- "team_id": ast.Constant(value=self._team.id),
- "scanner_ids": ast.Constant(value=scanner_ids),
- "candidate_cap": ast.Constant(value=_MAX_CANDIDATE_ROWS),
- "limit": ast.Constant(value=limit),
- }
- filter_clause = "".join(f"\n AND {clause}" for clause in filters.where_clauses(placeholders))
- hogql_query = f"""
- SELECT
- document_id,
- min(cosineDistance(embedding, {{embedding}})) AS distance
- FROM (
- SELECT document_id, embedding
- FROM document_embeddings
- WHERE model_name = {{model_name}}
- AND product = {{product}}
- AND document_type = {{document_type}}
- AND team_id = {{team_id}}
- AND JSONExtractString(metadata, 'scanner_id') IN {{scanner_ids}}{filter_clause}
- ORDER BY timestamp DESC
- LIMIT {{candidate_cap}}
- )
- GROUP BY document_id
- ORDER BY distance ASC
- LIMIT {{limit}}
- """
- tag_queries(product=Product.REPLAY_VISION, feature=Feature.SEMANTIC_SEARCH)
- result = execute_hogql_query(
- query=hogql_query,
- team=self._team,
- user=self._user,
- placeholders=placeholders,
- ch_user=ClickHouseUser.REPLAY_VISION,
- )
- return [row[0] for row in (result.results or [])]
-
# Everything a scan costs is priced per observation from this model unless a saved scanner names another.
DEFAULT_SCAN_MODEL = ScannerModel.GEMINI_3_FLASH_PREVIEW
diff --git a/products/replay_vision/backend/search.py b/products/replay_vision/backend/search.py
new file mode 100644
index 000000000000..e4d924b107c9
--- /dev/null
+++ b/products/replay_vision/backend/search.py
@@ -0,0 +1,219 @@
+"""Semantic search core over observation embeddings, shared by the HTTP API and the Max tool.
+
+The write side (`embed_observation`) stamps each embedding row with the scanner id and the structured
+outcome (monitor `verdict`, scorer `score`, classifier `tags`), so filtering and cosine ranking happen in
+a single ClickHouse query here. Callers resolve scanner scope and access control themselves and pass the
+readable scanner ids in.
+"""
+
+from dataclasses import dataclass
+from typing import Any
+
+from posthog.hogql import ast
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.models.team import Team
+from posthog.models.user import User
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.replay_vision.backend.embeddings import (
+ EMBEDDING_DOCUMENT_TYPE,
+ EMBEDDING_PRODUCT,
+ OBSERVATION_EMBEDDING_MODEL,
+)
+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.scanner_access import accessible_observations
+from products.replay_vision.backend.tags import clickhouse_slugify_sql, slugify_tag
+
+# Default and hard cap on how many observations a search returns.
+DEFAULT_SEARCH_LIMIT = 20
+MAX_SEARCH_LIMIT = 50
+# Postgres-side hydration re-checks status and access and can drop ranked ids, so a caller that ranks
+# exactly `limit` ids can come back short. Callers rank this many times their limit and slice the
+# hydrated rows back down, so drops only shorten the response once they exceed the margin.
+RANK_OVERFETCH_FACTOR = 3
+# Cut inside the candidate subquery so full facet paragraphs are neither carried through the sort nor
+# sent over the wire.
+_MATCHED_CONTENT_MAX_CHARS = 300
+# 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
+# predictable without an HNSW index (which our mandatory tenant/scanner metadata filters wouldn't engage anyway).
+_MAX_CANDIDATE_ROWS = 50_000
+
+# Slugify each stored metadata tag before `hasAny`, so the case/format-insensitive match works against rows
+# whose fixed-vocab tags were stamped verbatim, with no backfill. The caller passes already-slugified values in
+# `{tags}`. Built from hardcoded literals only (no user/LLM input), preserving the `_append_filter` invariant.
+_TAGS_FILTER_CLAUSE = (
+ f"hasAny(arrayMap(t -> {clickhouse_slugify_sql('t')}, JSONExtract(metadata, 'tags', 'Array(String)')), {{tags}})"
+)
+
+
+@dataclass(frozen=True)
+class ObservationMatch:
+ """One ranked search hit: the observation id and its cosine distance to the query (lower is closer)."""
+
+ observation_id: str
+ distance: float
+ # Excerpt of the row that ranked this hit. Empty for rows written before `content` was stored.
+ matched_content: str
+
+
+@dataclass(frozen=True)
+class ObservationSearchFilters:
+ """Exact-outcome filters, applied inside the ClickHouse ranking query against the embedding metadata
+ (monitor `verdict`, scorer `score`, classifier `tags` are stamped onto each embedding row at write time)."""
+
+ verdict: list[str] | None = None
+ tags: list[str] | None = None
+ min_score: float | None = None
+ max_score: float | None = None
+
+ @classmethod
+ def from_raw(
+ cls,
+ verdict: list[str] | None,
+ tags: list[str] | None,
+ min_score: float | None,
+ max_score: float | None,
+ ) -> "ObservationSearchFilters":
+ """Normalize caller-supplied values: tags slugified to match the stored side, verdicts lowercased so
+ a casing slip doesn't silently match nothing. Both are order-preserving deduped."""
+ normalized_tags = list(dict.fromkeys(s for t in (tags or []) if (s := slugify_tag(t)))) or None
+ normalized_verdict = list(dict.fromkeys(v.strip().lower() for v in (verdict or []) if v.strip())) or None
+ return cls(verdict=normalized_verdict, tags=normalized_tags, min_score=min_score, max_score=max_score)
+
+ def where_clauses(self, placeholders: dict[str, "ast.Expr"]) -> list[str]:
+ """HogQL predicates over `metadata`, registering their values into `placeholders`. The metadata key is
+ absent for scanner types that don't carry it, so each predicate naturally matches only the right type.
+
+ Every clause MUST be added via `_append_filter`, the only path that pairs a hardcoded-literal
+ clause string with a parameterized placeholder. Never append a clause built from anything other
+ than a static string literal. User/LLM-controlled input belongs in `value`, not in `clause`."""
+ clauses: list[str] = []
+ if self.verdict:
+ self._append_filter(
+ clauses, placeholders, "verdict", self.verdict, "JSONExtractString(metadata, 'verdict') IN {verdict}"
+ )
+ if self.tags:
+ self._append_filter(clauses, placeholders, "tags", self.tags, _TAGS_FILTER_CLAUSE)
+ if self.min_score is not None:
+ self._append_filter(
+ clauses,
+ placeholders,
+ "min_score",
+ self.min_score,
+ "JSONHas(metadata, 'score') AND JSONExtractFloat(metadata, 'score') >= {min_score}",
+ )
+ if self.max_score is not None:
+ self._append_filter(
+ clauses,
+ placeholders,
+ "max_score",
+ self.max_score,
+ "JSONHas(metadata, 'score') AND JSONExtractFloat(metadata, 'score') <= {max_score}",
+ )
+ return clauses
+
+ @staticmethod
+ def _append_filter(
+ clauses: list[str],
+ placeholders: dict[str, "ast.Expr"],
+ key: str,
+ value: Any,
+ clause: str,
+ ) -> None:
+ """Register one filter atomically: the value goes into `placeholders` (parameterized), the clause is
+ the hardcoded literal that references it. The structure/value split lives in one place so callers
+ can't half-do it. Any future filter must come through here, which makes the "clause is a static
+ literal" invariant impossible to break by accident."""
+ placeholders[key] = ast.Constant(value=value)
+ clauses.append(clause)
+
+
+def rank_observations(
+ team: Team,
+ user: User,
+ scanner_ids: list[str],
+ query_vector: list[float],
+ limit: int,
+ filters: ObservationSearchFilters,
+) -> list[ObservationMatch]:
+ """Closest observations by cosine distance, restricted to the given scanners and to the structured
+ outcome filters via the embedding metadata, so filter and rank happen in a single query.
+
+ `min(...)` collapses an observation's multiple renderings (the summarizer's per-facet rows) to its
+ single best-matching distance, so each observation appears once.
+
+ The distance scan is exact (brute-force), so we bound it: the inner query takes the most recent
+ `_MAX_CANDIDATE_ROWS` matching embedding rows before ranking. Below that volume (all teams at launch
+ scale) it's a no-op. A high-volume team is capped to its most recent embeddings, keeping latency
+ predictable at the cost of not ranking its oldest observations.
+ """
+ placeholders: dict[str, ast.Expr] = {
+ "embedding": ast.Constant(value=query_vector),
+ "model_name": ast.Constant(value=OBSERVATION_EMBEDDING_MODEL.value),
+ "product": ast.Constant(value=EMBEDDING_PRODUCT),
+ "document_type": ast.Constant(value=EMBEDDING_DOCUMENT_TYPE),
+ "team_id": ast.Constant(value=team.id),
+ "scanner_ids": ast.Constant(value=scanner_ids),
+ "candidate_cap": ast.Constant(value=_MAX_CANDIDATE_ROWS),
+ "limit": ast.Constant(value=limit),
+ "snippet_chars": ast.Constant(value=_MATCHED_CONTENT_MAX_CHARS),
+ }
+ filter_clause = "".join(f"\n AND {clause}" for clause in filters.where_clauses(placeholders))
+ # The distance layer wraps the capped candidate subquery so the 3072-dim dot product runs once per
+ # candidate row (min and argMin share the alias) and never on rows the cap already discarded.
+ hogql_query = f"""
+ SELECT
+ document_id,
+ min(row_distance) AS distance,
+ argMin(snippet, row_distance) AS matched_content
+ FROM (
+ SELECT document_id, cosineDistance(embedding, {{embedding}}) AS row_distance, snippet
+ FROM (
+ SELECT document_id, embedding, substring(content, 1, {{snippet_chars}}) AS snippet
+ FROM document_embeddings
+ WHERE model_name = {{model_name}}
+ AND product = {{product}}
+ AND document_type = {{document_type}}
+ AND team_id = {{team_id}}
+ AND JSONExtractString(metadata, 'scanner_id') IN {{scanner_ids}}{filter_clause}
+ ORDER BY timestamp DESC
+ LIMIT {{candidate_cap}}
+ )
+ )
+ GROUP BY document_id
+ ORDER BY distance ASC
+ LIMIT {{limit}}
+ """
+ tag_queries(product=Product.REPLAY_VISION, feature=Feature.SEMANTIC_SEARCH)
+ result = execute_hogql_query(
+ query=hogql_query,
+ team=team,
+ user=user,
+ placeholders=placeholders,
+ ch_user=ClickHouseUser.REPLAY_VISION,
+ )
+ return [
+ ObservationMatch(observation_id=row[0], distance=row[1], matched_content=row[2])
+ for row in (result.results or [])
+ ]
+
+
+def fetch_ranked_observations(
+ team_id: int, scanner_ids: list[str], ordered_ids: list[str], access: UserAccessControl
+) -> list[ReplayObservation]:
+ """Hydrate ranked observation ids into rows, preserving rank order. The scanner-id filter and
+ `accessible_observations` re-apply the caller's access scope here because embedding rows carry
+ no experiment metadata, so a ranked id alone could leak an observation the caller can't read."""
+ rows = ReplayObservation.objects.filter(
+ team_id=team_id,
+ scanner_id__in=scanner_ids,
+ status=ObservationStatus.SUCCEEDED,
+ id__in=ordered_ids,
+ )
+ rows = accessible_observations(access, team_id, rows).select_related("triggered_by_user", "label")
+ observations = {str(obs.id): obs for obs in rows}
+ return [obs for observation_id in ordered_ids if (obs := observations.get(observation_id)) is not None]
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 15fc14044f27..3cd52aa18af2 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -4,11 +4,13 @@ from typing import Any
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import MagicMock, patch
+from django.core.cache import cache
from django.db import connection
from django.test import SimpleTestCase, override_settings
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
+import requests
from parameterized import parameterized
from temporalio.exceptions import WorkflowAlreadyStartedError
@@ -19,6 +21,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value,
from posthog.redis import get_client
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
+from products.experiments.backend.models.experiment import Experiment
from products.replay_vision.backend.api.scanners import ReplayScannerSerializer
from products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_apply_scanner_workflow
from products.replay_vision.backend.billing import observation_credits_for_model
@@ -44,6 +47,7 @@ from products.replay_vision.backend.queries import ESTIMATE_STALE_AFTER, SAVE_ES
from products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVAL
from products.replay_vision.backend.quota import BillingPeriod, _current_period_bounds
from products.replay_vision.backend.scanner_draft import DraftError, ScannerDraft
+from products.replay_vision.backend.search import ObservationMatch
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
@@ -3035,6 +3039,184 @@ class TestSessionReplayObservationViewSet(_VisionAPITestCase):
self.assertIsNone(body["next_observation_id"])
+class TestObservationSearchAction(_VisionAPITestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.scanner = self._create_scanner(name="searchable")
+
+ @property
+ def search_url(self) -> str:
+ return f"/api/environments/{self.team.id}/vision/observations/search/"
+
+ def _create_succeeded_observation(self, session_id: str, scanner: ReplayScanner | None = None) -> ReplayObservation:
+ scanner = scanner or self.scanner
+ observation = ReplayObservation.objects.create(
+ scanner=scanner,
+ session_id=session_id,
+ scanner_snapshot=_snapshot_for(scanner),
+ triggered_by=ObservationTrigger.SCHEDULE,
+ )
+ ReplayObservation.objects.filter(pk=observation.id).update(
+ status=ObservationStatus.SUCCEEDED, completed_at=timezone.now()
+ )
+ return observation
+
+ @parameterized.expand(
+ [
+ ("missing_q", ""),
+ ("limit_above_cap", "?q=checkout&limit=51"),
+ ("unknown_verdict", "?q=checkout&verdict=yes,maybe"),
+ ("min_score_above_max_score", "?q=checkout&min_score=5&max_score=1"),
+ ("nan_score", "?q=checkout&min_score=nan"),
+ ("infinite_score", "?q=checkout&max_score=inf"),
+ ]
+ )
+ def test_search_rejects_bad_params(self, _name: str, query_string: str) -> None:
+ resp = self.client.get(f"{self.search_url}{query_string}")
+ self.assertEqual(resp.status_code, 400)
+
+ @patch("products.replay_vision.backend.api.observations.rank_observations")
+ @patch("products.replay_vision.backend.api.observations.generate_embedding")
+ def test_search_returns_results_in_rank_order(self, mock_embed: MagicMock, mock_rank: MagicMock) -> None:
+ first = self._create_succeeded_observation("sess-1")
+ second = self._create_succeeded_observation("sess-2")
+ mock_embed.return_value = MagicMock(embedding=[0.1, 0.2])
+ # A ranked id with no readable row must be skipped, not 500 or leak.
+ mock_rank.return_value = [
+ ObservationMatch(observation_id=str(second.id), distance=0.1, matched_content="user rage-clicked"),
+ ObservationMatch(observation_id=str(uuid7()), distance=0.2, matched_content=""),
+ ObservationMatch(observation_id=str(first.id), distance=0.3, matched_content=""),
+ ]
+
+ resp = self.client.get(f"{self.search_url}?q=confused users")
+
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual(
+ [(r["observation"]["id"], r["distance"], r["matched_content"]) for r in resp.json()["results"]],
+ [(str(second.id), 0.1, "user rage-clicked"), (str(first.id), 0.3, "")],
+ )
+ self.assertFalse(resp.json()["truncated"])
+
+ @patch("products.replay_vision.backend.api.observations.rank_observations")
+ @patch("products.replay_vision.backend.api.observations.generate_embedding")
+ def test_search_overfetches_then_slices_to_limit_and_flags_truncation(
+ self, mock_embed: MagicMock, mock_rank: MagicMock
+ ) -> None:
+ first = self._create_succeeded_observation("sess-1")
+ second = self._create_succeeded_observation("sess-2")
+ mock_embed.return_value = MagicMock(embedding=[0.1])
+ # The best-ranked id hydrates to nothing readable; the over-fetched tail must fill the response
+ # up to `limit`, and the extra readable row must be cut, not returned.
+ mock_rank.return_value = [
+ ObservationMatch(observation_id=str(uuid7()), distance=0.1, matched_content=""),
+ ObservationMatch(observation_id=str(first.id), distance=0.2, matched_content=""),
+ ObservationMatch(observation_id=str(second.id), distance=0.3, matched_content=""),
+ ]
+
+ resp = self.client.get(f"{self.search_url}?q=confused users&limit=1")
+
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertGreater(mock_rank.call_args[0][4], 1)
+ self.assertEqual([r["observation"]["id"] for r in resp.json()["results"]], [str(first.id)])
+ self.assertTrue(resp.json()["truncated"])
+
+ @patch("products.replay_vision.backend.api.observations.rank_observations")
+ @patch("products.replay_vision.backend.api.observations.generate_embedding")
+ def test_search_drops_rows_whose_snapshot_experiment_is_restricted(
+ self, mock_embed: MagicMock, mock_rank: MagicMock
+ ) -> None:
+ experiment = create_experiment(self.team, "restricted-flag")
+ targeted = self._create_scanner(
+ name="was-targeted", experiment_targeting={"experiment_id": experiment.id, "variant": "test"}
+ )
+ restricted = self._create_succeeded_observation("sess-restricted", scanner=targeted)
+ # Clear the targeting so the scanner passes the scanner gate. The row's snapshot must still block it.
+ targeted.experiment_targeting = None
+ targeted.save(update_fields=["experiment_targeting"])
+ visible = self._create_succeeded_observation("sess-visible")
+ mock_embed.return_value = MagicMock(embedding=[0.1])
+ mock_rank.return_value = [
+ ObservationMatch(observation_id=str(restricted.id), distance=0.1, matched_content=""),
+ ObservationMatch(observation_id=str(visible.id), distance=0.2, matched_content=""),
+ ]
+
+ with patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.filter_queryset_by_access_level",
+ side_effect=lambda qs, **_: qs.exclude(pk=experiment.pk) if qs.model is Experiment else qs,
+ ):
+ resp = self.client.get(f"{self.search_url}?q=anything")
+
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual([r["observation"]["id"] for r in resp.json()["results"]], [str(visible.id)])
+
+ @patch("products.replay_vision.backend.api.observations.rank_observations", return_value=[])
+ @patch("products.replay_vision.backend.api.observations.generate_embedding")
+ def test_search_hides_scanner_targeting_a_restricted_experiment(
+ self, mock_embed: MagicMock, mock_rank: MagicMock
+ ) -> None:
+ experiment = create_experiment(self.team, "restricted-flag")
+ denied = self._create_scanner(
+ name="targeted", experiment_targeting={"experiment_id": experiment.id, "variant": "test"}
+ )
+ mock_embed.return_value = MagicMock(embedding=[0.1])
+
+ with patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.filter_queryset_by_access_level",
+ side_effect=lambda qs, **_: qs.exclude(pk=experiment.pk) if qs.model is Experiment else qs,
+ ):
+ scoped = self.client.get(f"{self.search_url}?q=anything&scanner_id={denied.id}")
+ cross = self.client.get(f"{self.search_url}?q=anything")
+
+ # Not-found rather than 403, so the response never leaks the experiment's existence.
+ self.assertEqual(scoped.status_code, 404)
+ self.assertEqual(cross.status_code, 200)
+ searched_scanner_ids = mock_rank.call_args[0][2]
+ self.assertNotIn(str(denied.id), searched_scanner_ids)
+ self.assertIn(str(self.scanner.id), searched_scanner_ids)
+
+ # `generate_embedding` posts through a `requests` session, so its transport failures are the
+ # `requests` exceptions — an `httpx` mock here would exercise a handler that can never fire.
+ @parameterized.expand(
+ [
+ ("unreachable", requests.ConnectionError),
+ ("slow", requests.Timeout),
+ ]
+ )
+ def test_search_returns_503_when_embedding_unavailable(self, _name: str, exception_class: type) -> None:
+ with patch(
+ "products.replay_vision.backend.api.observations.generate_embedding",
+ side_effect=exception_class("embedding service down"),
+ ):
+ resp = self.client.get(f"{self.search_url}?q=anything")
+ self.assertEqual(resp.status_code, 503)
+
+ @patch("products.replay_vision.backend.api.observations.is_ai_data_processing_approved", return_value=False)
+ def test_search_returns_400_when_ai_consent_is_off(self, _mock_consent: MagicMock) -> None:
+ resp = self.client.get(f"{self.search_url}?q=anything")
+ self.assertEqual(resp.status_code, 400)
+ self.assertIn("allow AI analysis", resp.json()["detail"])
+
+ def test_search_with_unknown_scanner_returns_404(self) -> None:
+ resp = self.client.get(f"{self.search_url}?q=anything&scanner_id={uuid7()}")
+ self.assertEqual(resp.status_code, 404)
+
+ # Guards the wiring, not the rate: the action-level `throttle_classes` must actually reach
+ # `get_throttles()`, or the endpoint ships with no throttle at all.
+ @patch("posthog.rate_limit.ReplayVisionSearchBurstRateThrottle.rate", new="2/minute")
+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+ @patch("products.replay_vision.backend.api.observations.rank_observations", return_value=[])
+ @patch("products.replay_vision.backend.api.observations.generate_embedding")
+ def test_search_is_rate_limited(
+ self, mock_embed: MagicMock, _mock_rank: MagicMock, _mock_enabled: MagicMock
+ ) -> None:
+ cache.clear()
+ mock_embed.return_value = MagicMock(embedding=[0.1])
+ for _ in range(2):
+ self.assertEqual(self.client.get(f"{self.search_url}?q=anything").status_code, 200)
+
+ self.assertEqual(self.client.get(f"{self.search_url}?q=anything").status_code, 429)
+
+
class TestReplayScannerEstimateAction(ClickhouseTestMixin, _VisionAPITestCase):
@property
def estimate_url(self) -> str:
diff --git a/products/replay_vision/backend/tests/test_max_tools.py b/products/replay_vision/backend/tests/test_max_tools.py
index c93a432267eb..dd5c9f2a2f2d 100644
--- a/products/replay_vision/backend/tests/test_max_tools.py
+++ b/products/replay_vision/backend/tests/test_max_tools.py
@@ -32,7 +32,6 @@ from products.replay_vision.backend.max_tools import (
SearchReplayVisionObservationsTool,
SummarizeReplayVisionSummariesTool,
UpdateReplayVisionScannerTool,
- _ObservationFilters,
)
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
@@ -58,7 +57,7 @@ _SCANNER_LOOKUP_PATH = "products.replay_vision.backend.max_tools.scanner_for_rea
# The estimate refresh runs a ClickHouse query; these tests are about the tool, not the query.
_REFRESH_ESTIMATE_PATH = "products.replay_vision.backend.api.scanners._refresh_estimate_fail_soft"
_GENERATE_EMBEDDING_PATH = "products.replay_vision.backend.max_tools.async_generate_embedding"
-_EXECUTE_HOGQL_PATH = "products.replay_vision.backend.max_tools.execute_hogql_query"
+_EXECUTE_HOGQL_PATH = "products.replay_vision.backend.search.execute_hogql_query"
class TestDraftReplayVisionScannerPromptTool(BaseTest):
@@ -180,7 +179,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):
def _side_effect(*_args, **kwargs):
placeholders = kwargs.get("placeholders", {})
rows = [
- (str(obs.id), distance)
+ (str(obs.id), distance, "")
for obs, distance in ranked
if _matches(obs.scanner_result["model_output"], placeholders)
]
@@ -195,7 +194,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):
obs_far = await self._observation(scanner, "sess-far", "user smoothly completed checkout", score=5)
obs_near = await self._observation(scanner, "sess-near", "user rage-clicked the broken submit button", score=0)
# ClickHouse returns ids ordered by ascending cosine distance (nearest first).
- hogql_results = MagicMock(results=[(str(obs_near.id), 0.1), (str(obs_far.id), 0.4)])
+ hogql_results = MagicMock(results=[(str(obs_near.id), 0.1, ""), (str(obs_far.id), 0.4, "")])
with (
patch(
@@ -221,7 +220,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):
with (
patch(_GENERATE_EMBEDDING_PATH, new_callable=AsyncMock, return_value=MagicMock(embedding=[0.1])),
- patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1)])),
+ patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1, "")])),
):
_, artifact = await self._tool(context={"scanner_id": str(scanner.id)})._arun_impl(query="button")
@@ -236,7 +235,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):
with (
patch(_GENERATE_EMBEDDING_PATH, new_callable=AsyncMock, return_value=MagicMock(embedding=[0.1])),
- patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1)])),
+ patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1, "")])),
):
_, artifact = await self._tool(context={"scanner_id": str(context_scanner.id)})._arun_impl(
query="button", scanner_id=str(target_scanner.id)
@@ -277,7 +276,10 @@ class TestSearchReplayVisionObservationsTool(BaseTest):
with (
patch(_GENERATE_EMBEDDING_PATH, new_callable=AsyncMock, return_value=MagicMock(embedding=[0.1])),
- patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs_a.id), 0.1), (str(obs_b.id), 0.2)])),
+ patch(
+ _EXECUTE_HOGQL_PATH,
+ return_value=MagicMock(results=[(str(obs_a.id), 0.1, ""), (str(obs_b.id), 0.2, "")]),
+ ),
):
content, artifact = await self._tool()._arun_impl(query="checkout problems")
@@ -404,7 +406,7 @@ class TestSearchReplayVisionObservationsTool(BaseTest):
with (
patch(_GENERATE_EMBEDDING_PATH, new_callable=AsyncMock, return_value=MagicMock(embedding=[0.1])),
- patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1)])),
+ patch(_EXECUTE_HOGQL_PATH, return_value=MagicMock(results=[(str(obs.id), 0.1, "")])),
):
content, _ = await self._tool()._arun_impl(query="x", scanner_id=str(scanner.id))
@@ -455,30 +457,6 @@ class TestSummarizeReplayVisionSummariesTool(BaseTest):
assert "hunter2" not in content
-class TestObservationFiltersTagClause:
- """Pure-logic clause construction — no DB/ClickHouse, so it runs without the full test stack."""
-
- @parameterized.expand(
- [
- ("single", ["frustrated_or_confused"]),
- ("multiple", ["abandoned", "completed"]),
- # `_ObservationFilters` registers values verbatim — pre-slugifying is the caller's (tool's) job. The
- # SQL slugifies the *stored* side; passing a non-slug here proves the value is not re-normalized.
- ("verbatim_not_renormalized", ["Frustrated Or Confused"]),
- ]
- )
- def test_tags_clause_normalizes_stored_side_and_registers_values(self, _name: str, tags: list[str]) -> None:
- placeholders: dict = {}
- clauses = _ObservationFilters(tags=tags).where_clauses(placeholders)
-
- assert len(clauses) == 1
- # Stored metadata tags are slugified inside the clause (arrayMap) so verbatim-stored tags still match.
- assert clauses[0].startswith("hasAny(")
- assert "arrayMap" in clauses[0]
- # The clause carries no inlined tag value — it lives only in the parameterized placeholder, verbatim.
- assert placeholders["tags"].value == tags
-
-
class TestReplayVisionChargeConfirmation(BaseTest):
"""Every tool that spends Replay Vision credits has to ask first, and say what it costs."""
diff --git a/products/replay_vision/backend/tests/test_search.py b/products/replay_vision/backend/tests/test_search.py
new file mode 100644
index 000000000000..d74918fed37a
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_search.py
@@ -0,0 +1,143 @@
+import json
+import uuid
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.clickhouse.client import sync_execute
+
+from products.replay_vision.backend.embeddings import EMBEDDING_DOCUMENT_TYPE, EMBEDDING_PRODUCT
+from products.replay_vision.backend.search import ObservationSearchFilters, rank_observations
+
+
+class TestObservationFiltersTagClause:
+ """Pure-logic clause construction with no DB/ClickHouse, so it runs without the full test stack."""
+
+ @parameterized.expand(
+ [
+ ("single", ["frustrated_or_confused"]),
+ ("multiple", ["abandoned", "completed"]),
+ # `where_clauses` registers values verbatim, pre-slugifying is `from_raw`'s job. The SQL
+ # slugifies the *stored* side, so passing a non-slug here proves the value is not re-normalized.
+ ("verbatim_not_renormalized", ["Frustrated Or Confused"]),
+ ]
+ )
+ def test_tags_clause_normalizes_stored_side_and_registers_values(self, _name: str, tags: list[str]) -> None:
+ placeholders: dict = {}
+ clauses = ObservationSearchFilters(tags=tags).where_clauses(placeholders)
+
+ assert len(clauses) == 1
+ # Stored metadata tags are slugified inside the clause (arrayMap) so verbatim-stored tags still match.
+ assert clauses[0].startswith("hasAny(")
+ assert "arrayMap" in clauses[0]
+ # The clause carries no inlined tag value. It lives only in the parameterized placeholder, verbatim.
+ assert placeholders["tags"].value == tags
+
+
+# Runs the ranking SQL against real ClickHouse. Everything else mocks `execute_hogql_query`.
+class TestRankObservationsQuery(ClickhouseTestMixin, APIBaseTest):
+ def _insert_embedding_rows(self, rows: list[tuple]) -> None:
+ # Reads for this model route to its model-specific table. Named inline to avoid a cross-product import.
+ sync_execute(
+ """
+ INSERT INTO distributed_posthog_document_embeddings_text_embedding_3_large_3072 (
+ team_id, product, document_type, rendering, document_id,
+ timestamp, inserted_at, content, metadata, embedding,
+ _timestamp, _offset, _partition
+ ) VALUES
+ """,
+ rows,
+ flush=False,
+ team_id=self.team.pk,
+ )
+
+ def test_ranks_dedupes_and_truncates_matched_content(self) -> None:
+ scanner_id = str(uuid.uuid4())
+ best = str(uuid.uuid4())
+ other = str(uuid.uuid4())
+ now = timezone.now()
+ metadata = json.dumps({"scanner_id": scanner_id})
+
+ # The table enforces length(embedding) = 3072.
+ def vector(x: float, y: float) -> list[float]:
+ return [x, y, *([0.0] * 3070)]
+
+ def row(rendering: str, document_id: str, content: str, embedding: list[float]) -> tuple:
+ return (
+ self.team.pk,
+ EMBEDDING_PRODUCT,
+ EMBEDDING_DOCUMENT_TYPE,
+ rendering,
+ document_id,
+ now,
+ now,
+ content,
+ metadata,
+ embedding,
+ now,
+ 0,
+ 0,
+ )
+
+ self._insert_embedding_rows(
+ [
+ row("intent", best, "user wanted to check out", vector(1.0, 0.0)),
+ row("outcome", best, "gave up at the payment step", vector(0.0, 1.0)),
+ row("reasoning", other, "x" * 400, vector(0.6, 0.8)),
+ ]
+ )
+
+ matches = rank_observations(
+ self.team, self.user, [scanner_id], vector(1.0, 0.0), 10, ObservationSearchFilters()
+ )
+
+ self.assertEqual([m.observation_id for m in matches], [best, other])
+ # `best` has two renderings and the hit carries the closest one's text.
+ self.assertEqual(matches[0].matched_content, "user wanted to check out")
+ self.assertAlmostEqual(matches[0].distance, 0.0, places=5)
+ self.assertEqual(len(matches[1].matched_content), 300)
+
+ def test_every_filter_clause_compiles_and_applies_inside_the_candidate_subquery(self) -> None:
+ scanner_id = str(uuid.uuid4())
+ kept = str(uuid.uuid4())
+ dropped = str(uuid.uuid4())
+ now = timezone.now()
+ embedding = [1.0, *([0.0] * 3071)]
+
+ def row(document_id: str, metadata: dict) -> tuple:
+ return (
+ self.team.pk,
+ EMBEDDING_PRODUCT,
+ EMBEDDING_DOCUMENT_TYPE,
+ "reasoning",
+ document_id,
+ now,
+ now,
+ "some content",
+ json.dumps({"scanner_id": scanner_id, **metadata}),
+ embedding,
+ now,
+ 0,
+ 0,
+ )
+
+ self._insert_embedding_rows(
+ [
+ row(kept, {"verdict": "yes", "score": 2.0, "tags": ["Abandoned Cart"]}),
+ row(dropped, {"verdict": "no", "score": 0.5, "tags": ["other"]}),
+ ]
+ )
+
+ matches = rank_observations(
+ self.team,
+ self.user,
+ [scanner_id],
+ embedding,
+ 10,
+ ObservationSearchFilters.from_raw(verdict=["yes"], tags=["abandoned cart"], min_score=1.0, max_score=3.0),
+ )
+
+ self.assertEqual([m.observation_id for m in matches], [kept])
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index e01d3dbd1244..c69ca1ad0ec8 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -697,6 +697,22 @@ export interface RetryResponseApi {
workflow_id: string
}
+export interface ObservationSearchResultApi {
+ /** The matching observation. */
+ observation: ReplayObservationApi
+ /** Cosine distance between the search text and the observation's closest embedding. Lower is a closer match. Only comparable to other results in the same response. */
+ distance: number
+ /** Excerpt of the observation text that best matched the search, truncated. Empty for observations analyzed before excerpts were stored. */
+ matched_content: string
+}
+
+export interface ObservationSearchResponseApi {
+ /** Matching observations, most relevant first. */
+ results: ObservationSearchResultApi[]
+ /** True when more matches may exist beyond `results`, so the response is a top slice rather than everything that matched. */
+ truncated: boolean
+}
+
export interface VisionQuotaApi {
/**
* Credits the org may spend per billing period (1 credit = $0.01). Null when billing has synced the product with no spend limit: uncapped.
@@ -2273,6 +2289,43 @@ export type VisionObservationsRetrieveParams = {
verdict?: string
}
+export type VisionObservationsSearchRetrieveParams = {
+ /**
+ * Maximum number of results (default 20, at most 50).
+ * @minimum 1
+ * @maximum 50
+ */
+ limit?: number
+ /**
+ * Keep only scorer observations with a score at or below this value.
+ */
+ max_score?: number
+ /**
+ * Keep only scorer observations with a score at or above this value.
+ */
+ min_score?: number
+ /**
+ * Natural-language description of what to find, e.g. 'users confused by the pricing page'.
+ * @minLength 1
+ * @maxLength 2000
+ */
+ q: string
+ /**
+ * Search a single scanner's observations. Defaults to every scanner you can read.
+ */
+ scanner_id?: string
+ /**
+ * Comma-separated classifier tags to keep. Matching is case- and format-insensitive. Unlike `verdict`, tags are not validated against a fixed list, so an unknown tag matches nothing.
+ * @minLength 1
+ */
+ tags?: string
+ /**
+ * Comma-separated monitor verdicts to keep, e.g. `yes,inconclusive`.
+ * @minLength 1
+ */
+ verdict?: string
+}
+
export type VisionScannersListParams = {
/**
* Filter to scanners created by the given user IDs (comma-separated).
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index 621e1743990c..f1bb34d2d026 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -25,6 +25,7 @@ import type {
EvaluatePromptSuggestionRequestApi,
InlineScanRequestApi,
InlineScanResponseApi,
+ ObservationSearchResponseApi,
ObservationStatsApi,
ObserveAlreadyScannedApi,
ObserveRequestApi,
@@ -59,6 +60,7 @@ import type {
VisionActionsRunsListParams,
VisionObservationsListParams,
VisionObservationsRetrieveParams,
+ VisionObservationsSearchRetrieveParams,
VisionQuotaApi,
VisionScannersBackfillsListParams,
VisionScannersImpactRetrieveParams,
@@ -283,7 +285,8 @@ export const getVisionObservationsListUrl = (projectId: string, params: VisionOb
}
/**
- * Read-only access to a session's observations across every scanner the caller can read, for the replay-page dock.
+ * A session's observations across every scanner the caller can read, plus the team-level semantic
+ * `search` action, which resolves its own scanner scope instead of this queryset.
*/
export const visionObservationsList = async (
projectId: string,
@@ -406,6 +409,40 @@ export const visionObservationsRetryCreate = async (
})
}
+export const getVisionObservationsSearchRetrieveUrl = (
+ projectId: string,
+ params: VisionObservationsSearchRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/vision/observations/search/?${stringifiedParams}`
+ : `/api/projects/${projectId}/vision/observations/search/`
+}
+
+/**
+ * Rank observations by semantic similarity to the search text, optionally filtered by exact outcome
+ * (verdict, score, tags).
+ */
+export const visionObservationsSearchRetrieve = async (
+ projectId: string,
+ params: VisionObservationsSearchRetrieveParams,
+ options?: RequestInit
+): Promise<ObservationSearchResponseApi> => {
+ return apiMutator<ObservationSearchResponseApi>(getVisionObservationsSearchRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEnvironmentVisionQuotaRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/vision/quota/`
}
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
index 0d94e180c7ac..1522a6e8d5be 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
@@ -18,6 +18,7 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { IngestionLimitBanner } from '../components/IngestionLimitBanner'
import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'
import { visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { ObservationSearchTab } from '../search/ObservationSearchTab'
import { getReplayVisionEditDisabledReason } from '../utils/accessControl'
import { formatCreditsRange } from '../utils/credits'
import { quotaBannerState } from '../utils/quotaProjection'
@@ -134,6 +135,11 @@ export function ReplayScannerSceneComponent(): JSX.Element {
label: 'Observations',
content: <ScannerObservationsTable scannerId={scannerId} />,
},
+ {
+ key: ReplayScannerTab.Search,
+ label: 'Search',
+ content: <ObservationSearchTab scannerId={scannerId} />,
+ },
{
key: ReplayScannerTab.OnDemand,
label: 'On-demand',
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
index c2ec023cba83..be39568a1819 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
@@ -33,11 +33,13 @@ import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackBu
import { ScannerTypeBadge } from '../components/ScannerTypeBadge'
import { replayVisionEmptyState } from '../emptyState/replayVisionEmptyState'
import { visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { ObservationSearchTab } from '../search/ObservationSearchTab'
import { getReplayVisionDeleteDisabledReason, getReplayVisionEditDisabledReason } from '../utils/accessControl'
import { creditsToUsd, formatCreditCount } from '../utils/credits'
import { CreateScannerButton } from './components/CreateScannerButton'
import { VisionMetrics } from './components/VisionMetrics'
import { VisionUsageTab } from './components/VisionUsageTab'
+import { ReplayScannerTab } from './replayScannerSceneLogic'
import { type ScannersSorting, SCANNERS_PAGE_SIZE, replayScannersLogic } from './replayScannersLogic'
import { LIMIT_REACHED_TOOLTIP } from './scannerCopy'
import { ENABLED_OPTIONS, EnabledFilter, SCANNER_TYPE_OPTIONS, ScannerType, ReplayScanner } from './types'
@@ -252,15 +254,20 @@ export function ReplayScannersScene(): JSX.Element {
)}
<LemonTabs
- activeKey={searchParams.tab === 'usage' ? 'usage' : 'scanners'}
- onChange={(tab) => push(urls.replayVision(), tab === 'usage' ? { tab } : {})}
+ activeKey={
+ [ReplayScannerTab.Search, 'usage'].includes(searchParams.tab) ? searchParams.tab : 'scanners'
+ }
+ onChange={(tab) => push(urls.replayVision(), tab === 'scanners' ? {} : { tab })}
tabs={[
{ key: 'scanners', label: 'Scanners', content: <></> },
+ { key: ReplayScannerTab.Search, label: 'Search', content: <></> },
{ key: 'usage', label: 'Usage', content: <></> },
]}
/>
- {searchParams.tab === 'usage' ? (
+ {searchParams.tab === ReplayScannerTab.Search ? (
+ <ObservationSearchTab scannerId={null} />
+ ) : searchParams.tab === 'usage' ? (
<VisionUsageTab />
) : (
<>
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts
index 6bf18d48acf6..f8369e63d40a 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerSceneLogic.ts
@@ -11,6 +11,7 @@ import { Breadcrumb } from '~/types'
export enum ReplayScannerTab {
Overview = 'overview',
Observations = 'observations',
+ Search = 'search',
Calibration = 'calibration',
OnDemand = 'on-demand',
Backfills = 'backfills',
diff --git a/products/replay_vision/frontend/search/ObservationSearchTab.tsx b/products/replay_vision/frontend/search/ObservationSearchTab.tsx
new file mode 100644
index 000000000000..d521de43c64f
--- /dev/null
+++ b/products/replay_vision/frontend/search/ObservationSearchTab.tsx
@@ -0,0 +1,174 @@
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
+import { Fragment } from 'react'
+
+import { IconSearch } from '@posthog/icons'
+import { LemonButton, LemonInput, LemonTag, Link, Spinner } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { urls } from 'scenes/urls'
+
+import { ObservationResultSummary } from '../components/ObservationCard'
+import { ScannerTypeBadge } from '../components/ScannerTypeBadge'
+import type { ObservationSearchResultApi } from '../generated/api.schemas'
+import { observationSearchLogic } from './observationSearchLogic'
+import { snippetSegments } from './snippetSegments'
+
+const EXAMPLE_QUERIES = ['users who got stuck and gave up', 'rage clicking out of frustration']
+
+function countLabel(count: number, truncated: boolean): string {
+ if (truncated) {
+ return `Showing the top ${count === 1 ? 'match' : `${count} matches`}, best first`
+ }
+ return `${count === 1 ? '1 match' : `${count} matches`}, best first`
+}
+
+function SearchResultCard({
+ result,
+ searchedQuery,
+ showScanner,
+ strongMatch,
+}: {
+ result: ObservationSearchResultApi
+ searchedQuery: string
+ showScanner: boolean
+ strongMatch: boolean
+}): JSX.Element {
+ const observation = result.observation
+ const snapshot = observation.scanner_snapshot
+ return (
+ <Link
+ to={urls.replayVisionObservation(observation.id)}
+ className="block border rounded p-3 bg-surface-primary hover:border-accent space-y-2 text-primary"
+ data-attr="vision-search-result"
+ >
+ <div className="flex items-center gap-2 min-w-0">
+ {showScanner && snapshot && (
+ <>
+ <span className="font-semibold text-sm truncate">{snapshot.name || 'Scanner'}</span>
+ <ScannerTypeBadge scannerType={snapshot.scanner_type} size="small" variant="muted" />
+ </>
+ )}
+ <span className="font-mono text-xs text-muted truncate">{observation.session_id}</span>
+ {observation.recording_subject_email && (
+ <span className="text-xs text-muted truncate">{observation.recording_subject_email}</span>
+ )}
+ <span className="ml-auto shrink-0 flex items-center gap-2 text-xs text-muted">
+ {strongMatch && (
+ <LemonTag type="success" size="small">
+ Strong match
+ </LemonTag>
+ )}
+ <TZLabel time={observation.created_at} />
+ </span>
+ </div>
+ {result.matched_content && (
+ <div className="text-sm text-secondary line-clamp-2">
+ {snippetSegments(result.matched_content, searchedQuery).map((segment, index) =>
+ segment.highlighted ? (
+ <span key={index} className="font-semibold text-accent">
+ {segment.text}
+ </span>
+ ) : (
+ <Fragment key={index}>{segment.text}</Fragment>
+ )
+ )}
+ </div>
+ )}
+ <ObservationResultSummary observation={observation} />
+ </Link>
+ )
+}
+
+export function ObservationSearchTab({ scannerId }: { scannerId: string | null }): JSX.Element {
+ const logic = observationSearchLogic({ scannerId })
+ const { query, results, searching, searchedQuery, strongMatchDistanceCutoff, truncated } = useValues(logic)
+ const { setQuery, search } = useActions(logic)
+ const crossScanner = scannerId === null
+
+ return (
+ <div className="w-full max-w-3xl mx-auto flex flex-col gap-4 pt-2">
+ <div className="flex gap-2">
+ <LemonInput
+ type="search"
+ fullWidth
+ prefix={<IconSearch />}
+ placeholder="Describe what to look for"
+ value={query}
+ onChange={setQuery}
+ onPressEnter={() => !searching && search()}
+ autoFocus
+ data-attr="vision-search-query"
+ />
+ <LemonButton
+ type="primary"
+ onClick={() => search()}
+ loading={searching}
+ disabledReason={!query.trim() ? 'Describe what to look for first' : undefined}
+ data-attr="vision-search-submit"
+ >
+ Search
+ </LemonButton>
+ </div>
+
+ {results === null ? (
+ searching ? (
+ <div className="flex items-center justify-center h-40">
+ <Spinner className="text-2xl" />
+ </div>
+ ) : (
+ <div className="text-center text-muted pt-8 flex flex-col gap-3">
+ <div>
+ {crossScanner
+ ? 'Search everything your scanners have observed, ranked by how well it matches.'
+ : 'Search everything this scanner has observed, ranked by how well it matches.'}
+ </div>
+ <div className="flex items-center justify-center gap-2 flex-wrap">
+ <span>Try</span>
+ {EXAMPLE_QUERIES.map((example) => (
+ <LemonButton
+ key={example}
+ type="secondary"
+ size="small"
+ onClick={() => {
+ setQuery(example)
+ search()
+ }}
+ data-attr="vision-search-example"
+ >
+ {example}
+ </LemonButton>
+ ))}
+ </div>
+ </div>
+ )
+ ) : (
+ <div className={clsx('flex flex-col gap-4', searching && 'opacity-50 pointer-events-none')}>
+ {results.length === 0 ? (
+ <div className="text-center text-muted pt-8">
+ No matches for "{searchedQuery}". Only sessions a scanner has analyzed are searchable.
+ </div>
+ ) : (
+ <>
+ <div className="text-muted text-sm">{countLabel(results.length, truncated)}</div>
+ <div className="flex flex-col gap-2">
+ {results.map((result) => (
+ <SearchResultCard
+ key={result.observation.id}
+ result={result}
+ searchedQuery={searchedQuery ?? ''}
+ showScanner={crossScanner}
+ strongMatch={
+ strongMatchDistanceCutoff !== null &&
+ result.distance <= strongMatchDistanceCutoff
+ }
+ />
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/search/observationSearchLogic.test.ts b/products/replay_vision/frontend/search/observationSearchLogic.test.ts
new file mode 100644
index 000000000000..e4219ef385bb
--- /dev/null
+++ b/products/replay_vision/frontend/search/observationSearchLogic.test.ts
@@ -0,0 +1,112 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { urls } from 'scenes/urls'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { ObservationSearchResultApi } from '../generated/api.schemas'
+import { observationSearchLogic } from './observationSearchLogic'
+
+function searchResults(distances: number[]): ObservationSearchResultApi[] {
+ return distances.map(
+ (distance, index) =>
+ ({ observation: { id: `obs-${index}` }, distance }) as unknown as ObservationSearchResultApi
+ )
+}
+
+describe('observationSearchLogic', () => {
+ let searchSpy: jest.Mock
+
+ beforeEach(() => {
+ searchSpy = jest.fn(() => [200, { results: [{ observation: { id: 'obs-1' }, distance: 0.1 }] }])
+ useMocks({
+ get: {
+ '/api/projects/:team/vision/observations/search/': searchSpy,
+ },
+ })
+ initKeaTests()
+ })
+
+ it.each([
+ ['a scanner-scoped', 'scanner-1', 'scanner-1'],
+ ['a cross-scanner', null, null],
+ ])('%s search sends the right scope and stores ranked results', async (_name, scannerId, expectedScope) => {
+ const logic = observationSearchLogic({ scannerId })
+ logic.mount()
+ // On the live page URL, the actionToUrl echo would re-dispatch search without the in-flight guard.
+ router.actions.push(scannerId ? urls.replayVision(scannerId) : urls.replayVision(), { tab: 'search' })
+ logic.actions.setQuery('confused users')
+ await expectLogic(logic, () => logic.actions.search()).toFinishAllListeners()
+
+ expect(searchSpy).toHaveBeenCalledTimes(1)
+ const requestUrl = new URL(searchSpy.mock.calls[0][0].request.url)
+ expect(requestUrl.searchParams.get('q')).toBe('confused users')
+ expect(requestUrl.searchParams.get('scanner_id')).toBe(expectedScope)
+ expect(logic.values.results?.map((r) => r.observation.id)).toEqual(['obs-1'])
+ logic.unmount()
+ })
+
+ it.each([
+ ['spread distances tag the top tier', [0.1, 0.12, 0.4], expect.closeTo(0.15)],
+ ['clustered distances tag nothing', [0.1, 0.12, 0.14], null],
+ ['a single result tags nothing', [0.2], null],
+ ])('%s', (_name, distances, expectedCutoff) => {
+ const logic = observationSearchLogic({ scannerId: null })
+ logic.mount()
+ logic.actions.searchSuccess(searchResults(distances), 'query', false)
+
+ expect(logic.values.strongMatchDistanceCutoff).toEqual(expectedCutoff)
+ logic.unmount()
+ })
+
+ it('a blank query never reaches the API', async () => {
+ const logic = observationSearchLogic({ scannerId: null })
+ logic.mount()
+ logic.actions.setQuery(' ')
+ await expectLogic(logic, () => logic.actions.search()).toFinishAllListeners()
+
+ expect(searchSpy).not.toHaveBeenCalled()
+ expect(logic.values.searching).toBe(false)
+ logic.unmount()
+ })
+
+ it('a deep-linked q runs the search once, not on every navigation', async () => {
+ const logic = observationSearchLogic({ scannerId: null })
+ logic.mount()
+ router.actions.push(urls.replayVision(), { tab: 'search', q: 'rage clicks' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(searchSpy).toHaveBeenCalledTimes(1)
+
+ router.actions.push(urls.replayVision(), { tab: 'search', q: 'rage clicks' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(searchSpy).toHaveBeenCalledTimes(1)
+ logic.unmount()
+ })
+
+ it('a query with trailing whitespace searches once, despite the trimmed actionToUrl echo', async () => {
+ const logic = observationSearchLogic({ scannerId: null })
+ logic.mount()
+ router.actions.push(urls.replayVision(), { tab: 'search' })
+ logic.actions.setQuery('rage clicks ')
+ await expectLogic(logic, () => logic.actions.search()).toFinishAllListeners()
+
+ expect(searchSpy).toHaveBeenCalledTimes(1)
+ logic.unmount()
+ })
+
+ it('a failed deep-linked search does not re-fire on unrelated URL changes', async () => {
+ searchSpy.mockImplementation(() => [500, { detail: 'embedding service down' }])
+ const logic = observationSearchLogic({ scannerId: null })
+ logic.mount()
+ router.actions.push(urls.replayVision(), { tab: 'search', q: 'rage clicks' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(searchSpy).toHaveBeenCalledTimes(1)
+
+ router.actions.push(urls.replayVision(), { tab: 'search', q: 'rage clicks', unrelated: '1' })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(searchSpy).toHaveBeenCalledTimes(1)
+ logic.unmount()
+ })
+})
diff --git a/products/replay_vision/frontend/search/observationSearchLogic.ts b/products/replay_vision/frontend/search/observationSearchLogic.ts
new file mode 100644
index 000000000000..12440b913f35
--- /dev/null
+++ b/products/replay_vision/frontend/search/observationSearchLogic.ts
@@ -0,0 +1,194 @@
+import { MakeLogicType, actions, isBreakpoint, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { actionToUrl, router, urlToAction } from 'kea-router'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { visionObservationsSearchRetrieve } from '../generated/api'
+import type { ObservationSearchResultApi } from '../generated/api.schemas'
+import { ReplayScannerTab } from '../replay_scanners/replayScannerSceneLogic'
+
+// The server's MAX_SEARCH_LIMIT. A larger value would 400.
+const SEARCH_RESULT_LIMIT = 50
+
+// Relative to the best match, because distances are only comparable within one response.
+const STRONG_MATCH_MARGIN = 0.05
+
+export interface ObservationSearchLogicProps {
+ /** Scope the search to one scanner. Null searches every scanner the user can read. */
+ scannerId: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface observationSearchLogicValues {
+ query: string
+ results: ObservationSearchResultApi[] | null
+ searchedQuery: string | null
+ searching: boolean
+ strongMatchDistanceCutoff: number | null
+ truncated: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface observationSearchLogicActions {
+ search: () => {
+ value: true
+ }
+ searchFailure: () => {
+ value: true
+ }
+ searchSuccess: (
+ results: ObservationSearchResultApi[],
+ query: string,
+ truncated: boolean
+ ) => {
+ query: string
+ results: ObservationSearchResultApi[]
+ truncated: boolean
+ }
+ setQuery: (query: string) => {
+ query: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface observationSearchLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ strongMatchDistanceCutoff: (results: ObservationSearchResultApi[] | null) => number | null
+ }
+}
+
+export type observationSearchLogicType = MakeLogicType<
+ observationSearchLogicValues,
+ observationSearchLogicActions,
+ ObservationSearchLogicProps,
+ observationSearchLogicMeta
+>
+
+export const observationSearchLogic = kea<observationSearchLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'search', 'observationSearchLogic']),
+ props({} as ObservationSearchLogicProps),
+ key((props) => props.scannerId ?? 'cross-scanner'),
+
+ actions({
+ setQuery: (query: string) => ({ query }),
+ search: true,
+ searchSuccess: (results: ObservationSearchResultApi[], query: string, truncated: boolean) => ({
+ results,
+ query,
+ truncated,
+ }),
+ searchFailure: true,
+ }),
+
+ reducers({
+ query: [
+ '' as string,
+ {
+ setQuery: (_, { query }) => query,
+ },
+ ],
+ // null until the first search, so the empty state can tell "not searched yet" from "no matches".
+ results: [
+ null as ObservationSearchResultApi[] | null,
+ {
+ searchSuccess: (_, { results }) => results,
+ },
+ ],
+ searching: [
+ false,
+ {
+ search: () => true,
+ searchSuccess: () => false,
+ searchFailure: () => false,
+ },
+ ],
+ searchedQuery: [
+ null as string | null,
+ {
+ searchSuccess: (_, { query }) => query,
+ },
+ ],
+ // The server cut the response to `limit`, so the results are a top slice, not everything that matched.
+ truncated: [
+ false,
+ {
+ searchSuccess: (_, { truncated }) => truncated,
+ },
+ ],
+ }),
+
+ selectors({
+ // Null when the tag would not separate anything, so it is never shown on every result.
+ strongMatchDistanceCutoff: [
+ (s) => [s.results],
+ (results: ObservationSearchResultApi[] | null): number | null => {
+ if (!results || results.length < 2) {
+ return null
+ }
+ const cutoff = Math.min(...results.map((r) => r.distance)) + STRONG_MATCH_MARGIN
+ return results.some((r) => r.distance > cutoff) ? cutoff : null
+ },
+ ],
+ }),
+
+ listeners(({ actions, props, values }) => ({
+ search: async (_, breakpoint) => {
+ const query = values.query.trim()
+ if (!query) {
+ actions.searchFailure()
+ return
+ }
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.searchFailure()
+ return
+ }
+ try {
+ const response = await visionObservationsSearchRetrieve(String(teamId), {
+ q: query,
+ limit: SEARCH_RESULT_LIMIT,
+ ...(props.scannerId ? { scanner_id: props.scannerId } : {}),
+ })
+ // Drop out-of-order responses. The newest search owns the results.
+ breakpoint()
+ actions.searchSuccess(response.results ?? [], query, response.truncated ?? false)
+ } catch (error: any) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ throw error
+ }
+ lemonToast.error(`Search failed${error?.detail ? `: ${error.detail}` : ''}`)
+ actions.searchFailure()
+ }
+ },
+ })),
+
+ actionToUrl(({ values }) => ({
+ search: () => [
+ router.values.location.pathname,
+ { ...router.values.searchParams, q: values.query.trim() || undefined },
+ router.values.hashParams,
+ { replace: true },
+ ],
+ })),
+
+ urlToAction(({ actions, props, values }) => ({
+ [props.scannerId ? urls.replayVision(props.scannerId) : urls.replayVision()]: (_, searchParams) => {
+ if (searchParams.tab !== ReplayScannerTab.Search) {
+ return
+ }
+ // kea-router decodes ?q=true to a boolean, so stringify instead of dropping it.
+ const raw = searchParams.q
+ const q = typeof raw === 'string' ? raw : raw != null ? String(raw) : ''
+ // Run a deep-linked query once. Comparing against the trimmed input blocks the actionToUrl
+ // echo of an interactive search, and stops a failed query (which never reaches searchedQuery)
+ // from re-firing on every unrelated URL change while it still fills the input.
+ if (q && q !== values.searchedQuery && q !== values.query.trim()) {
+ actions.setQuery(q)
+ actions.search()
+ }
+ },
+ })),
+])
diff --git a/products/replay_vision/frontend/search/snippetSegments.test.ts b/products/replay_vision/frontend/search/snippetSegments.test.ts
new file mode 100644
index 000000000000..4461c9ef8cb8
--- /dev/null
+++ b/products/replay_vision/frontend/search/snippetSegments.test.ts
@@ -0,0 +1,59 @@
+import { snippetSegments } from './snippetSegments'
+
+describe('snippetSegments', () => {
+ it.each([
+ [
+ 'bolds whole words starting with a query term, case-insensitively',
+ 'Rage-clicking the submit button',
+ 'rage click',
+ ['Rage', '-', 'clicking', ' the submit button'],
+ ['Rage', 'clicking'],
+ ],
+ [
+ 'regex special characters in the query are literal, not a crash',
+ 'checkout (step 2) failed',
+ 'checkout (step 2)?',
+ ['checkout', ' (', 'step', ' 2) failed'],
+ ['checkout', 'step'],
+ ],
+ [
+ 'stopwords and short words are never bolded',
+ 'the user gave up after an error',
+ 'the user who gave up',
+ ['the ', 'user', ' ', 'gave', ' up after an error'],
+ ['user', 'gave'],
+ ],
+ [
+ 'a semantic-only match stays one plain segment',
+ 'visitor abandoned their cart',
+ 'frustrated shopper',
+ ['visitor abandoned their cart'],
+ [],
+ ],
+ [
+ 'an accented query word is dropped whole, not fragmented into false matches',
+ 'usual riots of confusion',
+ 'usuário confusion',
+ ['usual riots of ', 'confusion'],
+ ['confusion'],
+ ],
+ ])('%s', (_name, text, query, expectedTexts, expectedHighlights) => {
+ const segments = snippetSegments(text, query)
+
+ expect(segments.map((s) => s.text)).toEqual(expectedTexts)
+ expect(segments.filter((s) => s.highlighted).map((s) => s.text)).toEqual(expectedHighlights)
+ expect(segments.map((s) => s.text).join('')).toBe(text)
+ })
+
+ it('windows a late match into view behind a leading ellipsis', () => {
+ const text = `${'lead '.repeat(40)}rage clicking at checkout`
+
+ const segments = snippetSegments(text, 'rage clicking')
+
+ const joined = segments.map((s) => s.text).join('')
+ expect(joined.startsWith('… ')).toBe(true)
+ expect(joined.endsWith('rage clicking at checkout')).toBe(true)
+ expect(joined.length).toBeLessThan(80)
+ expect(segments.filter((s) => s.highlighted).map((s) => s.text)).toEqual(['rage', 'clicking'])
+ })
+})
diff --git a/products/replay_vision/frontend/search/snippetSegments.ts b/products/replay_vision/frontend/search/snippetSegments.ts
new file mode 100644
index 000000000000..9dc25d045acb
--- /dev/null
+++ b/products/replay_vision/frontend/search/snippetSegments.ts
@@ -0,0 +1,73 @@
+import { escapeRegex } from 'lib/utils/actions'
+
+export interface SnippetSegment {
+ text: string
+ highlighted: boolean
+}
+
+const STOPWORDS = new Set([
+ 'the',
+ 'and',
+ 'for',
+ 'was',
+ 'were',
+ 'with',
+ 'that',
+ 'this',
+ 'from',
+ 'into',
+ 'after',
+ 'about',
+ 'their',
+ 'have',
+ 'has',
+ 'who',
+])
+
+// Past what the two-line clamp shows.
+const MAX_LEAD_CHARS = 120
+const WINDOW_CONTEXT_CHARS = 40
+
+/** Split a snippet into segments, marking whole words that start with a query term ("click"
+ * also marks "clicking"). A match deep in the text is windowed in behind a leading ellipsis. */
+export function snippetSegments(text: string, query: string): SnippetSegment[] {
+ // Non-ASCII words are dropped whole: fragmenting "usuário" to "usu" would highlight unrelated words.
+ const terms = Array.from(
+ new Set(
+ query
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}]+/u)
+ .filter((term) => /^[a-z0-9]{3,}$/.test(term) && !STOPWORDS.has(term))
+ )
+ )
+ if (terms.length === 0) {
+ return [{ text, highlighted: false }]
+ }
+ const pattern = new RegExp(`\\b(?:${terms.map(escapeRegex).join('|')})[a-z0-9]*`, 'gi')
+
+ const segments: SnippetSegment[] = []
+ let display = text
+ const firstMatchIndex = text.search(pattern)
+ if (firstMatchIndex > MAX_LEAD_CHARS) {
+ let start = firstMatchIndex - WINDOW_CONTEXT_CHARS
+ const wordBoundary = text.indexOf(' ', start)
+ if (wordBoundary !== -1 && wordBoundary < firstMatchIndex) {
+ start = wordBoundary + 1
+ }
+ display = text.slice(start)
+ segments.push({ text: '… ', highlighted: false })
+ }
+
+ let consumedTo = 0
+ for (const match of display.matchAll(pattern)) {
+ if (match.index > consumedTo) {
+ segments.push({ text: display.slice(consumedTo, match.index), highlighted: false })
+ }
+ segments.push({ text: match[0], highlighted: true })
+ consumedTo = match.index + match[0].length
+ }
+ if (consumedTo < display.length) {
+ segments.push({ text: display.slice(consumedTo), highlighted: false })
+ }
+ return segments
+}
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index c82e1c05060d..4cdfcc571341 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -253,6 +253,30 @@ tools:
vision-observations-retry-create:
operation: vision_observations_retry_create
enabled: false
+ vision-observations-search:
+ operation: vision_observations_search_retrieve
+ enabled: true
+ scopes:
+ - replay_scanner:read
+ - session_recording:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Semantically search replay vision observations
+ description: >
+ Search replay vision observations by meaning, not keywords: `q` is a natural-language description of what to
+ find (e.g. "users confused by the pricing page") and results come back under `results`, most relevant first.
+ Each result pairs the `observation` with its `distance` to the query (lower is closer, only comparable
+ within one response) and `matched_content`, the excerpt of the observation's text that matched (may be empty
+ for old rows). The search ranks each observation's LLM output (a summarizer's intent/outcome/friction
+ facets, other scanners' reasoning) by semantic similarity, so it finds sessions described differently from
+ the query. Scope with `scanner_id` to search one scanner, otherwise every scanner the caller can read is
+ searched. Narrow by exact outcome with `verdict` (comma-separated, e.g. `yes,inconclusive`), `tags`
+ (comma-separated classifier tags), and `min_score`/`max_score` (scorer bounds). These filter, while `q`
+ ranks. `limit` defaults to 20 (max 50). Use `vision-observations-retrieve` for a result's full detail, or
+ `vision-observations-list` for everything observed about one session.
+ requires_ai_consent: true
vision-quota-retrieve:
operation: environment_vision_quota_retrieve
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 00578d4894f8..385396955346 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -11217,6 +11217,21 @@
"readOnlyHint": true
}
},
+ "vision-observations-search": {
+ "description": "Search replay vision observations by meaning, not keywords: `q` is a natural-language description of what to find (e.g. \"users confused by the pricing page\") and results come back under `results`, most relevant first. Each result pairs the `observation` with its `distance` to the query (lower is closer, only comparable within one response) and `matched_content`, the excerpt of the observation's text that matched (may be empty for old rows). The search ranks each observation's LLM output (a summarizer's intent/outcome/friction facets, other scanners' reasoning) by semantic similarity, so it finds sessions described differently from the query. Scope with `scanner_id` to search one scanner, otherwise every scanner the caller can read is searched. Narrow by exact outcome with `verdict` (comma-separated, e.g. `yes,inconclusive`), `tags` (comma-separated classifier tags), and `min_score`/`max_score` (scorer bounds). These filter, while `q` ranks. `limit` defaults to 20 (max 50). Use `vision-observations-retrieve` for a result's full detail, or `vision-observations-list` for everything observed about one session.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Semantically search replay vision observations",
+ "title": "Semantically search replay vision observations",
+ "required_scopes": ["replay_scanner:read", "session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "requires_ai_consent": true
+ },
"vision-quota-retrieve": {
"description": "Get the organization's Replay vision credit budget (1 credit = $0.01; observations cost credits by model). Returns `credit_limit` (null when uncapped), `credits_used` (in-flight + succeeded observations counted against it), `remaining`, `exhausted`, `projected_monthly_credits`, and the `period_start`/`period_end` of the current budget window (the org's billing period, or the calendar month when billing hasn't synced). Check `remaining`/`exhausted` before creating a scanner or calling `vision-scanners-scan-session`: over budget, a scanner's scheduled sweeps silently skip their observations until the next period, while `vision-scanners-scan-session` is rejected outright with a 402. Pair with `vision-scanners-estimate-create` to size a new scanner against the remaining budget.",
"category": "Replay vision",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index dd8d3b69e450..d6af57a1ecc5 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11831,6 +11831,21 @@
"readOnlyHint": true
}
},
+ "vision-observations-search": {
+ "description": "Search replay vision observations by meaning, not keywords: `q` is a natural-language description of what to find (e.g. \"users confused by the pricing page\") and results come back under `results`, most relevant first. Each result pairs the `observation` with its `distance` to the query (lower is closer, only comparable within one response) and `matched_content`, the excerpt of the observation's text that matched (may be empty for old rows). The search ranks each observation's LLM output (a summarizer's intent/outcome/friction facets, other scanners' reasoning) by semantic similarity, so it finds sessions described differently from the query. Scope with `scanner_id` to search one scanner, otherwise every scanner the caller can read is searched. Narrow by exact outcome with `verdict` (comma-separated, e.g. `yes,inconclusive`), `tags` (comma-separated classifier tags), and `min_score`/`max_score` (scorer bounds). These filter, while `q` ranks. `limit` defaults to 20 (max 50). Use `vision-observations-retrieve` for a result's full detail, or `vision-observations-list` for everything observed about one session.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Semantically search replay vision observations",
+ "title": "Semantically search replay vision observations",
+ "required_scopes": ["replay_scanner:read", "session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "requires_ai_consent": true
+ },
"vision-quota-retrieve": {
"description": "Get the organization's Replay vision credit budget (1 credit = $0.01; observations cost credits by model). Returns `credit_limit` (null when uncapped), `credits_used` (in-flight + succeeded observations counted against it), `remaining`, `exhausted`, `projected_monthly_credits`, and the `period_start`/`period_end` of the current budget window (the org's billing period, or the calendar month when billing hasn't synced). Check `remaining`/`exhausted` before creating a scanner or calling `vision-scanners-scan-session`: over budget, a scanner's scheduled sweeps silently skip their observations until the next period, while `vision-scanners-scan-session` is rejected outright with a 402. Pair with `vision-scanners-estimate-create` to size a new scanner against the remaining budget.",
"category": "Replay vision",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index dd3a52f4bc78..2ebab6aaae2f 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -50734,6 +50734,172 @@ export namespace Schemas {
version_markers: ObservationVersionMarker[];
}
+ /**
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `succeeded` - Succeeded
+ * * `failed` - Failed
+ * * `ineligible` - Ineligible
+ */
+ export type ObservationStatusEnum = typeof ObservationStatusEnum[keyof typeof ObservationStatusEnum];
+
+
+ export const ObservationStatusEnum = {
+ Pending: 'pending',
+ Running: 'running',
+ Succeeded: 'succeeded',
+ Failed: 'failed',
+ Ineligible: 'ineligible',
+ } as const;
+
+ /**
+ * Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.
+ */
+ export interface ScannerSnapshot {
+ /** Scanner name at run time. */
+ name: string;
+ /** Scanner type (monitor, classifier, scorer, summarizer) at run time.
+ *
+ * * `monitor` - Monitor
+ * * `classifier` - Classifier
+ * * `scorer` - Scorer
+ * * `summarizer` - Summarizer */
+ scanner_type: ScannerTypeEnum;
+ /** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */
+ scanner_version: number;
+ /** Concrete model that ran the observation; historical rows may carry since-retired model ids. */
+ model: string;
+ /** Concrete provider that ran the observation; historical rows may carry since-retired providers. */
+ provider: string;
+ /** Whether the observation was run with Signal emission enabled. */
+ emits_signals: boolean;
+ /** Scanner-type-specific configuration at run time (prompt, tags, scale, etc.). */
+ scanner_config: unknown;
+ }
+
+ /**
+ * Mirrors `temporal.types.ScannerResult` for OpenAPI generation.
+ */
+ export interface ScannerResult {
+ /** Validated scanner output. Shape depends on `scanner_snapshot.scanner_type`; always carries `confidence` and `scanner_type`. */
+ model_output: unknown;
+ /**
+ * Number of PostHog Signals emitted from this observation.
+ * @minimum 0
+ */
+ signals_count: number;
+ }
+
+ /**
+ * * `schedule` - Schedule
+ * * `on_demand` - On demand
+ * * `retry` - Retry
+ * * `backfill` - Backfill
+ */
+ export type ObservationTriggerEnum = typeof ObservationTriggerEnum[keyof typeof ObservationTriggerEnum];
+
+
+ export const ObservationTriggerEnum = {
+ Schedule: 'schedule',
+ OnDemand: 'on_demand',
+ Retry: 'retry',
+ Backfill: 'backfill',
+ } as const;
+
+ /**
+ * The team's shared judgement on whether the scanner scored this session correctly.
+ */
+ export interface ReplayObservationLabel {
+ /** True if the scanner scored this session correctly, false if not. */
+ is_correct: boolean;
+ /**
+ * Optional written context on the rating, for thumbs-up and thumbs-down alike: what the scanner got right or wrong, or what it should have concluded.
+ * @maxLength 5000
+ */
+ feedback?: string;
+ }
+
+ export interface ReplayObservation {
+ readonly id: string;
+ /** The scanner that produced this observation. */
+ readonly scanner_id: string;
+ /** Session recording id this scanner was applied to. */
+ readonly session_id: string;
+ /** Observation status (pending, running, succeeded, failed, ineligible).
+ *
+ * * `pending` - Pending
+ * * `running` - Running
+ * * `succeeded` - Succeeded
+ * * `failed` - Failed
+ * * `ineligible` - Ineligible */
+ readonly status: ObservationStatusEnum;
+ /** Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events / no_snapshots. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned. */
+ readonly error_reason: string;
+ /** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
+ readonly workflow_id: string;
+ /** Frozen view of the scanner at run time; scanner edits do not retroactively mutate this observation. */
+ readonly scanner_snapshot: ScannerSnapshot | null;
+ /** Result data persisted on success; null until the observation succeeds. */
+ readonly scanner_result: ScannerResult | null;
+ /** Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.
+ *
+ * * `schedule` - Schedule
+ * * `on_demand` - On demand
+ * * `retry` - Retry
+ * * `backfill` - Backfill */
+ readonly triggered_by: ObservationTriggerEnum;
+ /** User who triggered an on-demand observation; null for scheduled observations. */
+ readonly triggered_by_user: UserBasic | null;
+ /**
+ * Backfill that dispatched this observation; null for live, on-demand, and retry triggers.
+ * @nullable
+ */
+ readonly backfill_id: string | null;
+ /**
+ * Distinct id of the person in the recorded session (the subject being watched); null if unknown.
+ * @nullable
+ */
+ readonly distinct_id: string | null;
+ /**
+ * Email of the person in the recorded session (the subject being watched, not the user who triggered the observation), captured at scan time. Null when the session had no identified person.
+ * @nullable
+ */
+ readonly recording_subject_email: string | null;
+ /**
+ * Id of the preceding sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the start of the set.
+ * @nullable
+ */
+ readonly previous_observation_id: string | null;
+ /**
+ * Id of the following sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the end of the set.
+ * @nullable
+ */
+ readonly next_observation_id: string | null;
+ /** The team's shared label on this observation (correct/incorrect + feedback), or null if unlabeled. */
+ readonly label: ReplayObservationLabel | null;
+ /** @nullable */
+ started_at?: string | null;
+ /** @nullable */
+ completed_at?: string | null;
+ readonly created_at: string;
+ }
+
+ export interface ObservationSearchResult {
+ /** The matching observation. */
+ observation: ReplayObservation;
+ /** Cosine distance between the search text and the observation's closest embedding. Lower is a closer match. Only comparable to other results in the same response. */
+ distance: number;
+ /** Excerpt of the observation text that best matched the search, truncated. Empty for observations analyzed before excerpts were stored. */
+ matched_content: string;
+ }
+
+ export interface ObservationSearchResponse {
+ /** Matching observations, most relevant first. */
+ results: ObservationSearchResult[];
+ /** True when more matches may exist beyond `results`, so the response is a top slice rather than everything that matched. */
+ truncated: boolean;
+ }
+
export interface ObservationStatusCounts {
/** Total observations in the filtered set. */
total: number;
@@ -50813,40 +50979,6 @@ export namespace Schemas {
summarizer: SummarizerStats | null;
}
- /**
- * * `pending` - Pending
- * * `running` - Running
- * * `succeeded` - Succeeded
- * * `failed` - Failed
- * * `ineligible` - Ineligible
- */
- export type ObservationStatusEnum = typeof ObservationStatusEnum[keyof typeof ObservationStatusEnum];
-
-
- export const ObservationStatusEnum = {
- Pending: 'pending',
- Running: 'running',
- Succeeded: 'succeeded',
- Failed: 'failed',
- Ineligible: 'ineligible',
- } as const;
-
- /**
- * * `schedule` - Schedule
- * * `on_demand` - On demand
- * * `retry` - Retry
- * * `backfill` - Backfill
- */
- export type ObservationTriggerEnum = typeof ObservationTriggerEnum[keyof typeof ObservationTriggerEnum];
-
-
- export const ObservationTriggerEnum = {
- Schedule: 'schedule',
- OnDemand: 'on_demand',
- Retry: 'retry',
- Backfill: 'backfill',
- } as const;
-
/**
* 200 from POST /vision/scanners/{id}/observe/ - nothing started, the answer already exists.
*/
@@ -53551,122 +53683,6 @@ export namespace Schemas {
results: Reminder[];
}
- /**
- * Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.
- */
- export interface ScannerSnapshot {
- /** Scanner name at run time. */
- name: string;
- /** Scanner type (monitor, classifier, scorer, summarizer) at run time.
- *
- * * `monitor` - Monitor
- * * `classifier` - Classifier
- * * `scorer` - Scorer
- * * `summarizer` - Summarizer */
- scanner_type: ScannerTypeEnum;
- /** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */
- scanner_version: number;
- /** Concrete model that ran the observation; historical rows may carry since-retired model ids. */
- model: string;
- /** Concrete provider that ran the observation; historical rows may carry since-retired providers. */
- provider: string;
- /** Whether the observation was run with Signal emission enabled. */
- emits_signals: boolean;
- /** Scanner-type-specific configuration at run time (prompt, tags, scale, etc.). */
- scanner_config: unknown;
- }
-
- /**
- * Mirrors `temporal.types.ScannerResult` for OpenAPI generation.
- */
- export interface ScannerResult {
- /** Validated scanner output. Shape depends on `scanner_snapshot.scanner_type`; always carries `confidence` and `scanner_type`. */
- model_output: unknown;
- /**
- * Number of PostHog Signals emitted from this observation.
- * @minimum 0
- */
- signals_count: number;
- }
-
- /**
- * The team's shared judgement on whether the scanner scored this session correctly.
- */
- export interface ReplayObservationLabel {
- /** True if the scanner scored this session correctly, false if not. */
- is_correct: boolean;
- /**
- * Optional written context on the rating, for thumbs-up and thumbs-down alike: what the scanner got right or wrong, or what it should have concluded.
- * @maxLength 5000
- */
- feedback?: string;
- }
-
- export interface ReplayObservation {
- readonly id: string;
- /** The scanner that produced this observation. */
- readonly scanner_id: string;
- /** Session recording id this scanner was applied to. */
- readonly session_id: string;
- /** Observation status (pending, running, succeeded, failed, ineligible).
- *
- * * `pending` - Pending
- * * `running` - Running
- * * `succeeded` - Succeeded
- * * `failed` - Failed
- * * `ineligible` - Ineligible */
- readonly status: ObservationStatusEnum;
- /** Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events / no_snapshots. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned. */
- readonly error_reason: string;
- /** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
- readonly workflow_id: string;
- /** Frozen view of the scanner at run time; scanner edits do not retroactively mutate this observation. */
- readonly scanner_snapshot: ScannerSnapshot | null;
- /** Result data persisted on success; null until the observation succeeds. */
- readonly scanner_result: ScannerResult | null;
- /** Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.
- *
- * * `schedule` - Schedule
- * * `on_demand` - On demand
- * * `retry` - Retry
- * * `backfill` - Backfill */
- readonly triggered_by: ObservationTriggerEnum;
- /** User who triggered an on-demand observation; null for scheduled observations. */
- readonly triggered_by_user: UserBasic | null;
- /**
- * Backfill that dispatched this observation; null for live, on-demand, and retry triggers.
- * @nullable
- */
- readonly backfill_id: string | null;
- /**
- * Distinct id of the person in the recorded session (the subject being watched); null if unknown.
- * @nullable
- */
- readonly distinct_id: string | null;
- /**
- * Email of the person in the recorded session (the subject being watched, not the user who triggered the observation), captured at scan time. Null when the session had no identified person.
- * @nullable
- */
- readonly recording_subject_email: string | null;
- /**
- * Id of the preceding sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the start of the set.
- * @nullable
- */
- readonly previous_observation_id: string | null;
- /**
- * Id of the following sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the end of the set.
- * @nullable
- */
- readonly next_observation_id: string | null;
- /** The team's shared label on this observation (correct/incorrect + feedback), or null if unlabeled. */
- readonly label: ReplayObservationLabel | null;
- /** @nullable */
- started_at?: string | null;
- /** @nullable */
- completed_at?: string | null;
- readonly created_at: string;
- }
-
export interface PaginatedReplayObservationList {
count: number;
/** @nullable */
@@ -96197,6 +96213,43 @@ export namespace Schemas {
verdict?: string;
};
+ export type VisionObservationsSearchRetrieveParams = {
+ /**
+ * Maximum number of results (default 20, at most 50).
+ * @minimum 1
+ * @maximum 50
+ */
+ limit?: number;
+ /**
+ * Keep only scorer observations with a score at or below this value.
+ */
+ max_score?: number;
+ /**
+ * Keep only scorer observations with a score at or above this value.
+ */
+ min_score?: number;
+ /**
+ * Natural-language description of what to find, e.g. 'users confused by the pricing page'.
+ * @minLength 1
+ * @maxLength 2000
+ */
+ q: string;
+ /**
+ * Search a single scanner's observations. Defaults to every scanner you can read.
+ */
+ scanner_id?: string;
+ /**
+ * Comma-separated classifier tags to keep. Matching is case- and format-insensitive. Unlike `verdict`, tags are not validated against a fixed list, so an unknown tag matches nothing.
+ * @minLength 1
+ */
+ tags?: string;
+ /**
+ * Comma-separated monitor verdicts to keep, e.g. `yes,inconclusive`.
+ * @minLength 1
+ */
+ verdict?: string;
+ };
+
export type VisionScannersListParams = {
/**
* Filter to scanners created by the given user IDs (comma-separated).
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 93d434685fe6..647f6fb48fbf 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 29 enabled ops
+ * PostHog API - MCP 30 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -471,7 +471,8 @@ export const VisionActionsRunsRetrieveParams = /* @__PURE__ */ zod.object({
})
/**
- * Read-only access to a session's observations across every scanner the caller can read, for the replay-page dock.
+ * A session's observations across every scanner the caller can read, plus the team-level semantic
+ * `search` action, which resolves its own scanner scope instead of this queryset.
*/
export const VisionObservationsListParams = /* @__PURE__ */ zod.object({
project_id: zod
@@ -610,6 +611,55 @@ export const VisionObservationsLabelDestroyParams = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Rank observations by semantic similarity to the search text, optionally filtered by exact outcome
+ * (verdict, score, tags).
+ */
+export const VisionObservationsSearchRetrieveParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const visionObservationsSearchRetrieveQueryLimitDefault = 20
+export const visionObservationsSearchRetrieveQueryLimitMax = 50
+
+export const visionObservationsSearchRetrieveQueryQMax = 2000
+
+export const VisionObservationsSearchRetrieveQueryParams = /* @__PURE__ */ zod.object({
+ limit: zod
+ .number()
+ .min(1)
+ .max(visionObservationsSearchRetrieveQueryLimitMax)
+ .default(visionObservationsSearchRetrieveQueryLimitDefault)
+ .describe('Maximum number of results (default 20, at most 50).'),
+ max_score: zod.number().optional().describe('Keep only scorer observations with a score at or below this value.'),
+ min_score: zod.number().optional().describe('Keep only scorer observations with a score at or above this value.'),
+ q: zod
+ .string()
+ .min(1)
+ .max(visionObservationsSearchRetrieveQueryQMax)
+ .describe("Natural-language description of what to find, e.g. 'users confused by the pricing page'."),
+ scanner_id: zod
+ .string()
+ .optional()
+ .describe("Search a single scanner's observations. Defaults to every scanner you can read."),
+ tags: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe(
+ 'Comma-separated classifier tags to keep. Matching is case- and format-insensitive. Unlike `verdict`, tags are not validated against a fixed list, so an unknown tag matches nothing.'
+ ),
+ verdict: zod
+ .string()
+ .min(1)
+ .optional()
+ .describe('Comma-separated monitor verdicts to keep, e.g. `yes,inconclusive`.'),
+})
+
export const EnvironmentVisionQuotaRetrieveParams = /* @__PURE__ */ zod.object({
project_id: zod
.string()
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index 335e8479abae..fd6f84e332e6 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -18,6 +18,7 @@ import {
VisionObservationsListQueryParams,
VisionObservationsRetrieveParams,
VisionObservationsRetrieveQueryParams,
+ VisionObservationsSearchRetrieveQueryParams,
VisionScannersAffectedCohortCreateBody,
VisionScannersAffectedCohortCreateParams,
VisionScannersCreateBody,
@@ -362,6 +363,33 @@ const visionObservationsRetrieve = (): ToolBase<
},
})
+const VisionObservationsSearchSchema = VisionObservationsSearchRetrieveQueryParams
+
+const visionObservationsSearch = (): ToolBase<
+ typeof VisionObservationsSearchSchema,
+ Schemas.ObservationSearchResponse
+> => ({
+ name: 'vision-observations-search',
+ schema: VisionObservationsSearchSchema,
+ handler: async (context: Context, params: z.infer<typeof VisionObservationsSearchSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.ObservationSearchResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/observations/search/`,
+ query: {
+ limit: params.limit,
+ max_score: params.max_score,
+ min_score: params.min_score,
+ q: params.q,
+ scanner_id: params.scanner_id,
+ tags: params.tags,
+ verdict: params.verdict,
+ },
+ })
+ return result
+ },
+})
+
const VisionQuotaRetrieveSchema = z.object({})
const visionQuotaRetrieve = (): ToolBase<typeof VisionQuotaRetrieveSchema, Schemas.VisionQuota> => ({
@@ -936,6 +964,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'vision-observations-label-destroy': visionObservationsLabelDestroy,
'vision-observations-list': visionObservationsList,
'vision-observations-retrieve': visionObservationsRetrieve,
+ 'vision-observations-search': visionObservationsSearch,
'vision-quota-retrieve': visionQuotaRetrieve,
'vision-scanners-affected-cohort-create': visionScannersAffectedCohortCreate,
'vision-scanners-create': visionScannersCreate,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-search.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-search.json
new file mode 100644
index 000000000000..4b626b654a29
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-observations-search.json
@@ -0,0 +1,42 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "limit": {
+ "default": 20,
+ "description": "Maximum number of results (default 20, at most 50).",
+ "maximum": 50,
+ "minimum": 1,
+ "type": "number"
+ },
+ "max_score": {
+ "description": "Keep only scorer observations with a score at or below this value.",
+ "type": "number"
+ },
+ "min_score": {
+ "description": "Keep only scorer observations with a score at or above this value.",
+ "type": "number"
+ },
+ "q": {
+ "description": "Natural-language description of what to find, e.g. 'users confused by the pricing page'.",
+ "maxLength": 2000,
+ "minLength": 1,
+ "type": "string"
+ },
+ "scanner_id": {
+ "description": "Search a single scanner's observations. Defaults to every scanner you can read.",
+ "type": "string"
+ },
+ "tags": {
+ "description": "Comma-separated classifier tags to keep. Matching is case- and format-insensitive. Unlike `verdict`, tags are not validated against a fixed list, so an unknown tag matches nothing.",
+ "minLength": 1,
+ "type": "string"
+ },
+ "verdict": {
+ "description": "Comma-separated monitor verdicts to keep, e.g. `yes,inconclusive`.",
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": ["q"],
+ "type": "object"
+}