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(alerts): show investigation results in a moved alert's history (#127913)

Jimmy Zhu776a63b9ca04
diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.py
index b8667bf27f77..c5339654dbf8 100644
--- a/posthog/temporal/alerts/activities.py
+++ b/posthog/temporal/alerts/activities.py
@@ -103,6 +103,7 @@ from products.alerts.backend.facade.destinations import count_active_alert_desti
from products.alerts.backend.facade.email import alert_email_recipients
from products.alerts.backend.insight_alert_state_machine import apply_unsnooze
from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration, Threshold
+from products.alerts.backend.models.investigation import InsightAlertInvestigation
from products.notifications.backend.facade.api import (
NotificationData,
NotificationType,
@@ -1170,7 +1171,7 @@ async def run_investigation_safety_net() -> int:
async def cleanup_alert_checks() -> int:
@database_sync_to_async(thread_sensitive=False)
def _cleanup() -> int:
- return AlertCheck.clean_up_old_checks()
+ return AlertCheck.clean_up_old_checks() + InsightAlertInvestigation.clean_up_old_investigations()
async with Heartbeater():
return await _cleanup()
diff --git a/posthog/temporal/alerts/workflows.py b/posthog/temporal/alerts/workflows.py
index 012e7e602f36..0d68c43856e0 100644
--- a/posthog/temporal/alerts/workflows.py
+++ b/posthog/temporal/alerts/workflows.py
@@ -402,7 +402,7 @@ class RunInvestigationSafetyNetWorkflow(PostHogWorkflow):
@temporalio.workflow.defn(name="cleanup-alert-checks")
class CleanupAlertChecksWorkflow(PostHogWorkflow):
- """Purge old AlertCheck rows on a daily schedule."""
+ """Purge old AlertCheck and InsightAlertInvestigation rows on a daily schedule."""
@staticmethod
def parse_inputs(inputs: list[str]) -> None:
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index e74abd41cf03..2da5dbeeb686 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -202,6 +202,11 @@ class MovedAlertCheck:
triggered_dates: tuple[str, ...] = ()
interval: str | None = None
triggered_metadata: dict[str, Any] | None = None
+ investigation_status: str | None = None
+ investigation_verdict: str | None = None
+ investigation_summary: str | None = None
+ investigation_notebook_short_id: str | None = None
+ notification_suppressed_by_agent: bool = False
@frozen
diff --git a/products/alerts/backend/investigation_release.py b/products/alerts/backend/investigation_release.py
index 22d29b596a50..bc71b42acf02 100644
--- a/products/alerts/backend/investigation_release.py
+++ b/products/alerts/backend/investigation_release.py
@@ -129,6 +129,7 @@ def finish_investigation(
investigation.episode_started_at,
investigation.evaluation_key,
)
+ verdict_suppresses = _should_suppress_notification(verdict, alert.investigation_inconclusive_action)
with transaction.atomic():
InsightAlertInvestigation.objects.for_team(investigation.team_id).filter(id=investigation.id).update(
status=InvestigationStatus.DONE, verdict=verdict, summary=summary, notebook_id=notebook_id, error=None
@@ -136,9 +137,10 @@ def finish_investigation(
delivery = release_held(
_hold_of(investigation),
# As the safety net does, so turning the alert back on never sends a firing that old.
- suppress=not alert.enabled
- or _should_suppress_notification(verdict, alert.investigation_inconclusive_action),
- released_by=HoldReleasedBy.VERDICT,
+ suppress=not alert.enabled or verdict_suppresses,
+ # A firing only the disabled alert holds back is the safety net's suppress, so history does
+ # not show it as the agent's.
+ released_by=HoldReleasedBy.VERDICT if verdict_suppresses or alert.enabled else HoldReleasedBy.SAFETY_NET,
)
if delivery is None:
delivery = _announce_verdict_change(alert, investigation, verdict=verdict, previous_verdict=previous_verdict)
diff --git a/products/alerts/backend/migrations/0016_insight_alert_investigation_age_index.py b/products/alerts/backend/migrations/0016_insight_alert_investigation_age_index.py
new file mode 100644
index 000000000000..b79b169eb449
--- /dev/null
+++ b/products/alerts/backend/migrations/0016_insight_alert_investigation_age_index.py
@@ -0,0 +1,20 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ """The index behind the daily retention prune, built without locking writes out of the table."""
+
+ atomic = False
+
+ dependencies = [
+ ("alerts", "0015_insight_alert_investigation"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="insightalertinvestigation",
+ index=models.Index(fields=["created_at"], name="insight_alert_inv_age_idx"),
+ ),
+ ]
diff --git a/products/alerts/backend/migrations/max_migration.txt b/products/alerts/backend/migrations/max_migration.txt
index 4b481002c897..1b4010c0197b 100644
--- a/products/alerts/backend/migrations/max_migration.txt
+++ b/products/alerts/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0015_insight_alert_investigation
+0016_insight_alert_investigation_age_index
diff --git a/products/alerts/backend/models/investigation.py b/products/alerts/backend/models/investigation.py
index 52b8692bdb70..61f7f501ea97 100644
--- a/products/alerts/backend/models/investigation.py
+++ b/products/alerts/backend/models/investigation.py
@@ -1,3 +1,6 @@
+from datetime import UTC, datetime, timedelta
+from typing import ClassVar
+
from django.db import models
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
@@ -14,6 +17,9 @@ class InsightAlertInvestigation(TeamScopedRootMixin, UUIDModel):
claim refused, which is recorded as SKIPPED and spends no budget.
"""
+ # As long as the platform's check history the rows annotate (`PLATFORM_ALERT_EVENTS_TTL_DAYS`).
+ RETENTION: ClassVar[timedelta] = timedelta(days=90)
+
class Kind(models.TextChoices):
AGENT = "agent", "Agent"
METRICS = "metrics", "Metrics"
@@ -66,4 +72,13 @@ class InsightAlertInvestigation(TeamScopedRootMixin, UUIDModel):
),
# The claim's in-flight and cooldown checks.
models.Index(fields=["configuration_id", "created_at"], name="insight_alert_inv_recent_idx"),
+ # The daily retention prune, which reads every team's rows by age.
+ models.Index(fields=["created_at"], name="insight_alert_inv_age_idx"),
]
+
+ @classmethod
+ def clean_up_old_investigations(cls) -> int:
+ oldest_allowed_date = datetime.now(UTC) - cls.RETENTION
+ # nosemgrep: idor-lookup-without-team — fleet-wide retention prune by age; no request or team input reaches it
+ rows_count, _ = cls.objects.unscoped().filter(created_at__lt=oldest_allowed_date).delete()
+ return rows_count
diff --git a/products/alerts/backend/platform_alert_reads.py b/products/alerts/backend/platform_alert_reads.py
index 610cc3e5ebde..dd7ae0967216 100644
--- a/products/alerts/backend/platform_alert_reads.py
+++ b/products/alerts/backend/platform_alert_reads.py
@@ -23,13 +23,16 @@ from products.alerts.backend.facade.contracts import (
MovedAlertStatus,
)
from products.alerts.backend.models.alert import AlertConfiguration
+from products.alerts.backend.models.investigation import InsightAlertInvestigation
from products.alerts.backend.platform_cutover import insight_state_of_platform
+from products.alerts.backend.platform_investigation_detail import SUPPRESSED_BY_AGENT_KEY
from products.alerts.backend.platform_source_cycle import ERROR_CODE_KEY
from products.alerts_platform.backend.facade.api import (
check_page_by_legacy_id,
checks_with_detail_by_legacy_id,
last_check_by_legacy_id,
runtime_by_legacy_id,
+ source_suppressed_holds_by_legacy_id,
)
from products.alerts_platform.backend.facade.contracts import PlatformCheckEntry
from products.alerts_platform.backend.facade.enums import PlatformAlertOwner, PlatformAlertState
@@ -94,8 +97,9 @@ def moved_alert_check_page(
) -> MovedAlertCheckPage | None:
"""A page of a moved alert's checks in `[since, until]`, newest first, with how many the window holds.
- None when the alert's own checks are the ones to show: the platform does not own it, or its
- history could not be read.
+ Each check carries its investigation and whether the agent suppressed its notification. None
+ when the alert's own checks are the ones to show: the platform does not own it, or its history
+ could not be read.
"""
if not AlertConfiguration.objects.filter(team_id=team_id, id=alert_id, owner=PlatformAlertOwner.PLATFORM).exists():
return None
@@ -114,7 +118,29 @@ def moved_alert_check_page(
return None
if page is None:
return None
- return MovedAlertCheckPage(total=page.total, checks=tuple(_as_check(alert_id, check) for check in page.checks))
+ keys = [check.evaluation_key for check in page.checks]
+ investigations = {
+ investigation.evaluation_key: investigation
+ for investigation in InsightAlertInvestigation.objects.for_team(team_id)
+ .filter(configuration_id=page.configuration_id, evaluation_key__in=keys)
+ .select_related("notebook")
+ .only("evaluation_key", "status", "verdict", "summary", "notebook__short_id")
+ }
+ suppressed_holds = source_suppressed_holds_by_legacy_id(
+ team_id=team_id, legacy_configuration_id=alert_id, evaluation_keys=keys
+ )
+ return MovedAlertCheckPage(
+ total=page.total,
+ checks=tuple(
+ _as_check(
+ alert_id,
+ check,
+ investigation=investigations.get(check.evaluation_key),
+ suppressed_by_hold=check.evaluation_key in suppressed_holds,
+ )
+ for check in page.checks
+ ),
+ )
def moved_alert_fired_checks(
@@ -155,7 +181,13 @@ def moved_alert_fired_checks(
}
-def _as_check(alert_id: UUID, check: PlatformCheckEntry) -> MovedAlertCheck:
+def _as_check(
+ alert_id: UUID,
+ check: PlatformCheckEntry,
+ *,
+ investigation: InsightAlertInvestigation | None = None,
+ suppressed_by_hold: bool = False,
+) -> MovedAlertCheck:
detail = check.source_detail
metadata = detail.get("triggered_metadata")
interval = detail.get("interval")
@@ -175,6 +207,13 @@ def _as_check(alert_id: UUID, check: PlatformCheckEntry) -> MovedAlertCheck:
triggered_dates=tuple(_listed(detail, FIRED_DATES_KEY, (str,))),
interval=interval if isinstance(interval, str) else None,
triggered_metadata=metadata if isinstance(metadata, dict) else None,
+ investigation_status=investigation.status if investigation else None,
+ investigation_verdict=investigation.verdict if investigation else None,
+ investigation_summary=investigation.summary if investigation else None,
+ investigation_notebook_short_id=investigation.notebook.short_id
+ if investigation and investigation.notebook
+ else None,
+ notification_suppressed_by_agent=suppressed_by_hold or detail.get(SUPPRESSED_BY_AGENT_KEY) is True,
)
diff --git a/products/alerts/backend/platform_investigation.py b/products/alerts/backend/platform_investigation.py
index d4ed1808e20e..2feb72c98be6 100644
--- a/products/alerts/backend/platform_investigation.py
+++ b/products/alerts/backend/platform_investigation.py
@@ -44,6 +44,7 @@ from products.alerts.backend.models.investigation import InsightAlertInvestigati
from products.alerts.backend.platform_investigation_detail import (
INVESTIGATION_REQUESTED_KEY,
METRICS_INVESTIGATION_REQUESTED_KEY,
+ SUPPRESSED_BY_AGENT_KEY,
InvestigationClaims,
InvestigationStart,
MetricsInvestigationRun,
@@ -220,7 +221,12 @@ def with_investigation(check: PlatformAlertCheckInput, evaluation: SourceBatchEv
)
if group.kind == AlertEventKind.FIRING and carried_verdict_suppresses(alert, decision):
# As the insight stack: the firing still moves the alert's state and `last_notified_at`.
- group = replace(group, kind=AlertEventKind.CHECK, muted_notification=NotificationAction.FIRE.value)
+ group = replace(
+ group,
+ kind=AlertEventKind.CHECK,
+ muted_notification=NotificationAction.FIRE.value,
+ source_detail={**group.source_detail, SUPPRESSED_BY_AGENT_KEY: True},
+ )
return replace(evaluation, outcomes=(replace(outcome, groups=(group,)),), deliveries=())
return evaluation
diff --git a/products/alerts/backend/platform_investigation_detail.py b/products/alerts/backend/platform_investigation_detail.py
index 5020343ebcb8..be8e8b224e84 100644
--- a/products/alerts/backend/platform_investigation_detail.py
+++ b/products/alerts/backend/platform_investigation_detail.py
@@ -16,6 +16,8 @@ from products.alerts_platform.backend.facade.contracts import AlertDeliveryReque
INVESTIGATION_REQUESTED_KEY = "investigation_alert_id"
# The same, for a metrics alert, whose investigation is a few metric queries rather than an agent run.
METRICS_INVESTIGATION_REQUESTED_KEY = "metrics_investigation_alert_id"
+# Marks a firing the episode's last verdict muted, so the history tells it from a snooze.
+SUPPRESSED_BY_AGENT_KEY = "notification_suppressed_by_agent"
@frozen
diff --git a/products/alerts/backend/presentation/views/alert.py b/products/alerts/backend/presentation/views/alert.py
index f76e7ebd1d64..ec9f941832dc 100644
--- a/products/alerts/backend/presentation/views/alert.py
+++ b/products/alerts/backend/presentation/views/alert.py
@@ -1530,6 +1530,10 @@ def _show_platform_status(alerts: list[AlertConfiguration], *, now: datetime) ->
MOVED_ALERT_FIRED_CHECKS_LIMIT: Final = 500
+# The notebook model, reached through the check's link so this product does not import another's models.
+_NOTEBOOK: Final = cast(type[Any], AlertCheck._meta.get_field("investigation_notebook").related_model)
+
+
def _as_alert_check(alert: AlertConfiguration, check: MovedAlertCheck) -> AlertCheck:
# Never saved. It carries what the check serializer shows.
return AlertCheck(
@@ -1548,6 +1552,13 @@ def _as_alert_check(alert: AlertConfiguration, check: MovedAlertCheck) -> AlertC
triggered_dates=list(check.triggered_dates) or None,
interval=check.interval,
triggered_metadata=check.triggered_metadata,
+ investigation_status=check.investigation_status,
+ investigation_verdict=check.investigation_verdict,
+ investigation_summary=check.investigation_summary,
+ investigation_notebook=_NOTEBOOK(short_id=check.investigation_notebook_short_id)
+ if check.investigation_notebook_short_id
+ else None,
+ notification_suppressed_by_agent=check.notification_suppressed_by_agent,
)
diff --git a/products/alerts/backend/test/test_platform_source_cycle.py b/products/alerts/backend/test/test_platform_source_cycle.py
index 10f9488ecf50..201ff6a75b0a 100644
--- a/products/alerts/backend/test/test_platform_source_cycle.py
+++ b/products/alerts/backend/test/test_platform_source_cycle.py
@@ -49,7 +49,7 @@ from products.alerts.backend.models.investigation import InsightAlertInvestigati
from products.alerts.backend.platform_alert_wording import insight_alert_url
from products.alerts.backend.platform_chart_detail import CHART_PENDING_KEY, RenderedChart
from products.alerts.backend.platform_investigation import claim_requested_investigations
-from products.alerts.backend.platform_investigation_detail import requested_investigation
+from products.alerts.backend.platform_investigation_detail import SUPPRESSED_BY_AGENT_KEY, requested_investigation
from products.alerts.backend.platform_source_cycle import (
CAPACITY_REJECTED,
CHART_RENDER_INFLIGHT_KEY,
@@ -975,6 +975,7 @@ class TestPlatformInsightEvaluation(APIBaseTest):
assert requested_investigation(outcome) is None
assert (outcome.groups[0].kind, outcome.groups[0].muted_notification) == (AlertEventKind.CHECK, "fire")
+ assert outcome.groups[0].source_detail.get(SUPPRESSED_BY_AGENT_KEY) is True
assert self.deliveries == ()
@parameterized.expand(
diff --git a/products/alerts/backend/tests/api/test_alert_platform_owned.py b/products/alerts/backend/tests/api/test_alert_platform_owned.py
index 36c5fa30a183..4c9481bfaa6b 100644
--- a/products/alerts/backend/tests/api/test_alert_platform_owned.py
+++ b/products/alerts/backend/tests/api/test_alert_platform_owned.py
@@ -22,8 +22,15 @@ from products.alerts.backend.judge import (
LLM_DETECTOR_UNAVAILABLE_MESSAGE,
EarlierFlag,
)
-from products.alerts.backend.models.alert import AlertCheck, AlertConfiguration
+from products.alerts.backend.models.alert import (
+ AlertCheck,
+ AlertConfiguration,
+ InvestigationStatus,
+ InvestigationVerdict,
+)
+from products.alerts.backend.models.investigation import InsightAlertInvestigation
from products.alerts.backend.platform_cutover import cut_over_team
+from products.alerts.backend.platform_investigation_detail import SUPPRESSED_BY_AGENT_KEY
from products.alerts.backend.test.insight_alerts import create_insight_alert
from products.alerts_platform.backend.facade import testing as platform_testing
from products.alerts_platform.backend.facade.api import get_configuration, record_verdict_change, update_configuration
@@ -33,6 +40,8 @@ from products.alerts_platform.backend.facade.contracts import (
SourceKind,
VerdictChange,
)
+from products.alerts_platform.backend.facade.enums import HoldRelease, HoldReleasedBy
+from products.notebooks.backend.facade.api import create_notebook
def _iso(moment: datetime) -> str:
@@ -179,6 +188,56 @@ class TestPlatformOwnedInsightAlert(ClickhouseTestMixin, APIBaseTest):
"message": LLM_DETECTOR_UNAVAILABLE_MESSAGE,
}
+ def test_a_moved_alert_shows_each_checks_investigation_and_what_the_agent_suppressed(self) -> None:
+ notebook = create_notebook(self.team.id, title="Signups investigation", content=None)
+ for minutes_ago in (40, 30, 20, 10):
+ self._record(
+ minutes_ago,
+ "firing",
+ value=150.0,
+ detail={SUPPRESSED_BY_AGENT_KEY: True} if minutes_ago == 10 else None,
+ )
+ InsightAlertInvestigation.objects.for_team(self.team.id).create(
+ team=self.team,
+ alert_configuration=self.alert,
+ configuration_id=self.copy_id,
+ evaluation_key=f"slot:{self._at(40).isoformat()}",
+ kind=InsightAlertInvestigation.Kind.AGENT,
+ status=InvestigationStatus.DONE,
+ verdict=InvestigationVerdict.FALSE_POSITIVE,
+ summary="A release changed the event name.",
+ notebook_id=notebook.id,
+ )
+ released = [
+ (40, HoldReleasedBy.VERDICT),
+ (30, HoldReleasedBy.SAFETY_NET),
+ (20, HoldReleasedBy.CLAIM_REFUSED),
+ ]
+ for minutes_ago, released_by in released:
+ platform_testing.released_hold(
+ self.copy_id,
+ team_id=self.team.id,
+ at=self._at(minutes_ago),
+ action=HoldRelease.SUPPRESS,
+ released_by=released_by,
+ )
+
+ checks = self._row("retrieve")["checks"]
+
+ fields = (
+ "investigation_status",
+ "investigation_verdict",
+ "investigation_summary",
+ "investigation_notebook_short_id",
+ "notification_suppressed_by_agent",
+ )
+ assert [tuple(check[field] for field in fields) for check in checks] == [
+ (None, None, None, None, True),
+ (None, None, None, None, True),
+ (None, None, None, None, False),
+ ("done", "false_positive", "A release changed the event name.", notebook.short_id, True),
+ ]
+
def test_a_moved_detector_alert_marks_the_points_both_stacks_fired_on(self) -> None:
self._own_check(60 * 24, "2026-10-18", "Before the move.")
# The shadow's check after the move sent nothing, so the platform's verdict replaces it.
diff --git a/products/alerts/backend/tests/test_migration_0014_strip_llm_detector_threshold_and_window.py b/products/alerts/backend/tests/test_migration_0014_strip_llm_detector_threshold_and_window.py
index 236977f567fe..168aa75a75d1 100644
--- a/products/alerts/backend/tests/test_migration_0014_strip_llm_detector_threshold_and_window.py
+++ b/products/alerts/backend/tests/test_migration_0014_strip_llm_detector_threshold_and_window.py
@@ -1,11 +1,11 @@
from typing import Any
-from posthog.test.base import TestMigrations
+from posthog.test.base import NonAtomicTestMigrations
ZSCORE = {"type": "zscore", "threshold": 0.95, "window": 30}
-class TestStripLLMDetectorThresholdAndWindow(TestMigrations):
+class TestStripLLMDetectorThresholdAndWindow(NonAtomicTestMigrations):
app = "alerts"
migrate_from = "0013_alertconfiguration_owner"
migrate_to = "0014_strip_llm_detector_threshold_and_window"
diff --git a/products/alerts/backend/tests/test_platform_investigation.py b/products/alerts/backend/tests/test_platform_investigation.py
index 38cbe1189a4b..fef0a5ba0d45 100644
--- a/products/alerts/backend/tests/test_platform_investigation.py
+++ b/products/alerts/backend/tests/test_platform_investigation.py
@@ -161,6 +161,18 @@ class TestPlatformInvestigation(BaseTest):
assert self._claim() == first
assert first.claimed is claimed
+ def test_the_daily_prune_drops_only_investigations_past_retention(self) -> None:
+ self._investigation(at=NOW - InsightAlertInvestigation.RETENTION - timedelta(hours=1), key="slot:old")
+ self._investigation(at=NOW - InsightAlertInvestigation.RETENTION + timedelta(hours=1), key="slot:recent")
+
+ with time_machine.travel(NOW, tick=False):
+ deleted = InsightAlertInvestigation.clean_up_old_investigations()
+
+ assert deleted == 1
+ assert list(
+ InsightAlertInvestigation.objects.for_team(self.team.id).values_list("evaluation_key", flat=True)
+ ) == ["slot:recent"]
+
class TestFinishInvestigation(BaseTest):
def setUp(self) -> None:
@@ -219,13 +231,20 @@ class TestFinishInvestigation(BaseTest):
@parameterized.expand(
[
- ("a true positive sends", "true_positive", True, HoldRelease.SEND),
- ("a false positive suppresses", "false_positive", True, HoldRelease.SUPPRESS),
- ("a disabled alert suppresses", "true_positive", False, HoldRelease.SUPPRESS),
+ ("a true positive sends", "true_positive", True, HoldRelease.SEND, HoldReleasedBy.VERDICT),
+ ("a false positive suppresses", "false_positive", True, HoldRelease.SUPPRESS, HoldReleasedBy.VERDICT),
+ ("a disabled alert suppresses", "true_positive", False, HoldRelease.SUPPRESS, HoldReleasedBy.SAFETY_NET),
+ (
+ "a disabled alert's false positive is the agent's",
+ "false_positive",
+ False,
+ HoldRelease.SUPPRESS,
+ HoldReleasedBy.VERDICT,
+ ),
]
)
def test_a_verdict_releases_the_held_firing(
- self, _name: str, verdict: str, enabled: bool, action: HoldRelease
+ self, _name: str, verdict: str, enabled: bool, action: HoldRelease, released_by: HoldReleasedBy
) -> None:
self.alert.enabled = enabled
self.alert.save()
@@ -238,7 +257,7 @@ class TestFinishInvestigation(BaseTest):
expected = (self.request,) if action == HoldRelease.SEND else ()
assert release.deliveries == repeated.deliveries == expected
hold = platform_testing.hold_release(self.address)
- assert (hold.release_action, hold.released_by) == (action, HoldReleasedBy.VERDICT)
+ assert (hold.release_action, hold.released_by) == (action, released_by)
investigation.refresh_from_db()
assert (investigation.status, investigation.verdict) == (InvestigationStatus.DONE, verdict)
diff --git a/products/alerts_platform/backend/facade/api.py b/products/alerts_platform/backend/facade/api.py
index ca947300a00c..8748245245cc 100644
--- a/products/alerts_platform/backend/facade/api.py
+++ b/products/alerts_platform/backend/facade/api.py
@@ -86,6 +86,14 @@ def reschedule_hold(address: HeldDeliveryAddress, *, release_after: datetime) ->
return delivery_holds.reschedule_hold(address, release_after=release_after)
+def source_suppressed_holds_by_legacy_id(
+ *, team_id: int, legacy_configuration_id: UUID, evaluation_keys: Collection[str]
+) -> frozenset[str]:
+ """The named evaluations of an alert the platform owns whose held delivery its source released
+ with a suppress. A suppress by the safety net, for a configuration turned off, is left out."""
+ return delivery_holds.source_suppressed_holds_by_legacy_id(team_id, legacy_configuration_id, evaluation_keys)
+
+
def record_verdict_change(change: VerdictChange, *, now: datetime) -> AlertDeliveryRequest | None:
"""Records one follow-up about a firing that already went out, and returns the delivery to start
with `start_deliveries`, or None when there is nothing to send.
diff --git a/products/alerts_platform/backend/facade/contracts.py b/products/alerts_platform/backend/facade/contracts.py
index b343e7259137..44d4288f06b3 100644
--- a/products/alerts_platform/backend/facade/contracts.py
+++ b/products/alerts_platform/backend/facade/contracts.py
@@ -478,6 +478,8 @@ class PlatformCheckPage:
total: int
checks: tuple[PlatformCheckEntry, ...]
+ # The platform configuration the checks belong to, so a source can join its own rows on it.
+ configuration_id: UUID
@frozen
diff --git a/products/alerts_platform/backend/facade/testing.py b/products/alerts_platform/backend/facade/testing.py
index 62d0e5d4d235..04feda2f6cf7 100644
--- a/products/alerts_platform/backend/facade/testing.py
+++ b/products/alerts_platform/backend/facade/testing.py
@@ -246,6 +246,29 @@ def record_check(
)
+def released_hold(
+ configuration_id: UUID,
+ *,
+ team_id: int,
+ at: datetime,
+ action: HoldRelease,
+ released_by: HoldReleasedBy,
+) -> None:
+ """Write a hold on the check `record_check` wrote at `at`, already released."""
+ PlatformAlertDeliveryHold.objects.for_team(team_id).create(
+ team_id=team_id,
+ configuration_id=configuration_id,
+ evaluation_key=f"slot:{at.isoformat()}",
+ reason="test",
+ request={},
+ held_at=at,
+ release_after=at,
+ released_at=at,
+ release_action=action,
+ released_by=released_by,
+ )
+
+
def alert_for(configuration_id: UUID, *, grouping_key: str = "") -> PlatformAlertSnapshot | None:
"""The instance row a check wrote, or None when no check has written one."""
row = (
diff --git a/products/alerts_platform/backend/logic/delivery_holds.py b/products/alerts_platform/backend/logic/delivery_holds.py
index 4923283d5e71..8dfcad9efce4 100644
--- a/products/alerts_platform/backend/logic/delivery_holds.py
+++ b/products/alerts_platform/backend/logic/delivery_holds.py
@@ -6,9 +6,10 @@ request, hands it back to whoever releases it with a send, and sends it itself o
deadline passes, so a source that never answers still delivers.
"""
-from collections.abc import Sequence
+from collections.abc import Collection, Sequence
from datetime import UTC, datetime, timedelta
from typing import Final
+from uuid import UUID
from django.db import transaction
@@ -21,7 +22,12 @@ from products.alerts_platform.backend.facade.contracts import (
IncidentAction,
PlatformAlertOutcome,
)
-from products.alerts_platform.backend.facade.enums import HoldRelease, HoldReleasedBy, PlatformAlertState
+from products.alerts_platform.backend.facade.enums import (
+ HoldRelease,
+ HoldReleasedBy,
+ PlatformAlertOwner,
+ PlatformAlertState,
+)
from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration, PlatformAlertDeliveryHold
from products.alerts_platform.backend.models.platform_alert_events_sql import PLATFORM_ALERT_EVENTS_TTL_DAYS
@@ -180,6 +186,28 @@ def blocks_delivery(team_id: int, configuration_id: str, evaluation_key: str) ->
)
+def source_suppressed_holds_by_legacy_id(
+ team_id: int, legacy_configuration_id: UUID, evaluation_keys: Collection[str]
+) -> frozenset[str]:
+ """The named evaluations of an alert the platform owns whose hold its source released with a suppress.
+
+ A suppress by the safety net is left out: it is the platform's, for a configuration turned off.
+ """
+ if not evaluation_keys:
+ return frozenset()
+ return frozenset(
+ PlatformAlertDeliveryHold.objects.for_team(team_id)
+ .filter(
+ configuration__legacy_configuration_id=legacy_configuration_id,
+ configuration__owner=PlatformAlertOwner.PLATFORM,
+ evaluation_key__in=evaluation_keys,
+ release_action=HoldRelease.SUPPRESS,
+ )
+ .exclude(released_by=HoldReleasedBy.SAFETY_NET)
+ .values_list("evaluation_key", flat=True)
+ )
+
+
def stale_held_triggers(request: AlertDeliveryRequest, transitions: Sequence[AnnouncedTransition]) -> frozenset[str]:
"""The groups of a held evaluation whose incident trigger must not go out.
diff --git a/products/alerts_platform/backend/logic/platform_alert_events.py b/products/alerts_platform/backend/logic/platform_alert_events.py
index 4f039596da88..3fd29c5227ea 100644
--- a/products/alerts_platform/backend/logic/platform_alert_events.py
+++ b/products/alerts_platform/backend/logic/platform_alert_events.py
@@ -508,6 +508,7 @@ def check_page(
total = 0
return PlatformCheckPage(
total=total,
+ configuration_id=configuration_id,
checks=tuple(
_check_entry(occurred_at, evaluation_key, state, value, error_message, source_detail)
for occurred_at, evaluation_key, state, value, error_message, _, source_detail in rows