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.

fix(replay): stop posthog ai suggesting event exclusion it cannot apply (#117312)

posthog[bot]82078fc350f2
diff --git a/ee/hogai/tools/replay/filter_session_recordings.py b/ee/hogai/tools/replay/filter_session_recordings.py
index 835ffaa67b96..140dfca3ec16 100644
--- a/ee/hogai/tools/replay/filter_session_recordings.py
+++ b/ee/hogai/tools/replay/filter_session_recordings.py
@@ -1,12 +1,19 @@
from datetime import datetime, timedelta
from textwrap import dedent
-from typing import Any, Literal
+from typing import Any, Literal, Self
import structlog
+from langchain_core.runnables import RunnableConfig
from posthoganalytics import capture_exception
-from pydantic import BaseModel, Field
-
-from posthog.schema import EventsNode, FilterLogicalOperator, MaxRecordingUniversalFilters, RecordingsQuery
+from pydantic import BaseModel, Field, PrivateAttr
+
+from posthog.schema import (
+ EventsNode,
+ FilterLogicalOperator,
+ MaxRecordingEventFilter,
+ MaxRecordingUniversalFilters,
+ RecordingsQuery,
+)
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings
@@ -14,6 +21,7 @@ from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models import Team, User
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
from posthog.session_recordings.queries.sub_queries.events_subquery import ReplayFiltersEventsSubQuery
from posthog.session_recordings.queries.utils import SessionRecordingQueryResult, expand_test_account_filters
@@ -22,24 +30,30 @@ from posthog.temporal.session_replay.count_playlist_items import convert_filters
from products.replay.backend.prompts import (
DATE_FIELDS_PROMPT,
+ EVENT_NEGATION_SUPPORTED_PROMPT,
+ EVENT_NEGATION_UNSUPPORTED_PROMPT,
FILTER_EXAMPLES_PROMPT,
FILTER_FIELDS_TAXONOMY_PROMPT,
PRODUCT_DESCRIPTION_PROMPT,
SESSION_REPLAY_EXAMPLES_PROMPT,
)
+from ee.hogai.context.context import AssistantContextManager
from ee.hogai.tool import MaxTool, ToolMessagesArtifact
+from ee.hogai.tool_errors import MaxToolRetryableError
from ee.hogai.tools.replay import empty_result_diagnosis as diagnosis
from ee.hogai.tools.replay.empty_result_diagnosis import EventSessionLinkage
+from ee.hogai.utils.feature_flags import has_replay_negative_event_filters_feature_flag
+from ee.hogai.utils.types import AssistantState
+from ee.hogai.utils.types.base import NodePath
logger = structlog.get_logger(__name__)
DIAGNOSIS_MAX_EXECUTION_TIME = 30
-class FilterSessionRecordingsToolArgs(BaseModel):
- recordings_filters: MaxRecordingUniversalFilters = Field(
- description=dedent(f"""
+def _recordings_filters_description(event_negation_prompt: str) -> str:
+ return dedent(f"""
User's question converted into a recordings query.
{PRODUCT_DESCRIPTION_PROMPT}
@@ -139,6 +153,8 @@ class FilterSessionRecordingsToolArgs(BaseModel):
{FILTER_EXAMPLES_PROMPT}
+ {event_negation_prompt}
+
# Critical Reminders
1. **Property discovery**: ALWAYS use read_taxonomy to discover ALL properties and events before creating filters - never assume they exist
@@ -151,6 +167,17 @@ class FilterSessionRecordingsToolArgs(BaseModel):
8. **Silence**: Do not output when performing taxonomy exploration, just use the tools
9. **Recording properties are NOT events**: `keypress_count`, `click_count`, `console_error_count`, `mouse_activity_count`, `activity_score` always use `type: "recording"`. Events like `$keypress` or `$click` do not exist.
""").strip()
+
+
+class FilterSessionRecordingsToolArgs(BaseModel):
+ recordings_filters: MaxRecordingUniversalFilters = Field(
+ description=_recordings_filters_description(EVENT_NEGATION_UNSUPPORTED_PROMPT)
+ )
+
+
+class FilterSessionRecordingsWithEventNegationToolArgs(BaseModel):
+ recordings_filters: MaxRecordingUniversalFilters = Field(
+ description=_recordings_filters_description(EVENT_NEGATION_SUPPORTED_PROMPT)
)
@@ -171,12 +198,49 @@ class FilterSessionRecordingsTool(MaxTool):
""").strip()
context_prompt_template: str = "Current recordings filters are: {{{current_filters}}}.\nCurrent session ID being viewed: {{{current_session_id}}}."
+ _allow_event_negation: bool = PrivateAttr(default=False)
+
+ @classmethod
+ async def create_tool_class(
+ cls,
+ *,
+ team: Team,
+ user: User,
+ node_path: tuple[NodePath, ...] | None = None,
+ state: AssistantState | None = None,
+ config: RunnableConfig | None = None,
+ context_manager: AssistantContextManager | None = None,
+ ) -> Self:
+ # Event negation stays behind the same flag as the "Did not perform" option in the replay filters UI
+ allow_event_negation = await database_sync_to_async(has_replay_negative_event_filters_feature_flag)(team, user)
+ tool = cls(
+ team=team,
+ user=user,
+ node_path=node_path,
+ state=state,
+ config=config,
+ context_manager=context_manager,
+ args_schema=(
+ FilterSessionRecordingsWithEventNegationToolArgs
+ if allow_event_negation
+ else FilterSessionRecordingsToolArgs
+ ),
+ )
+ tool._allow_event_negation = allow_event_negation
+ return tool
+
def get_required_resource_access(self):
return [("session_recording", "viewer")]
async def _arun_impl(
self, recordings_filters: MaxRecordingUniversalFilters
) -> tuple[str, ToolMessagesArtifact | None]:
+ if not self._allow_event_negation and self._has_negated_event(recordings_filters):
+ raise MaxToolRetryableError(
+ "Excluding sessions by event is not available. Remove `negation` from every event filter, "
+ "and tell the user that this filter is not available."
+ )
+
# Convert filters to recordings query and execute
recordings_query = convert_filters_to_recordings_query(recordings_filters.model_dump(exclude_none=True))
@@ -204,6 +268,14 @@ class FilterSessionRecordingsTool(MaxTool):
content += f"\n...and {total_count - 5} more recordings"
return content, None
+ @staticmethod
+ def _has_negated_event(recordings_filters: MaxRecordingUniversalFilters) -> bool:
+ return any(
+ isinstance(value, MaxRecordingEventFilter) and value.negation
+ for group in recordings_filters.filter_group.values
+ for value in group.values
+ )
+
async def _diagnose_empty_result(self, recordings_query: RecordingsQuery) -> str:
try:
linkages = await database_sync_to_async(self._get_event_session_linkage, thread_sensitive=False)(
diff --git a/ee/hogai/tools/replay/test/test_filter_session_recordings.py b/ee/hogai/tools/replay/test/test_filter_session_recordings.py
index a188741c9b92..ecd3a0c614c4 100644
--- a/ee/hogai/tools/replay/test/test_filter_session_recordings.py
+++ b/ee/hogai/tools/replay/test/test_filter_session_recordings.py
@@ -2,6 +2,7 @@ from datetime import datetime, timedelta
import time_machine
from posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTest, _create_event, flush_persons_and_events
+from unittest.mock import patch
from langchain_core.runnables import RunnableConfig
from parameterized import parameterized
@@ -21,7 +22,12 @@ from posthog.models.utils import uuid7
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from ee.hogai.context.context import AssistantContextManager
-from ee.hogai.tools.replay.filter_session_recordings import FilterSessionRecordingsTool
+from ee.hogai.tool_errors import MaxToolRetryableError
+from ee.hogai.tools.replay.filter_session_recordings import (
+ FilterSessionRecordingsTool,
+ FilterSessionRecordingsToolArgs,
+ FilterSessionRecordingsWithEventNegationToolArgs,
+)
from ee.hogai.utils.types import AssistantState
from ee.hogai.utils.types.base import NodePath
@@ -106,13 +112,16 @@ class TestFilterSessionRecordingsTool(ClickhouseTestMixin, NonAtomicBaseTest):
self.assertIn("No recordings found", result_text)
self.assertIsNone(artifact)
- def _event_filters(self, event: str, properties: list[dict] | None = None) -> MaxRecordingUniversalFilters:
+ def _event_filters(
+ self, event: str, properties: list[dict] | None = None, negation: bool | None = None
+ ) -> MaxRecordingUniversalFilters:
return MaxRecordingUniversalFilters(
filter_group=MaxOuterUniversalFiltersGroup(
type="AND",
values=[
MaxInnerUniversalFiltersGroup(
- type="AND", values=[MaxRecordingEventFilter(id=event, properties=properties)]
+ type="AND",
+ values=[MaxRecordingEventFilter(id=event, properties=properties, negation=negation)],
),
],
),
@@ -183,6 +192,40 @@ class TestFilterSessionRecordingsTool(ClickhouseTestMixin, NonAtomicBaseTest):
self.assertIn("no `paywall_shown` events matched this filter", result_text)
self.assertIn("Do not offer a Replay Vision scanner", result_text)
+ @parameterized.expand([("flag on", True), ("flag off", False)])
+ async def test_negated_event_filter_follows_the_replay_negative_event_filters_flag(
+ self, _name: str, flag_enabled: bool
+ ):
+ buyer_session = self._produce_replay(distinct_id="buyer")
+ self._produce_replay(distinct_id="browser")
+ _create_event(
+ team=self.team,
+ event="purchase_completed",
+ distinct_id="buyer",
+ timestamp=datetime(2025, 1, 15, 10, 1, 0),
+ properties={"$session_id": buyer_session},
+ )
+ flush_persons_and_events()
+
+ with patch(
+ "ee.hogai.tools.replay.filter_session_recordings.has_replay_negative_event_filters_feature_flag",
+ return_value=flag_enabled,
+ ):
+ tool = await self._create_tool()
+ self.assertIs(
+ tool.args_schema,
+ FilterSessionRecordingsWithEventNegationToolArgs if flag_enabled else FilterSessionRecordingsToolArgs,
+ )
+ filters = self._event_filters("purchase_completed", negation=True)
+
+ if flag_enabled:
+ result_text, _ = await tool._arun_impl(recordings_filters=filters)
+ self.assertIn("Found 1 recording", result_text)
+ self.assertIn("User: browser", result_text)
+ else:
+ with self.assertRaises(MaxToolRetryableError):
+ await tool._arun_impl(recordings_filters=filters)
+
async def test_returns_single_recording_with_metadata(self):
base_time = datetime(2025, 1, 15, 10, 0, 0)
self._produce_replay(
diff --git a/ee/hogai/utils/feature_flags.py b/ee/hogai/utils/feature_flags.py
index 7cacbac50f70..a6fff10d6a6e 100644
--- a/ee/hogai/utils/feature_flags.py
+++ b/ee/hogai/utils/feature_flags.py
@@ -125,6 +125,16 @@ def has_conversation_task_mirror_feature_flag(team: Team, user: User) -> bool:
)
+def has_replay_negative_event_filters_feature_flag(team: Team, user: User) -> bool:
+ return feature_enabled_or_false(
+ "replay-negative-event-filters",
+ str(user.distinct_id),
+ groups={"organization": str(team.organization_id)},
+ group_properties={"organization": {"id": str(team.organization_id)}},
+ send_feature_flag_events=False,
+ )
+
+
def has_customer_analytics_mode_feature_flag(team: Team, user: User) -> bool:
return feature_enabled_or_false(
"customer-analytics-csp",
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 913fffbce04b..2d23deff1696 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -39297,6 +39297,10 @@
"description": "Optional display name for this event.",
"type": "string"
},
+ "negation": {
+ "description": "Set to true to match sessions that did NOT contain this event. Only set it when the tool description says excluding sessions by event is supported.",
+ "type": "boolean"
+ },
"properties": {
"description": "Optional property filters for this event only.",
"items": {
diff --git a/frontend/src/queries/schema/schema-assistant-replay.ts b/frontend/src/queries/schema/schema-assistant-replay.ts
index f0c566d03a45..7e9be45ce68f 100644
--- a/frontend/src/queries/schema/schema-assistant-replay.ts
+++ b/frontend/src/queries/schema/schema-assistant-replay.ts
@@ -54,6 +54,8 @@ export interface MaxRecordingEventFilter {
name?: string
/** Optional property filters for this event only. */
properties?: AssistantPropertyFilter[]
+ /** Set to true to match sessions that did NOT contain this event. Only set it when the tool description says excluding sessions by event is supported. */
+ negation?: boolean
}
export type MaxUniversalFilterValue =
diff --git a/posthog/schema.py b/posthog/schema.py
index 7b38ea33f82e..f30ca3bc16c9 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -6922,6 +6922,13 @@ class MaxRecordingEventFilter(BaseModel):
)
id: str = Field(..., description="Name of the event.")
name: str | None = Field(default=None, description="Optional display name for this event.")
+ negation: bool | None = Field(
+ default=None,
+ description=(
+ "Set to true to match sessions that did NOT contain this event. Only set it"
+ " when the tool description says excluding sessions by event is supported."
+ ),
+ )
properties: (
list[
AssistantCohortPropertyFilter
diff --git a/products/replay/backend/prompts.py b/products/replay/backend/prompts.py
index 3e4f809a8784..45ae3ff9173e 100644
--- a/products/replay/backend/prompts.py
+++ b/products/replay/backend/prompts.py
@@ -335,3 +335,21 @@ Valid element property keys: `tag_name` (HTML tag), `text` (visible text on the
{"date_from":"-3d","date_to":null,"duration":[],"filter_group":{"type":"AND","values":[{"type":"OR","values":[{"key":"$device_type","type":"session","operator":"exact","value":["Mobile"]},{"key":"$device_type","type":"session","operator":"exact","value":["Tablet"]}]},{"type":"OR","values":[{"key":"$geoip_country_code","type":"person","operator":"exact","value":["US"]},{"key":"$geoip_country_code","type":"person","operator":"exact","value":["UK"]}]}]},"filter_test_accounts":true}
</filter_examples>
""".strip()
+
+EVENT_NEGATION_SUPPORTED_PROMPT = """
+# Excluding Sessions by Event
+To find sessions where an event did NOT happen, add an `events` filter with `"negation": true`.
+Combine it with AND, because a session must match every negated event and every positive filter.
+**Sessions with a checkout but no purchase**:
+```json
+{"filter_group":{"type":"AND","values":[{"type":"AND","values":[{"id":"checkout_started","type":"events"},{"id":"purchase_completed","type":"events","negation":true}]}]}}
+```
+""".strip()
+
+EVENT_NEGATION_UNSUPPORTED_PROMPT = """
+# Excluding Sessions by Event
+You cannot exclude sessions by event. Never set `negation` on an `events` filter.
+The user has no "did not perform" or "does not contain" event filter, so never tell them to add one.
+If the user asks for sessions without an event, say that this filter is not available.
+Then offer the closest filter that you can apply, for example the sessions that contain a related event.
+""".strip()