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): persist a recovery run when an alert clears (#71680)

Kim Svatos Duganc47f460f2dbd
diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.py
index 408120dd77e2..0757fb84374e 100644
--- a/products/replay_vision/backend/api/vision_actions.py
+++ b/products/replay_vision/backend/api/vision_actions.py
@@ -621,6 +621,12 @@ class VisionActionRunListSerializer(serializers.ModelSerializer):
error_reason = serializers.SerializerMethodField(
help_text="Short human-readable reason a run skipped or failed; null on success.",
)
+ is_recovery = serializers.SerializerMethodField(
+ help_text=(
+ "True for the run recording an alert's condition clearing after a breach (the recovery "
+ "bookend in run history). False for alert firings and summaries."
+ ),
+ )
class Meta:
model = VisionActionRun
@@ -630,6 +636,7 @@ class VisionActionRunListSerializer(serializers.ModelSerializer):
"scheduled_at",
"observation_count",
"error_reason",
+ "is_recovery",
"created_at",
"updated_at",
]
@@ -649,6 +656,13 @@ class VisionActionRunListSerializer(serializers.ModelSerializer):
return "This run failed while generating the summary."
return None
+ @extend_schema_field(serializers.BooleanField())
+ def get_is_recovery(self, run: VisionActionRun) -> bool:
+ # The engine stamps recovery runs with output.recovered (alerts._persist_recovered) — the
+ # marker that distinguishes the bookend from a firing, since both persist a message.
+ output = run.output if isinstance(run.output, dict) else {}
+ return bool(output.get("recovered"))
+
class VisionActionRunSerializer(VisionActionRunListSerializer):
"""Full run detail: the list fields plus the synthesized report and the recordings it summarized."""
diff --git a/products/replay_vision/backend/temporal/vision_actions/alerts.py b/products/replay_vision/backend/temporal/vision_actions/alerts.py
index a6d951acf781..8430e483021f 100644
--- a/products/replay_vision/backend/temporal/vision_actions/alerts.py
+++ b/products/replay_vision/backend/temporal/vision_actions/alerts.py
@@ -158,6 +158,11 @@ def _evaluate(inputs: EvaluateAlertInputs) -> EvaluateAlertResult:
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:
+ # The check that observes the condition clearing after a breach persists a visible "recovered"
+ # run — the bookend that tells the user the firing is over. An unmeasurable metric (avg over an
+ # empty window) re-arms quietly instead: with no measurement there's no recovery to claim.
+ if previous is not None and previous_breached and metric_value is not None:
+ return _persist_recovered(run, action, alert_config, metric_value, matched_count, team)
return EvaluateAlertResult(
status=AlertStatus.NOT_BREACHED, observation_count=matched_count, metric_value=metric_value
)
@@ -172,11 +177,17 @@ def _evaluate(inputs: EvaluateAlertInputs) -> EvaluateAlertResult:
return _persist_fired(run, action, alert_config, metric_value, matched_count, observations_qs, team)
+def _is_recovery_run(run: VisionActionRun) -> bool:
+ output = run.output if isinstance(run.output, dict) else {}
+ return bool(output.get("recovered"))
+
+
def _last_evaluated_run(team_id: int, action_id: Any, exclude_pk: Any) -> tuple[VisionActionRun | None, bool]:
"""The most recent prior run whose outcome reflects the alert's state, and whether it observed a
- breach: a fired run (message persisted, even if delivery later failed) or an evaluated skip.
- Failed or interrupted checks are walked past so a transient failure can't re-arm a still-breached
- alert, and so an every-match window that a failed check never covered gets re-covered."""
+ breach: a run with a persisted message (fired = breached, recovered = cleared — even if delivery
+ later failed) or an evaluated skip. Failed or interrupted checks are walked past so a transient
+ failure can't re-arm a still-breached alert, and so an every-match window that a failed check
+ never covered gets re-covered."""
runs = (
VisionActionRun.objects.for_team(team_id)
.filter(vision_action_id=action_id)
@@ -185,13 +196,28 @@ def _last_evaluated_run(team_id: int, action_id: Any, exclude_pk: Any) -> tuple[
)
for prev in runs:
if prev.synthesized_markdown:
- return prev, True
+ return prev, not _is_recovery_run(prev)
error = prev.error if isinstance(prev.error, dict) else {}
if prev.status == VisionActionRunStatus.SKIPPED and error.get("skip_reason") in _EVALUATED_SKIP_REASONS:
return prev, error.get("skip_reason") == "still_breached"
return None, False
+def _breach_started_at(team_id: int, action_id: Any, exclude_pk: Any) -> datetime | None:
+ """When the current breach began: the most recent fired (non-recovery) run's tick. None when the
+ firing has scrolled past the scan limit — the recovery message then just omits the duration."""
+ runs = (
+ VisionActionRun.objects.for_team(team_id)
+ .filter(vision_action_id=action_id)
+ .exclude(pk=exclude_pk)
+ .order_by("-created_at")[:_STATE_SCAN_LIMIT]
+ )
+ for prev in runs:
+ if prev.synthesized_markdown and not _is_recovery_run(prev):
+ return prev.scheduled_at or prev.created_at
+ return None
+
+
def _persist_fired(
run: VisionActionRun,
action: Any,
@@ -228,6 +254,47 @@ def _persist_fired(
return EvaluateAlertResult(status=AlertStatus.FIRED, observation_count=matched_count, metric_value=metric_value)
+def _persist_recovered(
+ run: VisionActionRun,
+ action: Any,
+ alert_config: dict[str, Any],
+ metric_value: float,
+ matched_count: int,
+ team: Any,
+) -> EvaluateAlertResult:
+ """Persist the recovery bookend on the run: a short message that the condition cleared. The
+ `recovered` output marker is what distinguishes this from a firing everywhere a persisted message
+ implies breach — `_last_evaluated_run` state resolution and the API's `is_recovery` flag."""
+ threshold = alert_config.get("threshold", 0)
+ metric = alert_config.get("metric", AlertMetric.COUNT)
+ 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"
+ # Recovery means the metric sits strictly on the other side of the (inclusive) breach bound.
+ cleared_bound = "above" if alert_config.get("direction") == AlertDirection.BELOW else "below"
+ scanner_name = _scanner_display_name(action)
+
+ markdown = (
+ f"**Recovered: {scanner_name}** — {metric_label} over the last {window_label} is back at "
+ f"{_format_number(metric_value)}, {cleared_bound} the threshold of {_format_number(threshold)}."
+ )
+ started_at = _breach_started_at(team.id, action.id, run.pk)
+ if started_at is not None:
+ markdown += f" The alert had been firing since {started_at:%Y-%m-%d %H:%M} UTC."
+
+ markdown = strip_external_links_markdown(markdown)
+ # Same post-strip linkification as fired messages, so the URL isn't defanged off posthog.com hosts.
+ markdown = _linkify_header(markdown, action, _run_url(team.id, str(action.id), str(run.pk)), label="Recovered")
+ run.synthesized_markdown = markdown
+ # `recovered` rides `output` (alongside the Slack rendering, unused until recovery delivery is a
+ # thing) because the run row has no other slot that survives to both the engine and the API.
+ run.output = {"slack": _markdown_to_slack(markdown, team_id=team.id, observation_ids=[]), "recovered": True}
+ run.observation_count = matched_count
+ run.save(update_fields=["synthesized_markdown", "output", "observation_count", "updated_at"])
+
+ return EvaluateAlertResult(status=AlertStatus.RECOVERED, observation_count=matched_count, metric_value=metric_value)
+
+
def _format_number(value: float) -> str:
return str(int(value)) if float(value).is_integer() else f"{value:.2f}"
@@ -243,7 +310,7 @@ def _scanner_display_name(action: Any) -> str:
return re.sub(r"\s+", " ", re.sub(r"[*_`#\[\]()]", "", raw_name)).strip() or "your scanner"
-def _linkify_header(markdown: str, action: Any, run_url: str) -> str:
+def _linkify_header(markdown: str, action: Any, run_url: str, label: str = "Alert") -> str:
"""Wrap the header's scanner name in a link to this alert's run page — the alert's own message
plus every matching observation (and breadcrumbs back to the scanner). A name the strip pass
rewrote (e.g. it contained a bare URL, now a code span) won't match the expected header — leave
@@ -251,10 +318,10 @@ def _linkify_header(markdown: str, action: Any, run_url: str) -> str:
if not action.scanner_id:
return markdown
name = _scanner_display_name(action)
- prefix = f"**Alert: {name}**"
+ prefix = f"**{label}: {name}**"
if not markdown.startswith(prefix):
return markdown
- return f"**Alert: [{name}]({run_url})**" + markdown[len(prefix) :]
+ return f"**{label}: [{name}]({run_url})**" + markdown[len(prefix) :]
def _alert_markdown(
diff --git a/products/replay_vision/backend/temporal/vision_actions/types.py b/products/replay_vision/backend/temporal/vision_actions/types.py
index d27e0a155fad..34755ae867af 100644
--- a/products/replay_vision/backend/temporal/vision_actions/types.py
+++ b/products/replay_vision/backend/temporal/vision_actions/types.py
@@ -54,6 +54,7 @@ class AlertStatus(str, Enum):
FIRED = "fired" # condition held; message persisted on the run — deliver it
NOT_BREACHED = "not_breached" # condition did not hold; nothing to deliver
STILL_BREACHED = "still_breached" # condition holds but the previous check already notified
+ RECOVERED = "recovered" # condition cleared after a breach; message persisted — visible in history, not delivered
class EvaluateAlertInputs(BaseModel, frozen=True):
diff --git a/products/replay_vision/backend/temporal/vision_actions/workflows.py b/products/replay_vision/backend/temporal/vision_actions/workflows.py
index a18827cf2531..027f6619a590 100644
--- a/products/replay_vision/backend/temporal/vision_actions/workflows.py
+++ b/products/replay_vision/backend/temporal/vision_actions/workflows.py
@@ -96,6 +96,12 @@ class ProcessVisionActionWorkflow(PostHogWorkflow):
# final_status stays SKIPPED; record why so the run isn't an unexplained skip.
error_info = {"skip_reason": alert.status.value}
return
+ if alert.status == AlertStatus.RECOVERED:
+ # The recovery bookend is visible run history but not a notification: complete the
+ # run without delivering. Replay-safe unguarded: the branch is decided by recorded
+ # activity output, and no pre-RECOVERED history contains this status.
+ final_status = VisionActionRunStatus.COMPLETED.value
+ return
else:
synth = await wf.execute_activity(
synthesize_group_summary_activity,
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 4b77b1e9f0fa..f52be39b6e95 100644
--- a/products/replay_vision/backend/tests/test_vision_action_alerts.py
+++ b/products/replay_vision/backend/tests/test_vision_action_alerts.py
@@ -143,6 +143,55 @@ class TestVisionActionAlerts(BaseTest):
run.refresh_from_db()
self.assertEqual(run.synthesized_markdown, "")
+ def test_recovery_bookends_the_breach_and_rearms_the_alert(self) -> None:
+ # fire → recover → fire again. The recovery run must be persisted as a visible message AND
+ # must read as "cleared" in state resolution — misread as a breach, it would suppress the
+ # next firing forever (a fired run also has a persisted message).
+ scanner = self._scanner()
+ obs = self._observation(scanner, {"verdict": "yes"})
+ action = self._alert(scanner, {"metric": "count", "threshold": 1})
+
+ fired, fired_run = self._evaluate(action)
+ self.assertEqual(fired.status, AlertStatus.FIRED)
+ self._record(fired_run, VisionActionRunStatus.COMPLETED)
+
+ # The observation ages out of the rolling window: count drops to a measurable 0.
+ aged = timezone.now() - timedelta(days=2)
+ ReplayObservation.objects.filter(pk=obs.pk).update(completed_at=aged, created_at=aged)
+ recovered, recovery_run = self._evaluate(action, key="k2")
+
+ self.assertEqual(recovered.status, AlertStatus.RECOVERED)
+ recovery_run.refresh_from_db()
+ self.assertIn("Recovered:", recovery_run.synthesized_markdown)
+ self.assertIn("below the threshold of 1", recovery_run.synthesized_markdown)
+ self.assertIn("had been firing since", recovery_run.synthesized_markdown)
+ self.assertTrue(recovery_run.output["recovered"])
+ self._record(recovery_run, VisionActionRunStatus.COMPLETED)
+
+ # A fresh match after recovery is a new incident — it must fire, not report still_breached.
+ self._observation(scanner, {"verdict": "yes"}, session_id="s-new")
+ refired, _ = self._evaluate(action, key="k3")
+ self.assertEqual(refired.status, AlertStatus.FIRED)
+
+ def test_unmeasurable_window_after_breach_rearms_without_recovery_row(self) -> None:
+ # An avg over an empty window has no measurement, so it can't claim "back at X" — the alert
+ # re-arms via a quiet not_breached skip instead of a recovery bookend.
+ scanner = self._scanner(scanner_type=ScannerType.SCORER, name="fading-scorer")
+ obs = self._observation(scanner, {"score": 5})
+ action = self._alert(scanner, {"metric": "avg_score", "threshold": 4})
+
+ fired, fired_run = self._evaluate(action)
+ self.assertEqual(fired.status, AlertStatus.FIRED)
+ self._record(fired_run, VisionActionRunStatus.COMPLETED)
+
+ aged = timezone.now() - timedelta(days=2)
+ ReplayObservation.objects.filter(pk=obs.pk).update(completed_at=aged, created_at=aged)
+ result, run = self._evaluate(action, key="k2")
+
+ self.assertEqual(result.status, AlertStatus.NOT_BREACHED)
+ 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})
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 93829258b32e..e38bfcaaa022 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -402,6 +402,8 @@ export interface VisionActionRunListApi {
* @nullable
*/
readonly error_reason: string | null
+ /** True for the run recording an alert's condition clearing after a breach (the recovery bookend in run history). False for alert firings and summaries. */
+ readonly is_recovery: boolean
readonly created_at: string
readonly updated_at: string
}
@@ -463,6 +465,8 @@ export interface VisionActionRunApi {
* @nullable
*/
readonly error_reason: string | null
+ /** True for the run recording an alert's condition clearing after a breach (the recovery bookend in run history). False for alert firings and summaries. */
+ readonly is_recovery: boolean
readonly created_at: string
readonly updated_at: string
/** The synthesized group-summary report in Markdown. Empty until a run completes successfully. */
diff --git a/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.test.ts b/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.test.ts
index 14eec9e75b37..076f3e798e7a 100644
--- a/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.test.ts
@@ -12,6 +12,7 @@ const run = (id: string, overrides: Partial<VisionActionRunListApi> = {}): Visio
scheduled_at: '2026-01-01T09:00:00Z',
observation_count: 3,
error_reason: '',
+ is_recovery: false,
created_at: '2026-01-01T09:01:00Z',
updated_at: '2026-01-01T09:01:00Z',
...overrides,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3d50171593f2..62e068e1cec4 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -41717,6 +41717,8 @@ export namespace Schemas {
* @nullable
*/
readonly error_reason: string | null;
+ /** True for the run recording an alert's condition clearing after a breach (the recovery bookend in run history). False for alert firings and summaries. */
+ readonly is_recovery: boolean;
readonly created_at: string;
readonly updated_at: string;
}
@@ -62484,6 +62486,8 @@ export namespace Schemas {
* @nullable
*/
readonly error_reason: string | null;
+ /** True for the run recording an alert's condition clearing after a breach (the recovery bookend in run history). False for alert firings and summaries. */
+ readonly is_recovery: boolean;
readonly created_at: string;
readonly updated_at: string;
/** The synthesized group-summary report in Markdown. Empty until a run completes successfully. */