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): let threshold alerts fire at or below a value (#71292)

Kim Svatos Duganf78bfe10f4ae
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index c78e4da43d6a..f7195a53eceb 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -577,6 +577,7 @@ SPECTACULAR_SETTINGS = {
"ExportedRecordingStatusEnum": "products.replay.backend.models.exported_recording.ExportedRecording.Status",
"VisionActionRunStatusEnum": "products.replay_vision.backend.models.vision_action.VisionActionRunStatus",
"VisionAlertMetricEnum": "products.replay_vision.backend.models.vision_action.AlertMetric",
+ "VisionAlertDirectionEnum": "products.replay_vision.backend.models.vision_action.AlertDirection",
"AutonomyPriorityEnum": "products.signals.backend.models.AutonomyPriority",
"UserInterviewSearchDocumentTypeEnum": "products.user_interviews.backend.facade.enums.SEARCH_DOCUMENT_TYPES",
"BatchExportRunStatusEnum": "products.batch_exports.backend.models.batch_export.BatchExportRun.Status",
diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.py
index 40f2ef971e42..408120dd77e2 100644
--- a/products/replay_vision/backend/api/vision_actions.py
+++ b/products/replay_vision/backend/api/vision_actions.py
@@ -27,6 +27,7 @@ from products.replay_vision.backend.models.replay_observation import ReplayObser
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
from products.replay_vision.backend.models.vision_action import (
ActionMode,
+ AlertDirection,
AlertFrequency,
AlertMetric,
TriggerType,
@@ -118,8 +119,18 @@ class AlertConfigSerializer(serializers.Serializer):
threshold = serializers.FloatField(
required=False,
help_text=(
- "The alert fires when the metric is at or above this value. Required for on_breach; "
- "ignored for every_match."
+ "The alert fires when the metric is at or above ('above') or at or below ('below') this "
+ "value, per 'direction'. Required for on_breach; ignored for every_match."
+ ),
+ )
+ direction = serializers.ChoiceField(
+ choices=AlertDirection.choices,
+ required=False,
+ default=AlertDirection.ABOVE,
+ help_text=(
+ "Which side of the threshold breaches: 'above' fires when the metric is at or above it, "
+ "'below' when at or below (e.g. an average score dropping under a floor). Both inclusive. "
+ "Defaults to 'above'; ignored for every_match."
),
)
window_days = serializers.ChoiceField(
diff --git a/products/replay_vision/backend/models/vision_action.py b/products/replay_vision/backend/models/vision_action.py
index a94cfb7ff1c2..25404e9f20c7 100644
--- a/products/replay_vision/backend/models/vision_action.py
+++ b/products/replay_vision/backend/models/vision_action.py
@@ -38,6 +38,12 @@ class AlertMetric(models.TextChoices):
AVG_SCORE = "avg_score", "Average score" # scorer scanners only
+class AlertDirection(models.TextChoices):
+ # Which side of the threshold breaches. Both bounds are inclusive.
+ ABOVE = "above", "At or above"
+ BELOW = "below", "At or below"
+
+
class VisionAction(TeamScopedRootMixin, UUIDModel):
"""An "and then…" automation over a scanner's observations: gather, (optionally) synthesize, deliver.
diff --git a/products/replay_vision/backend/temporal/vision_actions/alerts.py b/products/replay_vision/backend/temporal/vision_actions/alerts.py
index d83b0045bacc..a6d951acf781 100644
--- a/products/replay_vision/backend/temporal/vision_actions/alerts.py
+++ b/products/replay_vision/backend/temporal/vision_actions/alerts.py
@@ -24,6 +24,7 @@ from posthog.sync import database_sync_to_async
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.vision_action import (
+ AlertDirection,
AlertFrequency,
AlertMetric,
VisionActionRun,
@@ -150,10 +151,13 @@ def _evaluate(inputs: EvaluateAlertInputs) -> EvaluateAlertResult:
else:
metric_value = float(matched_count)
- # No measurable data (e.g. avg over an empty window) can't breach anything — including a
- # "count lt N" condition, which zero observations WOULD satisfy; count is always measurable (0).
- # The only condition shape is "metric at or above threshold" — see AlertConfigSerializer.
- if metric_value is None or metric_value < threshold:
+ # The condition is "metric at or above/below the threshold" (inclusive, per direction — see
+ # AlertConfigSerializer). No measurable data (avg over an empty window) can't breach in either
+ # direction; count is always measurable (0), so a below-direction count alert DOES fire on a
+ # quiet window — that's its "went quiet" meaning.
+ below = alert_config.get("direction") == AlertDirection.BELOW
+ breached = metric_value is not None and (metric_value <= threshold if below else metric_value >= threshold)
+ if not breached:
return EvaluateAlertResult(
status=AlertStatus.NOT_BREACHED, observation_count=matched_count, metric_value=metric_value
)
@@ -279,9 +283,10 @@ def _alert_markdown(
window_days = alert_config.get("window_days", DEFAULT_ALERT_WINDOW_DAYS)
metric_label = "average score" if metric == AlertMetric.AVG_SCORE else "matching observations"
window_label = "24 hours" if window_days == 1 else f"{window_days} days"
+ bound = "at or below" if alert_config.get("direction") == AlertDirection.BELOW else "at or above"
lines = [
f"**Alert: {scanner_name}** — {metric_label} over the last {window_label} was "
- f"{_format_number(metric_value)}, at or above the threshold of {_format_number(threshold)}.",
+ f"{_format_number(metric_value)}, {bound} the threshold of {_format_number(threshold)}.",
"",
f"{matched_count} {noun} matched in this window.",
]
diff --git a/products/replay_vision/backend/tests/test_vision_action_alerts.py b/products/replay_vision/backend/tests/test_vision_action_alerts.py
index 75c1d128e479..4b77b1e9f0fa 100644
--- a/products/replay_vision/backend/tests/test_vision_action_alerts.py
+++ b/products/replay_vision/backend/tests/test_vision_action_alerts.py
@@ -122,16 +122,19 @@ class TestVisionActionAlerts(BaseTest):
@parameterized.expand(
[
- ("below_threshold", 3, AlertStatus.NOT_BREACHED),
- ("at_threshold", 2, AlertStatus.FIRED),
+ # direction defaults to above: fires when the metric is at or above the threshold.
+ ("above_under_threshold", {"threshold": 3}, AlertStatus.NOT_BREACHED),
+ ("above_at_threshold", {"threshold": 2}, AlertStatus.FIRED),
+ # below inverts the comparison (inclusive): fires when the metric is at or below it.
+ ("below_at_threshold", {"threshold": 2, "direction": "below"}, AlertStatus.FIRED),
+ ("below_over_threshold", {"threshold": 1, "direction": "below"}, AlertStatus.NOT_BREACHED),
]
)
- def test_threshold_semantics_over_count(self, _label: str, threshold: float, expected: AlertStatus) -> None:
- # The only condition shape is "metric at or above threshold" — the operator knob was dropped.
+ def test_threshold_semantics_over_count(self, _label: str, config: dict, expected: AlertStatus) -> None:
scanner = self._scanner(name=f"ops-{_label}")
self._observation(scanner, {"verdict": "yes"})
self._observation(scanner, {"verdict": "no"}, session_id="s2")
- action = self._alert(scanner, {"metric": "count", "threshold": threshold})
+ action = self._alert(scanner, {"metric": "count", **config})
result, run = self._evaluate(action)
@@ -140,6 +143,17 @@ class TestVisionActionAlerts(BaseTest):
run.refresh_from_db()
self.assertEqual(run.synthesized_markdown, "")
+ def test_below_direction_message_says_at_or_below(self) -> None:
+ scanner = self._scanner(scanner_type=ScannerType.SCORER, name="floor-scorer")
+ self._observation(scanner, {"score": 2})
+ action = self._alert(scanner, {"metric": "avg_score", "threshold": 3, "direction": "below"})
+
+ result, run = self._evaluate(action)
+
+ self.assertEqual(result.status, AlertStatus.FIRED)
+ run.refresh_from_db()
+ self.assertIn("at or below the threshold of 3", run.synthesized_markdown)
+
def test_slack_output_escapes_mrkdwn_control_sequences(self) -> None:
# Freeform tags are observation-derived untrusted text that the alert message interpolates
# verbatim; Slack treats <...> as control sequences, so an unescaped `<!channel>` tag would
@@ -194,10 +208,13 @@ class TestVisionActionAlerts(BaseTest):
run.refresh_from_db()
self.assertIn("average score over the last 24 hours was 3", run.synthesized_markdown)
- def test_avg_over_empty_window_never_fires(self) -> None:
- # An unmeasurable metric must not breach — a None average must not be coerced to a comparable 0.
- scanner = self._scanner(scanner_type=ScannerType.SCORER, name="quiet-scorer")
- action = self._alert(scanner, {"metric": "avg_score", "threshold": 0})
+ @parameterized.expand([("above", "above"), ("below", "below")])
+ def test_avg_over_empty_window_never_fires(self, _label: str, direction: str) -> None:
+ # An unmeasurable metric must not breach in either direction — a None average must not be
+ # coerced to a comparable 0 (below would otherwise fire on every quiet window).
+ scanner = self._scanner(scanner_type=ScannerType.SCORER, name=f"quiet-scorer-{_label}")
+ threshold = 0 if direction == "above" else 100
+ action = self._alert(scanner, {"metric": "avg_score", "threshold": threshold, "direction": direction})
result, _ = self._evaluate(action)
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 976bb8a6b217..46d88f11e084 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -104,6 +104,17 @@ export const VisionAlertMetricEnumApi = {
AvgScore: 'avg_score',
} as const
+/**
+ * * `above` - At or above
+ * * `below` - At or below
+ */
+export type VisionAlertDirectionEnumApi = (typeof VisionAlertDirectionEnumApi)[keyof typeof VisionAlertDirectionEnumApi]
+
+export const VisionAlertDirectionEnumApi = {
+ Above: 'above',
+ Below: 'below',
+} as const
+
/**
* * `1` - 1 day
* * `3` - 3 days
@@ -137,8 +148,13 @@ export interface AlertConfigApi {
* * `count` - Count of matching observations
* * `avg_score` - Average score */
metric?: VisionAlertMetricEnumApi
- /** The alert fires when the metric is at or above this value. Required for on_breach; ignored for every_match. */
+ /** The alert fires when the metric is at or above ('above') or at or below ('below') this value, per 'direction'. Required for on_breach; ignored for every_match. */
threshold?: number
+ /** Which side of the threshold breaches: 'above' fires when the metric is at or above it, 'below' when at or below (e.g. an average score dropping under a floor). Both inclusive. Defaults to 'above'; ignored for every_match.
+ *
+ * * `above` - At or above
+ * * `below` - At or below */
+ direction?: VisionAlertDirectionEnumApi
/** Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).
*
* * `1` - 1 day
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index d94951333163..710beb0b48b6 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -19,6 +19,7 @@ export const visionActionsCreateBodySynthesisConfigOnePromptGuideMax = 500
export const visionActionsCreateBodyAlertConfigOneFrequencyDefault = `on_breach`
export const visionActionsCreateBodyAlertConfigOneMetricDefault = `count`
+export const visionActionsCreateBodyAlertConfigOneDirectionDefault = `above`
export const VisionActionsCreateBody = /* @__PURE__ */ zod.object({
name: zod
@@ -126,7 +127,14 @@ export const VisionActionsCreateBody = /* @__PURE__ */ zod.object({
.number()
.optional()
.describe(
- 'The alert fires when the metric is at or above this value. Required for on_breach; ignored for every_match.'
+ "The alert fires when the metric is at or above ('above') or at or below ('below') this value, per 'direction'. Required for on_breach; ignored for every_match."
+ ),
+ direction: zod
+ .enum(['above', 'below'])
+ .describe('\* `above` - At or above\n\* `below` - At or below')
+ .default(visionActionsCreateBodyAlertConfigOneDirectionDefault)
+ .describe(
+ "Which side of the threshold breaches: 'above' fires when the metric is at or above it, 'below' when at or below (e.g. an average score dropping under a floor). Both inclusive. Defaults to 'above'; ignored for every_match.\n\n\* `above` - At or above\n\* `below` - At or below"
),
window_days: zod
.union([zod.literal(1), zod.literal(3), zod.literal(7), zod.literal(14), zod.literal(30)])
@@ -170,6 +178,7 @@ export const visionActionsPartialUpdateBodySynthesisConfigOnePromptGuideMax = 50
export const visionActionsPartialUpdateBodyAlertConfigOneFrequencyDefault = `on_breach`
export const visionActionsPartialUpdateBodyAlertConfigOneMetricDefault = `count`
+export const visionActionsPartialUpdateBodyAlertConfigOneDirectionDefault = `above`
export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod.object({
name: zod
@@ -281,7 +290,14 @@ export const VisionActionsPartialUpdateBody = /* @__PURE__ */ zod.object({
.number()
.optional()
.describe(
- 'The alert fires when the metric is at or above this value. Required for on_breach; ignored for every_match.'
+ "The alert fires when the metric is at or above ('above') or at or below ('below') this value, per 'direction'. Required for on_breach; ignored for every_match."
+ ),
+ direction: zod
+ .enum(['above', 'below'])
+ .describe('\* `above` - At or above\n\* `below` - At or below')
+ .default(visionActionsPartialUpdateBodyAlertConfigOneDirectionDefault)
+ .describe(
+ "Which side of the threshold breaches: 'above' fires when the metric is at or above it, 'below' when at or below (e.g. an average score dropping under a floor). Both inclusive. Defaults to 'above'; ignored for every_match.\n\n\* `above` - At or above\n\* `below` - At or below"
),
window_days: zod
.union([zod.literal(1), zod.literal(3), zod.literal(7), zod.literal(14), zod.literal(30)])
diff --git a/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx
index 41cdc799b7fd..b5ec0bc887d0 100644
--- a/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ActionEditorScene.tsx
@@ -27,6 +27,7 @@ import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackBu
import {
AlertConfigFrequencyEnumApi,
VisionActionModeEnumApi,
+ VisionAlertDirectionEnumApi,
VisionAlertMetricEnumApi,
} from '../generated/api.schemas'
import { actionEditorSceneLogic } from './actionEditorSceneLogic'
@@ -457,7 +458,16 @@ function ConditionSection({ scannerId }: { scannerId: string }): JSX.Element {
options={WINDOW_OPTIONS}
data-attr="vision-action-alert-window"
/>
- <span className="text-sm">is at least</span>
+ <LemonSelect
+ size="small"
+ value={actionForm.alert_direction}
+ onChange={(value) => value && setActionFormValue('alert_direction', value)}
+ options={[
+ { value: VisionAlertDirectionEnumApi.Above, label: 'is at least' },
+ { value: VisionAlertDirectionEnumApi.Below, label: 'is at most' },
+ ]}
+ data-attr="vision-action-alert-direction"
+ />
<LemonInput
type="number"
size="small"
diff --git a/products/replay_vision/frontend/replay_scanners/actionEditorSceneLogic.test.ts b/products/replay_vision/frontend/replay_scanners/actionEditorSceneLogic.test.ts
index 3e47be44a677..17c0764f2247 100644
--- a/products/replay_vision/frontend/replay_scanners/actionEditorSceneLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/actionEditorSceneLogic.test.ts
@@ -27,7 +27,7 @@ const existingAlert = {
name: 'alert-a',
mode: 'alert',
selection: { tags: ['rage-click'] },
- alert_config: { frequency: 'on_breach', metric: 'count', operator: 'gte', threshold: 3, window_days: 7 },
+ alert_config: { frequency: 'on_breach', metric: 'count', threshold: 3, direction: 'below', window_days: 7 },
} as unknown as VisionActionApi
const summarizerAlert = {
@@ -98,6 +98,7 @@ describe('actionEditorSceneLogic', () => {
alert_frequency: 'every_match',
alert_metric: 'count',
alert_threshold: 1,
+ alert_direction: 'above',
alert_window_days: 1,
},
})
@@ -121,6 +122,7 @@ describe('actionEditorSceneLogic', () => {
alert_frequency: 'on_breach',
alert_metric: 'count',
alert_threshold: 3,
+ alert_direction: 'below',
alert_window_days: 7,
tags: ['rage-click'],
}),
diff --git a/products/replay_vision/frontend/replay_scanners/actionEditorSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/actionEditorSceneLogic.ts
index 92c5756a859e..444b6adaaf1c 100644
--- a/products/replay_vision/frontend/replay_scanners/actionEditorSceneLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/actionEditorSceneLogic.ts
@@ -18,6 +18,7 @@ import {
import {
AlertConfigFrequencyEnumApi,
VisionActionModeEnumApi,
+ VisionAlertDirectionEnumApi,
VisionAlertMetricEnumApi,
} from '../generated/api.schemas'
import type { VisionActionApi } from '../generated/api.schemas'
@@ -303,6 +304,7 @@ export const actionEditorSceneLogic = kea<actionEditorSceneLogicType>([
: AlertConfigFrequencyEnumApi.EveryMatch),
alert_metric: action.alert_config?.metric ?? VisionAlertMetricEnumApi.Count,
alert_threshold: action.alert_config?.threshold ?? 1,
+ alert_direction: action.alert_config?.direction ?? VisionAlertDirectionEnumApi.Above,
alert_window_days: action.alert_config?.window_days ?? 1,
verdict: action.selection?.verdict ?? [],
tags: action.selection?.tags ?? [],
diff --git a/products/replay_vision/frontend/replay_scanners/visionActionsLogic.test.ts b/products/replay_vision/frontend/replay_scanners/visionActionsLogic.test.ts
index c4bc91411ef5..d31e16f17939 100644
--- a/products/replay_vision/frontend/replay_scanners/visionActionsLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/visionActionsLogic.test.ts
@@ -104,6 +104,7 @@ describe('visionActionsLogic', () => {
alert_frequency: 'on_breach',
alert_metric: 'count',
alert_threshold: 1,
+ alert_direction: 'above',
alert_window_days: 1,
}
expect(buildActionBody(form, 's1')).toEqual({
@@ -135,6 +136,7 @@ describe('visionActionsLogic', () => {
alert_frequency: 'on_breach',
alert_metric: 'count',
alert_threshold: 1,
+ alert_direction: 'above',
alert_window_days: 1,
}
const body = buildActionBody(form, 's1')
@@ -161,6 +163,7 @@ describe('visionActionsLogic', () => {
alert_frequency: 'on_breach',
alert_metric: 'count',
alert_threshold: 1,
+ alert_direction: 'below',
alert_window_days: 1,
}
const body = buildActionBody(form, 's1')
@@ -169,6 +172,7 @@ describe('visionActionsLogic', () => {
frequency: 'on_breach',
metric: 'count',
threshold: 1,
+ direction: 'below',
window_days: 1,
})
expect(body.selection).toEqual({ tags: ['rage-click'] })
diff --git a/products/replay_vision/frontend/replay_scanners/visionActionsLogic.ts b/products/replay_vision/frontend/replay_scanners/visionActionsLogic.ts
index fddc5a260195..b3f676294d12 100644
--- a/products/replay_vision/frontend/replay_scanners/visionActionsLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/visionActionsLogic.ts
@@ -14,6 +14,7 @@ import {
AlertConfigFrequencyEnumApi,
DeliveryTargetTypeEnumApi,
VisionActionModeEnumApi,
+ VisionAlertDirectionEnumApi,
VisionAlertMetricEnumApi,
WindowDaysEnumApi,
} from '../generated/api.schemas'
@@ -43,6 +44,7 @@ export interface VisionActionForm {
alert_frequency: AlertConfigFrequencyEnumApi
alert_metric: VisionAlertMetricEnumApi
alert_threshold: number | null
+ alert_direction: VisionAlertDirectionEnumApi
alert_window_days: WindowDaysEnumApi
}
@@ -62,6 +64,7 @@ export const NEW_ACTION_FORM = (): VisionActionForm => ({
alert_frequency: AlertConfigFrequencyEnumApi.EveryMatch,
alert_metric: VisionAlertMetricEnumApi.Count,
alert_threshold: 1,
+ alert_direction: VisionAlertDirectionEnumApi.Above,
alert_window_days: 1,
})
@@ -105,6 +108,7 @@ export function buildActionBody(form: VisionActionForm, scannerId: string): Para
frequency: form.alert_frequency,
metric: form.alert_metric,
threshold: form.alert_threshold ?? 1,
+ direction: form.alert_direction,
window_days: form.alert_window_days,
},
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d5488dcfc50c..1a31db481ed2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9570,6 +9570,18 @@ export namespace Schemas {
AvgScore: 'avg_score',
} as const;
+ /**
+ * * `above` - At or above
+ * * `below` - At or below
+ */
+ export type VisionAlertDirectionEnum = typeof VisionAlertDirectionEnum[keyof typeof VisionAlertDirectionEnum];
+
+
+ export const VisionAlertDirectionEnum = {
+ Above: 'above',
+ Below: 'below',
+ } as const;
+
/**
* * `1` - 1 day
* * `3` - 3 days
@@ -9604,8 +9616,13 @@ export namespace Schemas {
* * `count` - Count of matching observations
* * `avg_score` - Average score */
metric?: VisionAlertMetricEnum;
- /** The alert fires when the metric is at or above this value. Required for on_breach; ignored for every_match. */
+ /** The alert fires when the metric is at or above ('above') or at or below ('below') this value, per 'direction'. Required for on_breach; ignored for every_match. */
threshold?: number;
+ /** Which side of the threshold breaches: 'above' fires when the metric is at or above it, 'below' when at or below (e.g. an average score dropping under a floor). Both inclusive. Defaults to 'above'; ignored for every_match.
+ *
+ * * `above` - At or above
+ * * `below` - At or below */
+ direction?: VisionAlertDirectionEnum;
/** Rolling lookback window for on_breach conditions, ending at each check. Defaults to 1 day. every_match ignores it (each check covers what's new since the previous one).
*
* * `1` - 1 day