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(error_tracking): evaluate alert filters before opening threads (#92052)

Cataline672a3c54ac8
diff --git a/products/error_tracking/backend/logic/alerts.py b/products/error_tracking/backend/logic/alerts.py
index cbbb9b89e2b7..53b97b3a2ea9 100644
--- a/products/error_tracking/backend/logic/alerts.py
+++ b/products/error_tracking/backend/logic/alerts.py
@@ -191,9 +191,55 @@ def delete_alert(team_id: int, alert_id: UUID | str) -> bool:
return deleted > 0
+def _validate_filter_surface(filters: dict[str, Any]) -> None:
+ # Delivery evaluates filters without person, group, or cohort context, and
+ # native alerts have no bytecode refresh when actions or test-account
+ # definitions change. Reject what cannot be honored instead of silently
+ # mis-evaluating it.
+ unsupported_keys = [key for key in ("actions", "filter_test_accounts") if filters.get(key)]
+ if unsupported_keys:
+ raise AlertValidationError(f"Alert filters do not support {', '.join(unsupported_keys)}.")
+ property_lists = [filters.get("properties") or []]
+ for entity in filters.get("events") or []:
+ if isinstance(entity, dict):
+ if entity.get("type") != "events":
+ # A typeless entity compiles without its event-name predicate (a
+ # match-all branch), and an action entity smuggled into the events
+ # list would compile too.
+ raise AlertValidationError(f"Alert event filters must have type events, got: {entity.get('type')}.")
+ # Without an event name the entity compiles to a match-all branch too.
+ if not isinstance(entity.get("id"), str) or not entity["id"]:
+ raise AlertValidationError("Alert event filters must name an event.")
+ property_lists.append(entity.get("properties") or [])
+ for property_list in property_lists:
+ # The compiler accepts an object here and iterating it would only yield keys,
+ # so the leaf checks below would never run.
+ if not isinstance(property_list, list):
+ raise AlertValidationError("Alert property filters must be a list.")
+ for property_filter in property_list:
+ # A leaf without a key makes the compiler fall back to a constant-true
+ # branch, turning a "filtered" alert into a match-all.
+ if not isinstance(property_filter, dict) or not isinstance(property_filter.get("key"), str):
+ raise AlertValidationError("Each alert property filter must be an object with a key.")
+ if property_filter.get("type") not in (None, "event"):
+ raise AlertValidationError(
+ f"Alert filters support event properties only, got: {property_filter.get('type')}."
+ )
+ # A leaf with a key but no value compiles to constant-true as well. An empty
+ # string is a real comparison value and stays allowed.
+ if property_filter.get("operator") not in ("is_set", "is_not_set") and property_filter.get("value") in (
+ None,
+ [],
+ ):
+ raise AlertValidationError(
+ f"Alert property filter on {property_filter['key']} needs a value, or an is set / is not set operator."
+ )
+
+
def _compile_filters(team_id: int, filters: dict[str, Any]) -> dict[str, Any]:
if not isinstance(filters, dict):
raise AlertValidationError("Alert filters must be an object.")
+ _validate_filter_surface(filters)
team = Team.objects.get(id=team_id)
compiled = compile_filters_bytecode(dict(filters), team)
if compiled.get("bytecode_error"):
diff --git a/products/error_tracking/backend/logic/issue_mutations.py b/products/error_tracking/backend/logic/issue_mutations.py
index 10e999de8784..4597b202bc5b 100644
--- a/products/error_tracking/backend/logic/issue_mutations.py
+++ b/products/error_tracking/backend/logic/issue_mutations.py
@@ -322,6 +322,7 @@ def bulk_update_issues(
user=user,
status=new_status,
extra_properties={"previous_status": status_label(issue.status)},
+ opener_allowed=False,
)
)
produce_issue_lifecycle_events_on_commit(transitions)
@@ -332,7 +333,9 @@ def bulk_update_issues(
elif action == "assign":
transitions = []
for issue in issues:
- transition = _assign_one(issue, assignee, issue.team.organization, user, team_id, was_impersonated)
+ transition = _assign_one(
+ issue, assignee, issue.team.organization, user, team_id, was_impersonated, opener_allowed=False
+ )
if transition is not None:
transitions.append(transition)
changed_issue_ids.append(issue.id)
@@ -358,6 +361,8 @@ def _assign_one(
user: User,
team_id: int,
was_impersonated: bool,
+ *,
+ opener_allowed: bool = True,
) -> PendingLifecycleEvent | None:
"""Apply one assignment change; returns its lifecycle transition for the caller to queue, or None if nothing changed."""
assignment_before = ErrorTrackingIssueAssignment.objects.filter(issue_id=issue.id).first()
@@ -401,6 +406,7 @@ def _assign_one(
issue=issue,
user=user,
extra_properties={"assignee": assignee_property(assignee)},
+ opener_allowed=opener_allowed,
)
else:
if assignment_before is None:
@@ -416,6 +422,7 @@ def _assign_one(
issue=issue,
user=user,
extra_properties=extra_properties,
+ opener_allowed=opener_allowed,
)
log_activity(
diff --git a/products/error_tracking/backend/logic/lifecycle_events.py b/products/error_tracking/backend/logic/lifecycle_events.py
index 017c400ff193..207f99094ab6 100644
--- a/products/error_tracking/backend/logic/lifecycle_events.py
+++ b/products/error_tracking/backend/logic/lifecycle_events.py
@@ -20,6 +20,7 @@ from posthog.models.user import User
from products.error_tracking.backend.models import (
ErrorTrackingAlert,
+ ErrorTrackingAlertThread,
ErrorTrackingIssue,
ErrorTrackingIssueAssignment,
ErrorTrackingIssueFingerprintV2,
@@ -109,6 +110,7 @@ def prepare_issue_lifecycle_event(
user: Optional[User],
status: Optional[str] = None,
extra_properties: Optional[dict[str, Any]] = None,
+ opener_allowed: bool = True,
) -> PendingLifecycleEvent:
# Snapshot everything now: the issue row may be mutated again (or deleted, for
# merge sources) before the surrounding transaction commits.
@@ -173,7 +175,11 @@ def prepare_issue_lifecycle_event(
status=status_property if isinstance(status_property, str) else None,
assignee=assignee_property_value if isinstance(assignee_property_value, str) else None,
actor_email=actor_email,
+ severity=properties.get("severity"),
+ fingerprint=fingerprint,
+ first_seen=properties.get("first_seen"),
extra=delivery_extra or None,
+ opener_allowed=opener_allowed,
)
return PendingLifecycleEvent(
team_id=team_id, internal_event=internal_event, person=person, alert_inputs=alert_inputs
@@ -206,14 +212,17 @@ def produce_issue_lifecycle_events_on_commit(events: list[PendingLifecycleEvent]
# queue nothing; the flag is evaluated once, inside the task.
if not ErrorTrackingAlert.objects.for_team(team_id).filter(enabled=True).exists():
return
+ to_dispatch = _with_reply_targets(team_id, events)
+ if not to_dispatch:
+ return
# The task module imports the Temporal package aggregator, which loads every
# worker-only workflow module; keep it off the web import path.
from products.error_tracking.backend.tasks.tasks import ( # noqa: PLC0415
dispatch_error_tracking_alert_deliveries,
)
- for start in range(0, len(events), ALERT_DISPATCH_BATCH_SIZE):
- chunk = events[start : start + ALERT_DISPATCH_BATCH_SIZE]
+ for start in range(0, len(to_dispatch), ALERT_DISPATCH_BATCH_SIZE):
+ chunk = to_dispatch[start : start + ALERT_DISPATCH_BATCH_SIZE]
try:
dispatch_error_tracking_alert_deliveries.delay(
team_id=team_id,
@@ -231,6 +240,31 @@ def produce_issue_lifecycle_events_on_commit(events: list[PendingLifecycleEvent]
transaction.on_commit(_produce, robust=True)
+def _with_reply_targets(team_id: int, events: list[PendingLifecycleEvent]) -> list[PendingLifecycleEvent]:
+ """Drop reply-only transitions for issues no thread has been opened on.
+
+ Bulk actions cannot open threads, so their transitions only matter where a
+ thread already exists; one lookup here keeps a bulk action over hundreds of
+ issues from starting hundreds of workflows that would plan nothing.
+ """
+ reply_only_issue_ids = {
+ pending.alert_inputs.issue_id for pending in events if not pending.alert_inputs.opener_allowed
+ }
+ if not reply_only_issue_ids:
+ return events
+ threaded_issue_ids = {
+ str(issue_id)
+ for issue_id in ErrorTrackingAlertThread.objects.for_team(team_id)
+ .filter(issue_id__in=reply_only_issue_ids)
+ .values_list("issue_id", flat=True)
+ }
+ return [
+ pending
+ for pending in events
+ if pending.alert_inputs.opener_allowed or pending.alert_inputs.issue_id in threaded_issue_ids
+ ]
+
+
def produce_issue_lifecycle_event_on_commit(
*,
event: str,
diff --git a/products/error_tracking/backend/temporal/alerts/delivery.py b/products/error_tracking/backend/temporal/alerts/delivery.py
index ddb6b47d0e79..736fd470b199 100644
--- a/products/error_tracking/backend/temporal/alerts/delivery.py
+++ b/products/error_tracking/backend/temporal/alerts/delivery.py
@@ -3,20 +3,20 @@
Triggers gate thread openers only. A transition whose event satisfies one of an
alert's triggers opens a notification thread per destination: a root Slack
message whose `ts` is stored on the thread row. Every other lifecycle event is
-delivered as a reply into that thread, without a second trigger evaluation, and
-status transitions also edit the root in place.
+delivered as a reply into that thread, without a second trigger or filter
+evaluation, and status transitions also edit the root in place.
Delivery is at-least-once. A per-thread send claim serializes concurrent
deliveries so two notifications never post at the same time (the loser retries
into the winner's thread), and delivered notification ids recorded on the row make
a retry after a successful save a no-op. A crash between the Slack post and that
-save still re-posts on retry. The alert's stored filters are evaluated by the
-follow-up filter-evaluation layer before openers actually send; until then
-delivery is trigger-only.
+save still re-posts on retry. The alert's stored filters gate openers (see
+filtering.py).
"""
import dataclasses
from datetime import datetime, timedelta
+from uuid import UUID
from django.db import IntegrityError
from django.db.models import Q
@@ -33,6 +33,11 @@ from products.error_tracking.backend.models import (
ErrorTrackingAlertThread,
ErrorTrackingIssue,
)
+from products.error_tracking.backend.temporal.alerts.filtering import (
+ alert_filters_match,
+ fetch_exception_properties,
+ has_configured_filters,
+)
from products.error_tracking.backend.temporal.alerts.messages import (
DEFAULT_HEADLINE,
build_reply_text,
@@ -99,15 +104,10 @@ def plan_alert_deliveries(inputs: AlertDeliveryWorkflowInputs) -> list[PlannedDe
planned: list[PlannedDelivery] = []
for alert in alerts:
- trigger_matched = trigger is not None and trigger in alert.triggers
- if trigger_matched and _has_configured_filters(alert):
- # Until the filter-evaluation layer lands, alerts with configured
- # filters never open threads: missing an opener is better than posting
- # issues the user filtered out.
- trigger_matched = False
+ can_open = inputs.opener_allowed and trigger is not None and trigger in alert.triggers
for destination in destinations_by_alert.get(alert.id, []):
thread = threads_by_destination.get(destination.id)
- if thread is None and not trigger_matched:
+ if thread is None and not can_open:
# Replies never open threads: an update with no rooted thread stays
# unclaimed so a later opener can still start the conversation cleanly.
continue
@@ -116,24 +116,63 @@ def plan_alert_deliveries(inputs: AlertDeliveryWorkflowInputs) -> list[PlannedDe
# repeated opener event (e.g. spiking again, or reopen after resolve).
# An unrooted row is a failed root post: the next opener roots it.
rooted = thread is not None and bool(thread.external_ref.get("ts"))
- is_opener = trigger_matched and not rooted
+ is_opener = can_open and not rooted
planned.append(PlannedDelivery(alert=alert, destination=destination, is_opener=is_opener, thread=thread))
return planned
-def _has_configured_filters(alert: ErrorTrackingAlert) -> bool:
- # Empty filters still carry trivially-true compiled bytecode, so look at the
- # configured predicate keys instead.
- filters = alert.filters or {}
- return any(filters.get(key) for key in ("events", "actions", "properties", "filter_test_accounts"))
+def _opener_filter_matches(
+ planned: list[PlannedDelivery], inputs: AlertDeliveryWorkflowInputs
+) -> dict[UUID, bool | None]:
+ """Filters gate openers only, evaluated once per (transition, alert).
+
+ Replies follow the thread without a second evaluation, so this only looks at
+ alerts with a planned opener, and only fetches the triggering exception's
+ properties when at least one of those alerts configures filters.
+ """
+ opener_alerts = {delivery.alert.id: delivery.alert for delivery in planned if delivery.is_opener}
+ if not opener_alerts:
+ return {}
+ exception_properties: dict[str, object] | None = None
+ if any(has_configured_filters(alert) for alert in opener_alerts.values()):
+ try:
+ exception_properties = fetch_exception_properties(inputs)
+ except Exception:
+ # Filtered openers cannot be decided without the properties, but that
+ # must not hold back alerts that never needed them: those deliver now,
+ # the undecided ones fail the activity so the retry evaluates them.
+ logger.exception(
+ "error_tracking_alert_exception_properties_unavailable",
+ team_id=inputs.team_id,
+ issue_id=inputs.issue_id,
+ notification_id=inputs.notification_id,
+ )
+ return {
+ alert_id: (None if has_configured_filters(alert) else True) for alert_id, alert in opener_alerts.items()
+ }
+ return {
+ alert_id: alert_filters_match(alert, inputs, exception_properties) for alert_id, alert in opener_alerts.items()
+ }
def deliver_alert_notifications(inputs: AlertDeliveryWorkflowInputs) -> int:
planned = plan_alert_deliveries(inputs)
+ filter_matches = _opener_filter_matches(planned, inputs)
delivered = 0
failures = 0
busy = 0
for delivery in planned:
+ if delivery.is_opener:
+ verdict = filter_matches.get(delivery.alert.id, True)
+ if verdict is None:
+ # Undecided: the exception properties could not be fetched. Counted
+ # as a failure so the activity retries once the rest has delivered.
+ failures += 1
+ continue
+ if not verdict:
+ # A filtered-out opener leaves no thread behind, so later replies for
+ # this issue stay unclaimed and a matching opener can still root one.
+ continue
try:
if _deliver_one(delivery, inputs):
delivered += 1
diff --git a/products/error_tracking/backend/temporal/alerts/filtering.py b/products/error_tracking/backend/temporal/alerts/filtering.py
new file mode 100644
index 000000000000..ab7223d41313
--- /dev/null
+++ b/products/error_tracking/backend/temporal/alerts/filtering.py
@@ -0,0 +1,175 @@
+"""Alert filter evaluation: does a lifecycle transition match an alert's filters.
+
+Filters gate thread openers only; replies follow the thread without a second
+evaluation. The compiled bytecode is the same one hog function destinations
+evaluate, and the property surface mirrors the internal-event consumer
+(convertInternalEventToHogFunctionInvocationGlobals in nodejs/src/cdp/utils.ts):
+the triggering exception's properties are flattened under the lifecycle event's
+own properties, with the lifecycle properties winning on key collisions.
+"""
+
+import structlog
+
+from posthog.models import Team
+
+from products.error_tracking.backend.models import ErrorTrackingAlert
+from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs
+from products.error_tracking.backend.temporal.lifecycle.event_properties import fetch_event_properties
+
+from common.hogvm.python.execute import execute_bytecode
+from common.hogvm.python.stl import BLOCKING_FUNCTIONS
+
+logger = structlog.get_logger(__name__)
+
+
+def has_configured_filters(alert: ErrorTrackingAlert) -> bool:
+ # Empty filters still carry trivially-true compiled bytecode, so look at the
+ # configured predicate keys instead.
+ filters = alert.filters or {}
+ return any(filters.get(key) for key in ("events", "actions", "properties", "filter_test_accounts"))
+
+
+def _coerce_numeric(value: str) -> object:
+ # Extras cross Temporal as strings; numeric filters need real numbers or
+ # HogVM compares lexicographically ("9" > "10").
+ try:
+ return int(value)
+ except ValueError:
+ try:
+ return float(value)
+ except ValueError:
+ return value
+
+
+# Every key the lifecycle snapshot can carry, populated or not: a filter on one of
+# these is decidable without the exception (an absent value is a real "not set").
+LIFECYCLE_PROPERTY_KEYS = frozenset(
+ {
+ "name",
+ "description",
+ "issue_description",
+ "first_seen",
+ "severity",
+ "status",
+ "exception_timestamp",
+ "fingerprint",
+ "assignee",
+ }
+)
+
+
+def _filter_property_keys(alert: ErrorTrackingAlert, event: str) -> set[str]:
+ # Global properties apply to every branch; event branches are OR'd by the
+ # compiler, so only the branch for this event can constrain the outcome.
+ filters = alert.filters or {}
+ leaves = list(filters.get("properties") or [])
+ for entity in filters.get("events") or []:
+ if isinstance(entity, dict) and entity.get("id") == event:
+ leaves.extend(entity.get("properties") or [])
+ return {leaf["key"] for leaf in leaves if isinstance(leaf, dict) and isinstance(leaf.get("key"), str)}
+
+
+def alert_filters_match(
+ alert: ErrorTrackingAlert, inputs: AlertDeliveryWorkflowInputs, exception_properties: dict[str, object] | None
+) -> bool:
+ """Whether the transition passes the alert's filters.
+
+ `exception_properties` is None when the transition has no triggering event to
+ read them from (manual reopen, assign). Filters on lifecycle keys still evaluate;
+ one on any other key fails closed, because negated operators (is not, is not
+ set) would otherwise pass on the missing value and open excluded issues.
+ """
+ if not has_configured_filters(alert):
+ return True
+ bytecode = (alert.filters or {}).get("bytecode")
+ if not bytecode:
+ # Configured filters without compiled bytecode cannot be honored: skip the
+ # opener rather than posting issues the user meant to exclude.
+ logger.warning("error_tracking_alert_filters_missing_bytecode", alert_id=str(alert.id))
+ return False
+
+ # The producers always emit these keys, null included, and on the CDP plane a null
+ # lifecycle value shadows the exception's own property; mirror that so both planes agree.
+ lifecycle_properties: dict[str, object] = {
+ **{key: _coerce_numeric(value) for key, value in (inputs.extra or {}).items()},
+ "name": inputs.issue_name,
+ "description": inputs.issue_description,
+ "issue_description": inputs.issue_description,
+ "first_seen": inputs.first_seen,
+ "severity": inputs.severity,
+ }
+ optional_properties = {
+ # Spiking events carry no status at all, so absence must stay absence.
+ "status": inputs.status,
+ # Older in-flight payloads predate lifecycle_timestamp; the exception time
+ # is the right value for created/reopened and the previous one for spiking.
+ "exception_timestamp": inputs.lifecycle_timestamp or inputs.event_timestamp,
+ "fingerprint": inputs.fingerprint,
+ "assignee": inputs.assignee,
+ }
+ lifecycle_properties.update({key: value for key, value in optional_properties.items() if value is not None})
+ if exception_properties is None:
+ # Conservative on purpose: one OR'd branch that needs the exception makes the
+ # whole filter undecidable, even if a sibling branch would match on its own.
+ decidable_keys = LIFECYCLE_PROPERTY_KEYS | (inputs.extra or {}).keys()
+ unavailable_keys = _filter_property_keys(alert, inputs.event) - decidable_keys
+ if unavailable_keys:
+ logger.info(
+ "error_tracking_alert_filter_needs_exception_properties",
+ alert_id=str(alert.id),
+ team_id=inputs.team_id,
+ lifecycle_event=inputs.event,
+ keys=sorted(unavailable_keys),
+ )
+ return False
+ exception_properties = {}
+ filter_globals = {
+ "event": inputs.event,
+ "distinct_id": inputs.issue_id,
+ "timestamp": inputs.event_timestamp,
+ "elements_chain": "",
+ "properties": {**exception_properties, **lifecycle_properties},
+ }
+ try:
+ # Filters run on the shared worker; a smuggled blocking call must not hold it.
+ result = execute_bytecode(bytecode, filter_globals, disallowed_functions=BLOCKING_FUNCTIONS).result
+ except Exception:
+ # Match the hog function consumer: a filter that cannot be evaluated
+ # skips delivery instead of firing on excluded issues.
+ logger.exception(
+ "error_tracking_alert_filter_evaluation_failed",
+ alert_id=str(alert.id),
+ team_id=inputs.team_id,
+ lifecycle_event=inputs.event,
+ )
+ return False
+ return bool(result)
+
+
+class _EventPropertiesInputs:
+ """Adapter for the lifecycle event-properties protocol."""
+
+ class _Snapshot:
+ def __init__(self, created_at: str) -> None:
+ self.created_at = created_at
+
+ def __init__(self, inputs: AlertDeliveryWorkflowInputs) -> None:
+ self.team_id = inputs.team_id
+ self.event_uuid = inputs.event_uuid or ""
+ self.event_timestamp = inputs.event_timestamp or ""
+ self.issue = self._Snapshot(inputs.first_seen or "")
+
+
+def fetch_exception_properties(inputs: AlertDeliveryWorkflowInputs) -> dict[str, object] | None:
+ """The triggering exception's properties, for openers with configured filters.
+
+ Ingestion transitions carry the event uuid: the Redis handoff (with a
+ ClickHouse fallback) that the lifecycle activities already use serves those,
+ and a miss raises so the activity retries. Manual transitions (reopen, assign)
+ have no triggering event and get no lookup (a bulk action would turn into one
+ ClickHouse scan per issue): None tells the filter the data is unavailable.
+ """
+ if not inputs.event_uuid:
+ return None
+ team = Team.objects.get(id=inputs.team_id)
+ return fetch_event_properties(team, _EventPropertiesInputs(inputs))
diff --git a/products/error_tracking/backend/temporal/alerts/messages.py b/products/error_tracking/backend/temporal/alerts/messages.py
index f92e910aaddf..2edb7e312a0d 100644
--- a/products/error_tracking/backend/temporal/alerts/messages.py
+++ b/products/error_tracking/backend/temporal/alerts/messages.py
@@ -7,6 +7,7 @@ interpolated into mrkdwn text.
from django.conf import settings
+from products.error_tracking.backend.logic import build_issue_permalink_path
from products.error_tracking.backend.temporal.alerts.types import AlertDeliveryWorkflowInputs
ROOT_HEADLINES = {
@@ -31,8 +32,16 @@ def _truncate(text: str, limit: int) -> str:
return text if len(text) <= limit else text[: limit - 1] + "…"
-def issue_url(team_id: int, issue_id: str) -> str:
- return f"{settings.SITE_URL}/project/{team_id}/error_tracking/{issue_id}"
+def issue_url(inputs: AlertDeliveryWorkflowInputs) -> str:
+ # Slack keeps the root forever and a merge deletes the source issue, so the link
+ # follows the fingerprint to whichever issue owns it now. The path segment takes
+ # the environment id, which is what the workflow inputs carry.
+ return settings.SITE_URL + build_issue_permalink_path(
+ # Cymbal persists an explicitly empty manual fingerprint; that has no route.
+ project_id=inputs.team_id,
+ issue_id=inputs.issue_id,
+ fingerprint=inputs.fingerprint or None,
+ )
def root_headline(event: str) -> str:
@@ -67,7 +76,7 @@ def _link_block(inputs: AlertDeliveryWorkflowInputs) -> dict:
{
"type": "button",
"text": {"type": "plain_text", "text": "View issue", "emoji": True},
- "url": issue_url(inputs.team_id, inputs.issue_id),
+ "url": issue_url(inputs),
}
],
}
diff --git a/products/error_tracking/backend/temporal/alerts/types.py b/products/error_tracking/backend/temporal/alerts/types.py
index c229d87623f8..9d634430c54e 100644
--- a/products/error_tracking/backend/temporal/alerts/types.py
+++ b/products/error_tracking/backend/temporal/alerts/types.py
@@ -23,13 +23,24 @@ class AlertDeliveryWorkflowInputs:
status: str | None = None
assignee: str | None = None
actor_email: str | None = None
+ # Issue fields filters can reference; same values the internal event carries.
+ severity: str | None = None
+ fingerprint: str | None = None
+ first_seen: str | None = None
# Reference to the triggering exception event, when the transition has one
# (ingestion-driven transitions). Event properties are fetched by reference
# inside activities; nothing large crosses the Temporal payload boundary.
event_uuid: str | None = None
event_timestamp: str | None = None
+ # The `exception_timestamp` the lifecycle event carried. Spiking uses the detection
+ # time there while event_timestamp stays the exception's own time (the fetch anchor);
+ # filters must see the same value on both delivery paths.
+ lifecycle_timestamp: str | None = None
# Small event-specific extras (e.g. spike baseline values); never exception payloads.
extra: dict[str, str] | None = None
+ # Bulk mutations set this off: they only reply into threads that already exist,
+ # so one action over many issues cannot open a thread per issue.
+ opener_allowed: bool = True
@classmethod
def build(
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py
index 0a81cc118238..eb78059a9067 100644
--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py
@@ -203,7 +203,12 @@ def merge_issue_created_fingerprint_activity(
@posthoganalytics.scoped(capture_exceptions=False)
@close_db_connections
def dispatch_issue_created_alert_activity(inputs: IssueCreatedWorkflowInputs) -> None:
- dispatch_issue_lifecycle_alert(inputs, event="$error_tracking_issue_created", humanize_status=False)
+ dispatch_issue_lifecycle_alert(
+ inputs,
+ event="$error_tracking_issue_created",
+ exception_timestamp=inputs.event_timestamp,
+ humanize_status=False,
+ )
@activity.defn
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py
index e905345a04aa..e6fe453781c8 100644
--- a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py
@@ -16,7 +16,9 @@ from products.error_tracking.backend.temporal.lifecycle.side_effects import (
@posthoganalytics.scoped()
@close_db_connections
def dispatch_issue_reopened_alert_activity(inputs: IssueReopenedWorkflowInputs) -> None:
- dispatch_issue_lifecycle_alert(inputs, event="$error_tracking_issue_reopened")
+ dispatch_issue_lifecycle_alert(
+ inputs, event="$error_tracking_issue_reopened", exception_timestamp=inputs.event_timestamp
+ )
@activity.defn
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/activities.py
index e729bde84982..dc3194b346e5 100644
--- a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/activities.py
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/activities.py
@@ -60,6 +60,7 @@ def dispatch_issue_spiking_alert_activity(inputs: IssueSpikingWorkflowInputs) ->
dispatch_issue_lifecycle_alert(
inputs,
event="$error_tracking_issue_spiking",
+ exception_timestamp=inputs.detected_at,
extra_properties={
"computed_baseline": inputs.computed_baseline,
"current_bucket_value": inputs.current_bucket_value,
diff --git a/products/error_tracking/backend/temporal/lifecycle/side_effects.py b/products/error_tracking/backend/temporal/lifecycle/side_effects.py
index 99d68a4ffe3d..3dd43c24fe19 100644
--- a/products/error_tracking/backend/temporal/lifecycle/side_effects.py
+++ b/products/error_tracking/backend/temporal/lifecycle/side_effects.py
@@ -88,10 +88,20 @@ def _status_property(
return _STATUS_LABELS.get(status, status) if humanize_status else status
+def _normalize_timestamp(value: str) -> datetime:
+ timestamp = parse_datetime(value)
+ if timestamp is None:
+ return datetime.now(UTC)
+ if timestamp.tzinfo is None:
+ return timestamp.replace(tzinfo=UTC)
+ return timestamp
+
+
def alert_delivery_inputs(
inputs: IssueLifecycleWorkflowInputs,
*,
event: str,
+ exception_timestamp: str,
extra_properties: dict[str, object] | None = None,
include_status: bool = True,
humanize_status: bool = True,
@@ -111,10 +121,16 @@ def alert_delivery_inputs(
issue_description=inputs.issue.description,
status=_status_property(inputs, include_status=include_status, humanize_status=humanize_status),
assignee=inputs.assignee,
+ severity=inputs.issue.severity,
+ fingerprint=inputs.fingerprint,
+ first_seen=inputs.issue.created_at,
event_uuid=inputs.event_uuid,
# Paired with event_uuid, so it must be the exception's own time: spiking
# passes the detection time as exception_timestamp, which can differ.
event_timestamp=inputs.event_timestamp,
+ # Same value the internal event carries as exception_timestamp (spiking: the
+ # detection time), so filters see one clock across both paths.
+ lifecycle_timestamp=_normalize_timestamp(exception_timestamp).isoformat(),
extra=extra or None,
)
@@ -123,6 +139,7 @@ def dispatch_issue_lifecycle_alert(
inputs: IssueLifecycleWorkflowInputs,
*,
event: str,
+ exception_timestamp: str,
extra_properties: dict[str, object] | None = None,
include_status: bool = True,
humanize_status: bool = True,
@@ -132,6 +149,7 @@ def dispatch_issue_lifecycle_alert(
alert_delivery_inputs(
inputs,
event=event,
+ exception_timestamp=exception_timestamp,
extra_properties=extra_properties,
include_status=include_status,
humanize_status=humanize_status,
@@ -154,11 +172,7 @@ def produce_issue_lifecycle_internal_event(
return
event_properties = fetch_event_properties(team, inputs)
- timestamp = parse_datetime(exception_timestamp)
- if timestamp is None:
- timestamp = datetime.now(UTC)
- elif timestamp.tzinfo is None:
- timestamp = timestamp.replace(tzinfo=UTC)
+ timestamp = _normalize_timestamp(exception_timestamp)
properties: dict[str, object] = {
"name": inputs.issue.name,
diff --git a/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py b/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py
index 193497fc46bc..a78a22d8749d 100644
--- a/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py
+++ b/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py
@@ -225,6 +225,7 @@ def test_alert_inputs_mirror_the_internal_event_and_key_the_exception_by_its_own
alert = alert_delivery_inputs(
inputs,
event="$error_tracking_issue_spiking",
+ exception_timestamp=inputs.detected_at,
extra_properties={"computed_baseline": 2.0, "current_bucket_value": 40, "ignored": "x"},
include_status=False,
)
@@ -235,10 +236,14 @@ def test_alert_inputs_mirror_the_internal_event_and_key_the_exception_by_its_own
# carries the spike detection time.
assert alert.event_uuid == inputs.event_uuid
assert alert.event_timestamp == inputs.event_timestamp
+ # The filter clock is the lifecycle event's own time, normalized like the internal event.
+ assert alert.lifecycle_timestamp == "2026-07-21T12:30:00+00:00"
assert alert.extra == {"computed_baseline": "2.0", "current_bucket_value": "40"}
assert alert.issue_name is not None and len(alert.issue_name) == 500
- reopened = alert_delivery_inputs(_inputs(), event="$error_tracking_issue_reopened")
+ reopened = alert_delivery_inputs(
+ _inputs(), event="$error_tracking_issue_reopened", exception_timestamp=_inputs().event_timestamp
+ )
assert reopened.status == "Pending Release"
assert reopened.assignee == '{"type":"user","id":1}'
@@ -251,7 +256,9 @@ def test_dispatch_raises_so_the_activity_retries() -> None:
) as start,
pytest.raises(RuntimeError),
):
- dispatch_issue_lifecycle_alert(_inputs(), event="$error_tracking_issue_reopened")
+ dispatch_issue_lifecycle_alert(
+ _inputs(), event="$error_tracking_issue_reopened", exception_timestamp="2026-07-21T12:05:00Z"
+ )
assert start.call_args.args[0].event == "$error_tracking_issue_reopened"
diff --git a/products/error_tracking/backend/tests/api/test_alerts_api.py b/products/error_tracking/backend/tests/api/test_alerts_api.py
index ef1b395ee260..3f820df2cb17 100644
--- a/products/error_tracking/backend/tests/api/test_alerts_api.py
+++ b/products/error_tracking/backend/tests/api/test_alerts_api.py
@@ -126,6 +126,19 @@ class TestErrorTrackingAlerts(APIBaseTest):
assert update.status_code == 200, update.json()
assert update.json()["filters"]["bytecode"] is not None
+ def test_alert_accepts_a_comparison_against_an_empty_string(self):
+ # An empty string is a real value, unlike a missing one.
+ integration = self._create_slack_integration()
+ leaf = {"key": "environment", "value": "", "operator": "exact", "type": "event"}
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/error_tracking/alerts/",
+ data=self._valid_payload(integration, filters={"properties": [leaf]}),
+ format="json",
+ )
+
+ assert response.status_code == 201, response.json()
+
def test_alert_create_rejects_uncompilable_filters(self):
integration = self._create_slack_integration()
@@ -171,6 +184,42 @@ class TestErrorTrackingAlerts(APIBaseTest):
{"destinations": [{"channel_type": "carrier_pigeon", "integration_id": 1, "config": {}}]},
),
("missing_integration", {"destinations": [{"channel_type": "slack", "config": {"channel": "C1"}}]}),
+ (
+ "typeless_event_entity",
+ {"filters": {"events": [{"id": "$error_tracking_issue_created"}]}},
+ ),
+ ("keyless_property_filter", {"filters": {"properties": [{"value": "x", "type": "event"}]}}),
+ (
+ "valueless_property_filter",
+ {"filters": {"properties": [{"key": "environment", "operator": "exact", "type": "event"}]}},
+ ),
+ ("idless_event_entity", {"filters": {"events": [{"type": "events"}]}}),
+ (
+ "object_event_properties",
+ {
+ "filters": {
+ "events": [
+ {
+ "id": "$error_tracking_issue_created",
+ "type": "events",
+ "properties": {"key": "sleep(5)", "type": "hogql"},
+ }
+ ]
+ }
+ },
+ ),
+ (
+ "person_property_filter",
+ {"filters": {"properties": [{"key": "email", "value": "@example.com", "type": "person"}]}},
+ ),
+ (
+ "action_filters",
+ {"filters": {"actions": [{"id": "1", "name": "Action", "type": "actions"}]}},
+ ),
+ (
+ "filter_test_accounts",
+ {"filters": {"filter_test_accounts": True}},
+ ),
(
"missing_channel_in_config",
{"destinations": [{"channel_type": "slack", "integration_id": VALID_INTEGRATION, "config": {}}]},
diff --git a/products/error_tracking/backend/tests/api/test_error_tracking_api.py b/products/error_tracking/backend/tests/api/test_error_tracking_api.py
index 7999ca77ab2e..b48257632c5d 100644
--- a/products/error_tracking/backend/tests/api/test_error_tracking_api.py
+++ b/products/error_tracking/backend/tests/api/test_error_tracking_api.py
@@ -31,6 +31,7 @@ from posthog.settings import (
from products.access_control.backend.models.role import Role
from products.error_tracking.backend.models import (
ErrorTrackingAlert,
+ ErrorTrackingAlertThread,
ErrorTrackingIssue,
ErrorTrackingIssueAssignment,
ErrorTrackingIssueFingerprintV2,
@@ -585,9 +586,25 @@ class TestErrorTracking(APIBaseTest):
issue.refresh_from_db()
assert issue.status == ErrorTrackingIssue.Status.RESOLVED
- def _enable_alerts(self) -> None:
+ def _enable_alerts(self) -> ErrorTrackingAlert:
with team_scope(self.team.id):
- ErrorTrackingAlert.objects.create(team=self.team, name="Notify", triggers=["issue_created"])
+ return ErrorTrackingAlert.objects.create(team=self.team, name="Notify", triggers=["issue_created"])
+
+ def _open_thread(self, alert: ErrorTrackingAlert, issue: ErrorTrackingIssue) -> None:
+ with team_scope(self.team.id):
+ integration = Integration.objects.create(
+ team=self.team, kind=Integration.IntegrationKind.SLACK.value, config={"team": {"id": "T1"}}
+ )
+ destination = alert.destinations.create(
+ team=self.team, channel_type="slack", integration=integration, config={"channel": "C1"}
+ )
+ ErrorTrackingAlertThread.objects.create(
+ team=self.team,
+ alert=alert,
+ issue=issue,
+ destination=destination,
+ external_ref={"channel": "C1", "ts": "1.2"},
+ )
def test_issue_status_update_queues_alert_dispatch_with_the_event_uuid(self):
issue = self.create_issue()
@@ -614,6 +631,7 @@ class TestErrorTracking(APIBaseTest):
assert notification["issue_id"] == str(issue.id)
assert notification["status"] == "Resolved"
assert notification["actor_email"] == self.user.email
+ assert notification["opener_allowed"] is True
# The delivery workflow and the internal event share the notification id.
assert notification["notification_id"] == mock_produce.call_args.kwargs["event"].uuid
@@ -642,7 +660,9 @@ class TestErrorTracking(APIBaseTest):
def test_issue_bulk_assign_queues_one_dispatch_task_per_transaction(self):
issues = [self.create_issue() for _ in range(3)]
- self._enable_alerts()
+ alert = self._enable_alerts()
+ # Bulk transitions only reply: issues without a thread queue nothing.
+ self._open_thread(alert, issues[0])
with (
patch("products.error_tracking.backend.logic.lifecycle_events.produce_internal_event") as mock_produce,
@@ -665,9 +685,10 @@ class TestErrorTracking(APIBaseTest):
assert response.status_code == 200, response.json()
assert mock_produce.call_count == 3
mock_dispatch.assert_called_once()
- notifications = mock_dispatch.call_args.kwargs["notifications"]
- assert {n["event"] for n in notifications} == {"$error_tracking_issue_assigned"}
- assert {n["issue_id"] for n in notifications} == {str(issue.id) for issue in issues}
+ (notification,) = mock_dispatch.call_args.kwargs["notifications"]
+ assert notification["event"] == "$error_tracking_issue_assigned"
+ assert notification["issue_id"] == str(issues[0].id)
+ assert notification["opener_allowed"] is False
def test_issue_status_update_queues_nothing_for_teams_without_alerts(self):
issue = self.create_issue()
@@ -689,7 +710,9 @@ class TestErrorTracking(APIBaseTest):
def test_issue_bulk_set_status_queues_one_dispatch_task_per_transaction(self):
issues = [self.create_issue() for _ in range(3)]
- self._enable_alerts()
+ alert = self._enable_alerts()
+ for issue in issues:
+ self._open_thread(alert, issue)
with (
patch("products.error_tracking.backend.logic.lifecycle_events.produce_internal_event") as mock_produce,
@@ -708,6 +731,7 @@ class TestErrorTracking(APIBaseTest):
mock_dispatch.assert_called_once()
notifications = mock_dispatch.call_args.kwargs["notifications"]
assert {n["issue_id"] for n in notifications} == {str(issue.id) for issue in issues}
+ assert all(n["opener_allowed"] is False for n in notifications)
assert {n["notification_id"] for n in notifications} == {
call.kwargs["event"].uuid for call in mock_produce.call_args_list
}
diff --git a/products/error_tracking/backend/tests/test_alert_delivery.py b/products/error_tracking/backend/tests/test_alert_delivery.py
index b17735f6eb74..d543fd983766 100644
--- a/products/error_tracking/backend/tests/test_alert_delivery.py
+++ b/products/error_tracking/backend/tests/test_alert_delivery.py
@@ -15,6 +15,7 @@ from parameterized import parameterized
from temporalio.common import WorkflowIDReusePolicy
from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError
+from posthog.cdp.filters import compile_filters_bytecode
from posthog.models.integration import Integration
from posthog.models.scoping import team_scope
@@ -33,7 +34,7 @@ from products.error_tracking.backend.temporal.alerts.dispatch import (
start_alert_delivery_workflow,
start_alert_delivery_workflows,
)
-from products.error_tracking.backend.temporal.alerts.messages import build_reply_text, build_root_message
+from products.error_tracking.backend.temporal.alerts.messages import build_reply_text, build_root_message, issue_url
from products.error_tracking.backend.temporal.alerts.types import THREAD_BUSY_ERROR_TYPE, AlertDeliveryWorkflowInputs
from products.error_tracking.backend.temporal.alerts.workflow import BUSY_WAIT_LIMIT
@@ -80,6 +81,25 @@ class AlertTestMixin(BaseTest):
defaults.update(overrides)
return AlertDeliveryWorkflowInputs(**defaults)
+ def _mock_slack(self):
+ slack_integration = patch("products.error_tracking.backend.temporal.alerts.delivery.SlackIntegration")
+ mock = slack_integration.start()
+ self.addCleanup(slack_integration.stop)
+ client = mock.return_value.client
+ client.chat_postMessage.return_value = {"channel": "C0123", "ts": "111.222"}
+ return client
+
+ def _thread(self, alert, *, rooted=True) -> ErrorTrackingAlertThread:
+ with team_scope(self.team.id):
+ return ErrorTrackingAlertThread.objects.create(
+ team=self.team,
+ alert=alert,
+ issue=self.issue,
+ destination=alert.destinations.get(),
+ external_ref={"channel": "C0123", "ts": "111.222"} if rooted else {},
+ root_headline="🔴 New issue" if rooted else "",
+ )
+
class TestAlertDeliveryPlanning(AlertTestMixin):
@parameterized.expand(
@@ -155,6 +175,19 @@ class TestAlertDeliveryPlanning(AlertTestMixin):
assert planned[0].is_opener is False
assert planned[0].thread is not None
+ def test_bulk_transition_only_replies_into_existing_threads(self):
+ # A bulk action over many issues must not open one thread per issue.
+ alert = self._create_alert(triggers=["issue_assigned"])
+ inputs = self._inputs("$error_tracking_issue_assigned", opener_allowed=False)
+
+ assert plan_alert_deliveries(inputs) == []
+
+ thread = self._thread(alert)
+ (planned,) = plan_alert_deliveries(inputs)
+ assert planned.is_opener is False
+ assert planned.thread is not None
+ assert planned.thread.id == thread.id
+
def test_multi_destination_alert_plans_per_destination(self):
alert = self._create_alert(triggers=["issue_created"])
with team_scope(self.team.id):
@@ -218,27 +251,18 @@ class TestAlertMessages(SimpleTestCase):
def test_spiking_reply_without_measurements_stays_short(self):
assert build_reply_text(self._inputs()) == "📈 Spiking again"
+ def test_issue_link_follows_the_fingerprint_when_known(self):
+ # A merge deletes the source issue; the fingerprint route redirects to the survivor.
+ inputs = AlertDeliveryWorkflowInputs(
+ notification_id="notif-1", team_id=1, issue_id="issue-1", event="$error_tracking_issue_created"
+ )
+ assert issue_url(inputs).endswith("/project/1/error_tracking/issue-1")
+ assert issue_url(dataclasses.replace(inputs, fingerprint="")).endswith("/project/1/error_tracking/issue-1")
+ with_fingerprint = dataclasses.replace(inputs, fingerprint="a/b c")
+ assert issue_url(with_fingerprint).endswith("/project/1/error_tracking/fingerprint/a%2Fb%20c")
-class TestSlackThreadDelivery(AlertTestMixin):
- def _mock_slack(self):
- slack_integration = patch("products.error_tracking.backend.temporal.alerts.delivery.SlackIntegration")
- mock = slack_integration.start()
- self.addCleanup(slack_integration.stop)
- client = mock.return_value.client
- client.chat_postMessage.return_value = {"channel": "C0123", "ts": "111.222"}
- return client
-
- def _thread(self, alert, *, rooted=True) -> ErrorTrackingAlertThread:
- with team_scope(self.team.id):
- return ErrorTrackingAlertThread.objects.create(
- team=self.team,
- alert=alert,
- issue=self.issue,
- destination=alert.destinations.get(),
- external_ref={"channel": "C0123", "ts": "111.222"} if rooted else {},
- root_headline="🔴 New issue" if rooted else "",
- )
+class TestSlackThreadDelivery(AlertTestMixin):
def test_opener_posts_root_and_stores_thread_state(self):
client = self._mock_slack()
alert = self._create_alert(triggers=["issue_created"])
@@ -500,26 +524,6 @@ class TestSlackThreadDelivery(AlertTestMixin):
assert thread.external_ref == {"channel": "C0123", "ts": "111.222", "root_status": "Active"}
assert thread.delivered_notification_ids == ["notif-1"]
- def test_opener_with_configured_filters_stays_dark(self):
- # Filter evaluation lands in a follow-up layer; until then a filtered
- # alert must not post issues the user may have excluded.
- client = self._mock_slack()
- with team_scope(self.team.id):
- alert = ErrorTrackingAlert.objects.create(
- team=self.team,
- name="Filtered",
- triggers=["issue_created"],
- filters={"properties": [{"key": "environment", "value": "production", "type": "event"}]},
- )
- alert.destinations.create(
- team=self.team, channel_type="slack", integration=self.integration, config={"channel": "C0123"}
- )
-
- delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))
-
- assert delivered == 0
- client.chat_postMessage.assert_not_called()
-
def test_root_header_stays_within_slack_limit(self):
client = self._mock_slack()
self._create_alert(triggers=["issue_created"])
@@ -576,6 +580,292 @@ class TestSlackThreadDelivery(AlertTestMixin):
assert len(rooted) == 1
+class TestAlertFilterEvaluation(AlertTestMixin):
+ def _create_filtered_alert(self, filters: dict, *, triggers=None) -> ErrorTrackingAlert:
+ compiled = compile_filters_bytecode(dict(filters), self.team)
+ assert not compiled.get("bytecode_error"), compiled
+ with team_scope(self.team.id):
+ alert = ErrorTrackingAlert.objects.create(
+ team=self.team,
+ name="Filtered",
+ triggers=triggers if triggers is not None else ["issue_created"],
+ filters=compiled,
+ )
+ alert.destinations.create(
+ team=self.team, channel_type="slack", integration=self.integration, config={"channel": "C0123"}
+ )
+ return alert
+
+ def _patch_exception_properties(self, properties: dict):
+ fetcher = patch(
+ "products.error_tracking.backend.temporal.alerts.delivery.fetch_exception_properties",
+ return_value=properties,
+ )
+ mock = fetcher.start()
+ self.addCleanup(fetcher.stop)
+ return mock
+
+ ENVIRONMENT_FILTER = {"properties": [{"key": "environment", "value": "production", "type": "event"}]}
+
+ def test_matching_event_property_filter_opens_a_thread(self):
+ client = self._mock_slack()
+ self._create_filtered_alert(self.ENVIRONMENT_FILTER)
+ self._patch_exception_properties({"environment": "production"})
+
+ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))
+
+ assert delivered == 1
+ client.chat_postMessage.assert_called_once()
+
+ def test_non_matching_filter_skips_the_opener_and_leaves_no_thread(self):
+ client = self._mock_slack()
+ self._create_filtered_alert(self.ENVIRONMENT_FILTER)
+ self._patch_exception_properties({"environment": "staging"})
+
+ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))
+
+ assert delivered == 0
+ client.chat_postMessage.assert_not_called()
+ with team_scope(self.team.id):
+ assert not ErrorTrackingAlertThread.objects.filter(issue=self.issue).exists()
+
+ def test_exception_timestamp_filter_sees_the_lifecycle_value(self):
+ # Spiking carries the detection time as exception_timestamp on the lifecycle
+ # event; the exception's own time is only the fetch anchor. Filters must see
+ # the same value the CDP path sees.
+ client = self._mock_slack()
+ self._create_filtered_alert(
+ {"properties": [{"key": "exception_timestamp", "value": "2026-07-21T15:00:00+00:00", "type": "event"}]},
+ triggers=["issue_spiking"],
+ )
+ self._patch_exception_properties({})
+
+ delivered = deliver_alert_notifications(
+ self._inputs(
+ "$error_tracking_issue_spiking",
+ event_timestamp="2026-07-21T14:00:00+00:00",
+ lifecycle_timestamp="2026-07-21T15:00:00+00:00",
+ )
+ )
+
+ assert delivered == 1
+ client.chat_postMessage.assert_called_once()
+
+ def test_exception_timestamp_filter_falls_back_to_the_event_time(self):
+ # Payloads from before lifecycle_timestamp existed still evaluate the filter.
+ client = self._mock_slack()
+ self._create_filtered_alert(
+ {"properties": [{"key": "exception_timestamp", "value": "2026-07-21T14:00:00+00:00", "type": "event"}]}
+ )
+ self._patch_exception_properties({})
+
+ delivered = deliver_alert_notifications(
+ self._inputs("$error_tracking_issue_created", event_timestamp="2026-07-21T14:00:00+00:00")
+ )
+
+ assert delivered == 1
+ client.chat_postMessage.assert_called_once()
+
+ def test_property_fetch_failure_does_not_block_unfiltered_alerts(self):
+ client = self._mock_slack()
+ self._create_alert(triggers=["issue_created"])
+ self._create_filtered_alert(self.ENVIRONMENT_FILTER)
+ fetcher = self._patch_exception_properties({"environment": "production"})
+ fetcher.side_effect = RuntimeError("clickhouse unavailable")
+ inputs = self._inputs("$error_tracking_issue_created")
+
+ # The unfiltered alert posts now; the activity still fails so the filtered one is retried.
+ with self.assertRaises(AlertDeliveryError):
+ deliver_alert_notifications(inputs)
+ assert client.chat_postMessage.call_count == 1
+
+ fetcher.side_effect = None
+ assert deliver_alert_notifications(inputs) == 1
+ assert client.chat_postMessage.call_count == 2
+
+ def test_issue_field_filter_evaluates_from_the_lifecycle_snapshot(self):
+ client = self._mock_slack()
+ self._create_filtered_alert({"properties": [{"key": "severity", "value": "critical", "type": "event"}]})
+ fetcher = self._patch_exception_properties({})
+
+ skipped = deliver_alert_notifications(self._inputs("$error_tracking_issue_created", severity="low"))
+ delivered = deliver_alert_notifications(
+ self._inputs("$error_tracking_issue_created", notification_id="notif-2", severity="critical")
+ )
+
+ assert (skipped, delivered) == (0, 1)
+ client.chat_postMessage.assert_called_once()
+ assert fetcher.call_count == 2
+
+ def test_null_lifecycle_fields_shadow_exception_properties(self):
+ # The CDP plane spreads lifecycle properties over the exception's with nulls
+ # winning; a team's own `severity` on the exception must not leak through here.
+ client = self._mock_slack()
+ self._create_filtered_alert({"properties": [{"key": "severity", "value": "critical", "type": "event"}]})
+ self._patch_exception_properties({"severity": "critical"})
+
+ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created", severity=None))
+
+ assert delivered == 0
+ client.chat_postMessage.assert_not_called()
+
+ def test_spiking_leaves_the_exceptions_status_visible(self):
+ # Spiking events carry no status, so an exception's own status property must
+ # stay filterable rather than being shadowed by a null.
+ client = self._mock_slack()
+ self._create_filtered_alert(
+ {"properties": [{"key": "status", "value": "open", "type": "event"}]}, triggers=["issue_spiking"]
+ )
+ self._patch_exception_properties({"status": "open"})
+
+ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_spiking", status=None))
+
+ assert delivered == 1
+ client.chat_postMessage.assert_called_once()
+
+ def test_lifecycle_only_properties_are_filterable(self):
+ client = self._mock_slack()
+ self._create_filtered_alert(
+ {"properties": [{"key": "computed_baseline", "value": "10", "type": "event"}]},
+ triggers=["issue_spiking"],
+ )
+ self._patch_exception_properties({})
+
+ skipped = deliver_alert_notifications(
+ self._inputs("$error_tracking_issue_spiking", extra={"computed_baseline": "99"})
+ )
+ delivered = deliver_alert_notifications(
+ self._inputs("$error_tracking_issue_spiking", notification_id="n-2", extra={"computed_baseline": "10"})
+ )
+
+ assert (skipped, delivered) == (0, 1)
+ client.chat_postMessage.assert_called_once()
+
+ def _patch_event_properties_lookup(self):
+ lookup = patch("products.error_tracking.backend.temporal.alerts.filtering.fetch_event_properties")
+ mock = lookup.start()
+ self.addCleanup(lookup.stop)
+ return mock
+
+ @parameterized.expand(
+ [
+ ("equals", {"key": "environment", "value": "production", "type": "event"}),
+ # Negated operators pass on a missing property; unavailable data must still fail closed.
+ ("is_not", {"key": "environment", "value": "staging", "operator": "is_not", "type": "event"}),
+ ("is_not_set", {"key": "environment", "operator": "is_not_set", "type": "event"}),
+ ]
+ )
+ def test_manual_opener_fails_closed_on_exception_property_filters(self, _name, leaf):
+ # No triggering event to look up: an exception-property filter cannot be
+ # decided, so the opener is skipped rather than scanning ClickHouse for a sample.
+ client = self._mock_slack()
+ self._create_filtered_alert({"properties": [leaf]}, triggers=["issue_assigned"])
+ lookup = self._patch_event_properties_lookup()
+
+ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_assigned", event_uuid=None))
+
+ assert delivered == 0
+ client.chat_postMessage.assert_not_called()
+ lookup.assert_not_called()
+ with team_scope(self.team.id):
+ assert not ErrorTrackingAlertThread.objects.filter(issue=self.issue).exists()
+
+ @parameterized.expand(
+ [
+ (
+ "populated_lifecycle_key",
+ {"properties": [{"key": "severity", "value": "critical", "type": "event"}]},
+ {"severity": "critical"},
+ ),
+ # An absent lifecycle value is a real "not set", not unavailable data.
+ (
+ "absent_lifecycle_key",
+ {"properties": [{"key": "assignee", "operator": "is_not_set", "type": "event"}]},
+ {"assignee": None},
+ ),
+ # Event branches are OR'd: another branch's exception-property leaf is irrelevant.
+ (
+ "other_event_branch",
+ {
+ "events": [
+ {
+ "id": "$error_tracking_issue_created",
+ "type": "events",
+ "properties": [{"key": "environment", "value": "production", "type": "event"}],
+ },
+ {"id": "$error_tracking_issue_assigned", "type": "events", "properties": []},
+ ]
+ },
+ {},
+ ),
+ ]
+ )
+ def test_manual_opener_evaluates_lifecycle_filters(self, _name, filters, overrides):
+ client = self._mock_slack()
+ self._create_filtered_alert(filters, triggers=["issue_assigned"])
+ lookup = self._patch_event_properties_lookup()
+
+ delivered = deliver_alert_notifications(
+ self._inputs("$error_tracking_issue_assigned", event_uuid=None, **overrides)
+ )
+
+ assert delivered == 1
+ client.chat_postMessage.assert_called_once()
+ lookup.assert_not_called()
+
+ def test_ingestion_opener_looks_up_the_triggering_event(self):
+ client = self._mock_slack()
+ self._create_filtered_alert(self.ENVIRONMENT_FILTER)
+ lookup = self._patch_event_properties_lookup()
+ lookup.return_value = {"environment": "production"}
+
+ delivered = deliver_alert_notifications(
+ self._inputs("$error_tracking_issue_created", event_uuid="evt-1", event_timestamp="2026-07-21T14:00:00Z")
+ )
+
+ assert delivered == 1
+ client.chat_postMessage.assert_called_once()
+ lookup.assert_called_once()
+ assert lookup.call_args.args[1].event_uuid == "evt-1"
+
+ def test_replies_are_never_filtered(self):
+ client = self._mock_slack()
+ alert = self._create_filtered_alert(self.ENVIRONMENT_FILTER)
+ self._thread(alert)
+ fetcher = self._patch_exception_properties({"environment": "staging"})
+
+ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_resolved"))
+
+ assert delivered == 1
+ assert client.chat_postMessage.call_args.kwargs["thread_ts"] == "111.222"
+ # Replies follow the thread: no opener planned, so nothing was fetched.
+ fetcher.assert_not_called()
+
+ def test_unfiltered_alerts_never_fetch_event_properties(self):
+ client = self._mock_slack()
+ self._create_alert(triggers=["issue_created"])
+ fetcher = self._patch_exception_properties({})
+
+ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))
+
+ assert delivered == 1
+ client.chat_postMessage.assert_called_once()
+ fetcher.assert_not_called()
+
+ def test_broken_bytecode_fails_closed(self):
+ client = self._mock_slack()
+ alert = self._create_filtered_alert(self.ENVIRONMENT_FILTER)
+ with team_scope(self.team.id):
+ alert.filters = {**alert.filters, "bytecode": ["not-bytecode"]}
+ alert.save()
+ self._patch_exception_properties({"environment": "production"})
+
+ delivered = deliver_alert_notifications(self._inputs("$error_tracking_issue_created"))
+
+ assert delivered == 0
+ client.chat_postMessage.assert_not_called()
+
+
class TestAlertDeliveryDispatch(AlertTestMixin):
def _dispatch(self, *notification_ids: str) -> None:
batch = [