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(aio): apply property access rules to ai events (#104042)

Radu Raicea1b43c5d7016d
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index 936cad1c5726..09fc80907a90 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -355,6 +355,16 @@ procs:
layer: Ingestion pipeline
tech: Rust
+ property-defs-ai:
+ shell: |-
+ bin/wait-for-docker && \
+ KAFKA_CONSUMER_TOPIC=clickhouse_ai_events_json KAFKA_CONSUMER_GROUP=property-defs-ai BIND_PORT=3320 bin/start-rust-service property-defs-rs
+ capability: property_definitions
+ ready_pattern: 'Subscribed to topic: *'
+ groups:
+ layer: Ingestion pipeline
+ tech: Rust
+
property-vals-rs:
shell: |-
bin/wait-for-docker && \
diff --git a/docker-compose.dev-full.yml b/docker-compose.dev-full.yml
index e32fed63fd75..a16515bb282e 100644
--- a/docker-compose.dev-full.yml
+++ b/docker-compose.dev-full.yml
@@ -171,6 +171,16 @@ services:
depends_on:
- kafka
+ property-defs-ai:
+ extends:
+ file: docker-compose.base.yml
+ service: property-defs-rs
+ environment:
+ KAFKA_CONSUMER_TOPIC: clickhouse_ai_events_json
+ KAFKA_CONSUMER_GROUP: property-defs-ai
+ depends_on:
+ - kafka
+
feature-flags:
extends:
file: docker-compose.base.yml
diff --git a/docker-compose.hobby.yml b/docker-compose.hobby.yml
index ee689d73e7b3..83f844fe8822 100644
--- a/docker-compose.hobby.yml
+++ b/docker-compose.hobby.yml
@@ -567,6 +567,22 @@ services:
db:
condition: service_healthy
+ property-defs-ai:
+ build:
+ context: ./posthog/rust
+ extends:
+ file: docker-compose.base.yml
+ service: property-defs-rs
+ logging: *default-logging
+ environment:
+ KAFKA_CONSUMER_TOPIC: clickhouse_ai_events_json
+ KAFKA_CONSUMER_GROUP: property-defs-ai
+ depends_on:
+ kafka-init:
+ condition: service_completed_successfully
+ db:
+ condition: service_healthy
+
livestream:
extends:
file: docker-compose.base.yml
diff --git a/ee/hogai/tools/read_data/test/test_tool.py b/ee/hogai/tools/read_data/test/test_tool.py
index 44c6722703b9..35c6d45c3402 100644
--- a/ee/hogai/tools/read_data/test/test_tool.py
+++ b/ee/hogai/tools/read_data/test/test_tool.py
@@ -21,10 +21,12 @@ from posthog.schema import (
)
from posthog.constants import AvailableFeature
-from posthog.models import OrganizationMembership
+from posthog.models import OrganizationMembership, PropertyDefinition
from posthog.models.scoping import team_scope
from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.access_control.backend.property_access_control import PropertyAccessLevel
from products.ai_observability.backend.summarization.llm.schema import (
InterestingNote,
SummarizationResponse,
@@ -1980,15 +1982,49 @@ class TestReadDataTool(BaseTest):
mock_summarize.assert_not_called()
assert artifact is None
+ @parameterized.expand([("unrestricted", False), ("restricted", True)])
@patch("ee.hogai.tools.read_data.tool.django_cache")
@patch("ee.hogai.tools.read_data.tool.summarize")
@patch("ee.hogai.tools.read_data.tool.format_trace_text_repr", return_value=("x" * 6000, False))
@patch("ee.hogai.tools.read_data.tool.llm_trace_to_formatter_format", return_value=({}, []))
@patch("ee.hogai.context.insight.query_executor.AssistantQueryExecutor.aexecute_query", new_callable=AsyncMock)
async def test_read_llm_trace_calls_summarize_on_cache_miss(
- self, mock_execute, mock_to_formatter, mock_format_repr, mock_summarize, mock_cache
- ):
- mock_cache.get.return_value = None
+ self,
+ _name: str,
+ restricted: bool,
+ mock_execute: AsyncMock,
+ mock_to_formatter: MagicMock,
+ mock_format_repr: MagicMock,
+ mock_summarize: MagicMock,
+ mock_cache: MagicMock,
+ ) -> None:
+ if restricted:
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ await self.organization.asave()
+ self.team.organization = self.organization
+ property_definition = await PropertyDefinition.objects.acreate(
+ team=self.team, name="$ai_input", type=PropertyDefinition.Type.EVENT
+ )
+ await PropertyAccessControl.objects.acreate(
+ team=self.team,
+ property_definition=property_definition,
+ organization_member=await OrganizationMembership.objects.aget(
+ organization=self.organization, user=self.user
+ ),
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+
+ unrestricted_key = f"llm_summary:{self.team.id}:trace:trace-1:minimal:default"
+ unrestricted_summary = _make_summary().model_copy(update={"title": "Unrestricted input summary"})
+ cache_entries = (
+ {unrestricted_key: {"summary": unrestricted_summary.model_dump(), "text_repr": "unrestricted input"}}
+ if restricted
+ else {}
+ )
+ mock_cache.get.side_effect = cache_entries.get
+ mock_cache.set.side_effect = lambda key, value, timeout: cache_entries.update({key: value})
summary = _make_summary()
mock_summarize.return_value = summary
mock_execute.return_value = {"results": [_make_trace_data()]}
@@ -2004,13 +2040,21 @@ class TestReadDataTool(BaseTest):
result, _ = await tool._arun_impl({"kind": "llm_trace", "trace_id": "trace-1"})
assert "Test Summary Title" in result
+ assert "Unrestricted input summary" not in result
mock_summarize.assert_called_once()
mock_cache.set.assert_called_once()
cache_key, cache_value, timeout = mock_cache.set.call_args[0]
- assert cache_key == f"llm_summary:{self.team.id}:trace:trace-1:minimal:default"
+ assert (cache_key != unrestricted_key) is restricted
assert cache_value["summary"] == summary.model_dump()
assert timeout == 3600
+ cached_result, _ = await tool._arun_impl({"kind": "llm_trace", "trace_id": "trace-1"})
+
+ assert cached_result == result
+ mock_summarize.assert_called_once()
+ if restricted:
+ assert cache_entries[unrestricted_key]["summary"] == unrestricted_summary.model_dump()
+
@patch("ee.hogai.context.insight.query_executor.AssistantQueryExecutor.aexecute_query", new_callable=AsyncMock)
async def test_read_llm_trace_not_found(self, mock_execute):
mock_execute.return_value = {"results": []}
diff --git a/ee/hogai/tools/read_data/tool.py b/ee/hogai/tools/read_data/tool.py
index 39f41f26bd72..0bd8bc7e2266 100644
--- a/ee/hogai/tools/read_data/tool.py
+++ b/ee/hogai/tools/read_data/tool.py
@@ -29,6 +29,9 @@ from posthog.hogql.database.schema.table_descriptions import TableDescriptions
from posthog.models import Team, User
from posthog.sync import database_sync_to_async
+from products.access_control.backend.property_access_control import (
+ get_restricted_properties_with_group_type_index_for_team,
+)
from products.ai_observability.backend.summarization.budget import text_repr_budget
from products.ai_observability.backend.summarization.llm.call import summarize
from products.ai_observability.backend.summarization.llm.schema import SummarizationResponse
@@ -950,7 +953,10 @@ class ReadDataTool(HogQLDatabaseMixin, MaxTool):
if len(text_repr) <= self.TRACE_SUMMARIZATION_THRESHOLD:
return text_repr
- cache_key = get_summary_cache_key(self._team.id, "trace", trace_id)
+ restricted_properties = await database_sync_to_async(get_restricted_properties_with_group_type_index_for_team)(
+ user=self._user, team=self._team
+ )
+ cache_key = get_summary_cache_key(self._team.id, "trace", trace_id, restricted_properties=restricted_properties)
cached_result = await database_sync_to_async(django_cache.get)(cache_key)
if cached_result is not None:
summary = SummarizationResponse.model_validate(cached_result["summary"])
diff --git a/posthog/hogql/ACCESS_CONTROL.md b/posthog/hogql/ACCESS_CONTROL.md
index cd9cc5d89069..cd3730d615b6 100644
--- a/posthog/hogql/ACCESS_CONTROL.md
+++ b/posthog/hogql/ACCESS_CONTROL.md
@@ -208,7 +208,8 @@ It restricts one distinctly named key per property class, walks the catalog, and
The expected mapping is written out in the test rather than derived from `RESTRICTABLE_JSON_BLOB_COLUMNS`, so it holds the invariant in both directions: a table added to the catalog without a branch arrives masking nothing, and a column dropped from that set leaves its blob out of the walk entirely.
Because each class restricts its own key, a table dispatched as the wrong class, or a group blob dispatched to the wrong group index, comes back carrying another class's key instead of passing on a non-empty result.
-The exemptions are not a statement of full coverage: `accounts.properties` and `pg_embeddings.properties` are name collisions masked nowhere by design, and `ai_events.properties` carries event properties but has no branch yet, so its blob is still returned unmasked.
+The exemptions are name collisions: `accounts.properties` and `pg_embeddings.properties` do not contain event, person, or group properties.
+`ai_events.properties` uses the same event-property rules as `events.properties`.
Covering a table means moving it out of the exemptions and into the expected mapping, so neither list can keep a stale entry.
### Typed columns that mirror a property
@@ -217,7 +218,11 @@ Masking rewrites `properties.<key>` reads and strips keys from a JSON blob. It d
Several catalog tables expose such columns because reading them scans far less data than digging the value out of the blob: `events` exposes `$session_id`, `$window_id`, and `$group_0`..`$group_4`; `flag_evaluations` exposes `flag_key`, `response`, `session_id`, `request_id`, and `$group_0`..`$group_4`.
`events`' mirror columns are not masked: restricting the property they mirror masks the blob read and leaves the column readable.
-`flag_evaluations`' mirror columns are masked, through `_FLAG_EVALUATIONS_MIRRORED_COLUMNS` in `posthog/hogql/restricted_properties.py`, consulted via `mirrored_property_for_column()` from `ClickHousePropertyResolver.visit_field` in `posthog/hogql/transforms/clickhouse_property_resolution.py`.
+`flag_evaluations` and `ai_events` mirror columns are masked through `mirrored_property_for_column()` in `posthog/hogql/restricted_properties.py`, consulted by `ClickHousePropertyResolver` in `posthog/hogql/transforms/clickhouse_property_resolution.py`.
+For AI columns, `AI_PROPERTY_TO_COLUMN` in `posthog/hogql/database/schema/ai_events.py` is shared with the query rewriter.
+One rule for `$ai_input` masks both `events.properties.$ai_input` and `ai_events.input`, including nested reads such as `input[1].content`.
+The same rule applies when a filter or an aggregate reads the column.
+Nested keys in an allowed AI payload are not separate event properties: a restriction on the event property `content` does not restrict `input.content`.
That resolver rewrites a restricted mirror column to the same `Constant(value=None, type=StringType(nullable=True))` the source property lowers to, before the AST reaches the printer — so the mirror column and its source property are one AST node by the time comparisons and nullability are decided, not two independently masked spellings that could drift apart.
Covering `events`' remaining mirror columns, or a future catalog table's, means adding it to `_FLAG_EVALUATIONS_MIRRORED_COLUMNS`'s sibling mapping (or a new one `mirrored_property_for_column` dispatches to) rather than a print-time patch.
@@ -226,14 +231,33 @@ Covering `events`' remaining mirror columns, or a future catalog table's, means
When no user is present, only the team **default** rules apply instead of failing every query — see `get_restricted_properties_for_team()`.
There is the asymmetry with the warehouse access control, which bypasses entirely for shared links rather than applying a default; that may be aligned later.
+### AI previews and summaries
+
+AI evaluation and tagger previews read event properties with the requesting user's permissions, including properties available to Hog scripts.
+Background trace and session evaluations skip with `property_access_restricted` when project-default rules deny any event property.
+They skip before reading content or running a Hog or LLM judge, because grading masked data can change the verdict.
+Hog scripts can read arbitrary event properties, so this check covers all event-property denials, not only input and output.
+Person/group restrictions and member-only rules do not trigger this skip.
+Generation evaluations keep using the original Kafka event payload.
+
+Summary caches use the caller's current property restrictions, including cached titles and summaries read by PostHog AI.
+When the caller has event-property restrictions, summaries generated from client-supplied data refetch the source with the caller's permissions.
+For client-supplied events, omitted lookup dates use a window from one day before to one day after the event's `timestamp`.
+Explicit `date_from` and `date_to` values take precedence; events without a valid timestamp keep the default lookup dates.
+A refetch that finds no matching event or trace returns 404 without generating a summary from the supplied data.
+
## Query cache partitioning
+`products.access_control.backend.facade.property_access` defines the shared restriction ordering and fingerprint.
+Query, experiment-session, and summary caches use that ordering while preserving their existing serialized keys.
+
**The critical invariant:** if a query reads access-controlled tables, its cache key must include the user's restrictions.
Otherwise a denied user gets served an allowed user's cached rows.
The cache key is derived from `get_cache_payload()`:
-- `QueryRunner.get_cache_payload()` adds named property restriction records, including the group type index, when the user has property restrictions.
+- `QueryRunner.get_cache_payload()` adds named property restriction records, including the group type index, and a property-enforcement version when the user has property restrictions.
+ Bump that version when tightening enforcement so a cached result cannot bypass the new masking rules.
- `AnalyticsQueryRunner.get_cache_payload()` adds `restricted_resources` (denied scopes) and `restricted_objects` (denied object IDs per scope) for levels 1 and 2.
Two things keep cache hit rates high:
diff --git a/posthog/hogql/database/schema/ai_events.py b/posthog/hogql/database/schema/ai_events.py
index 90d394197654..991d472e8b98 100644
--- a/posthog/hogql/database/schema/ai_events.py
+++ b/posthog/hogql/database/schema/ai_events.py
@@ -13,6 +13,67 @@ from posthog.hogql.database.models import (
)
from posthog.hogql.database.schema.person_distinct_ids import PersonDistinctIdsTable
+# Mapping from AI property names to their dedicated ai_events column names.
+# Properties not in this mapping remain as JSONExtract on the `properties` column.
+AI_PROPERTY_TO_COLUMN: dict[str, str] = {
+ # Trace structure
+ "$ai_trace_id": "trace_id",
+ "$ai_session_id": "session_id",
+ "$ai_parent_id": "parent_id",
+ "$ai_span_id": "span_id",
+ "$ai_span_type": "span_type",
+ "$ai_generation_id": "generation_id",
+ "$ai_experiment_id": "experiment_id",
+ # Names
+ "$ai_span_name": "span_name",
+ "$ai_trace_name": "trace_name",
+ "$ai_prompt_name": "prompt_name",
+ # Model info
+ "$ai_model": "model",
+ "$ai_provider": "provider",
+ "$ai_framework": "framework",
+ # Token counts
+ "$ai_total_tokens": "total_tokens",
+ "$ai_input_tokens": "input_tokens",
+ "$ai_output_tokens": "output_tokens",
+ "$ai_text_input_tokens": "text_input_tokens",
+ "$ai_text_output_tokens": "text_output_tokens",
+ "$ai_image_input_tokens": "image_input_tokens",
+ "$ai_image_output_tokens": "image_output_tokens",
+ "$ai_audio_input_tokens": "audio_input_tokens",
+ "$ai_audio_output_tokens": "audio_output_tokens",
+ "$ai_video_input_tokens": "video_input_tokens",
+ "$ai_video_output_tokens": "video_output_tokens",
+ "$ai_reasoning_tokens": "reasoning_tokens",
+ "$ai_cache_read_input_tokens": "cache_read_input_tokens",
+ "$ai_cache_creation_input_tokens": "cache_creation_input_tokens",
+ "$ai_web_search_count": "web_search_count",
+ # Costs
+ "$ai_input_cost_usd": "input_cost_usd",
+ "$ai_output_cost_usd": "output_cost_usd",
+ "$ai_total_cost_usd": "total_cost_usd",
+ "$ai_request_cost_usd": "request_cost_usd",
+ "$ai_web_search_cost_usd": "web_search_cost_usd",
+ "$ai_audio_cost_usd": "audio_cost_usd",
+ "$ai_image_cost_usd": "image_cost_usd",
+ "$ai_video_cost_usd": "video_cost_usd",
+ # Timing
+ "$ai_latency": "latency",
+ "$ai_time_to_first_token": "time_to_first_token",
+ # Errors
+ "$ai_is_error": "is_error",
+ "$ai_error": "error",
+ "$ai_error_type": "error_type",
+ "$ai_error_normalized": "error_normalized",
+ # Heavy columns
+ "$ai_input": "input",
+ "$ai_output": "output",
+ "$ai_output_choices": "output_choices",
+ "$ai_input_state": "input_state",
+ "$ai_output_state": "output_state",
+ "$ai_tools": "tools",
+}
+
class AiEventsTable(Table):
description: str = "AI observability events ($ai_generation, $ai_span, $ai_trace, $ai_evaluation, etc.) capturing model calls, token usage, costs, and trace structure."
diff --git a/posthog/hogql/printer/test/test_property_access_control.py b/posthog/hogql/printer/test/test_property_access_control.py
index 22f832540279..2998bf1dc54c 100644
--- a/posthog/hogql/printer/test/test_property_access_control.py
+++ b/posthog/hogql/printer/test/test_property_access_control.py
@@ -80,7 +80,8 @@ class TestRestrictPropertiesInHogQL(BaseTest):
sql = self._compile_select("SELECT properties.secret_field FROM events")
assert "secret_field" in sql
- def test_denied_event_property_is_stripped_silently(self):
+ @parameterized.expand([("events",), ("posthog.ai_events",)])
+ def test_denied_event_property_is_stripped_silently(self, table_name: str) -> None:
# A restricted property reads as NULL rather than raising. Explicit access (``properties.secret_field``)
# compiles to a constant NULL — the value is never extracted from the blob, and the key never appears, inline
# or as a parameter.
@@ -89,7 +90,7 @@ class TestRestrictPropertiesInHogQL(BaseTest):
property_definition=self.event_prop,
access_level=PropertyAccessLevel.NONE.value,
)
- sql, values = self._compile_select_with_values("SELECT properties.secret_field FROM events")
+ sql, values = self._compile_select_with_values(f"SELECT properties.secret_field FROM {table_name}")
assert "NULL AS secret_field" in sql
assert "JSONExtract" not in sql # the restricted value is never read from the blob
assert "JSONDropKeys" not in sql # no redundant drop-then-extract
@@ -258,23 +259,33 @@ class TestRestrictPropertiesInHogQL(BaseTest):
@parameterized.expand(
[
- ("events_properties", "SELECT properties FROM events", PropertyDefinition.Type.EVENT, "secret_field"),
- ("events_star", "SELECT * FROM events", PropertyDefinition.Type.EVENT, "secret_field"),
+ ("events_properties", "SELECT properties FROM events", PropertyDefinition.Type.EVENT, "secret_field", None),
+ ("events_star", "SELECT * FROM events", PropertyDefinition.Type.EVENT, "secret_field", None),
+ (
+ "ai_properties",
+ "SELECT properties FROM posthog.ai_events",
+ PropertyDefinition.Type.EVENT,
+ "secret_field",
+ None,
+ ),
+ ("ai_star", "SELECT * FROM posthog.ai_events", PropertyDefinition.Type.EVENT, "$ai_input", "input"),
(
"events_person_properties",
"SELECT person.properties FROM events",
PropertyDefinition.Type.PERSON,
"secret_person_field",
+ None,
),
]
)
def test_restricted_properties_blob_uses_json_drop_keys(
self,
- _case_name: str,
+ _name: str,
query: str,
property_type: int,
restricted_key: str,
- ):
+ masked_column: str | None,
+ ) -> None:
property_definition = self.event_prop
if property_type == PropertyDefinition.Type.PERSON:
property_definition = PropertyDefinition.objects.create(
@@ -283,6 +294,9 @@ class TestRestrictPropertiesInHogQL(BaseTest):
property_type="String",
type=PropertyDefinition.Type.PERSON,
)
+ elif property_definition.name != restricted_key:
+ property_definition.name = restricted_key
+ property_definition.save()
PropertyAccessControl.objects.create(
team=self.team,
@@ -293,6 +307,50 @@ class TestRestrictPropertiesInHogQL(BaseTest):
assert "JSONDropKeys" in sql
assert restricted_key not in sql
self._assert_value_present(values, restricted_key)
+ if masked_column is not None:
+ assert f"NULL AS {masked_column}" in sql
+
+ @parameterized.expand(
+ [
+ ("input", "$ai_input", "a.input"),
+ ("nested_input", "$ai_input", "a.input[1].content"),
+ ("output_choices", "$ai_output_choices", "a.output_choices"),
+ ("model", "$ai_model", "a.model"),
+ ("tokens", "$ai_input_tokens", "a.input_tokens"),
+ ("cost", "$ai_total_cost_usd", "a.total_cost_usd"),
+ ("error", "$ai_is_error", "a.is_error"),
+ ]
+ )
+ def test_ai_column_and_nested_reads_use_the_canonical_property_rule(
+ self, _name: str, property_name: str, expression: str
+ ) -> None:
+ self.event_prop.name = property_name
+ self.event_prop.save()
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.event_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+
+ sql = self._compile_select(
+ f"SELECT {expression} AS restricted_value FROM posthog.ai_events AS a WHERE {expression} IS NULL"
+ )
+
+ assert "NULL AS restricted_value" in sql
+ assert "JSONExtract" not in sql
+ assert expression.split("[")[0] not in sql
+
+ def test_ai_json_content_is_not_an_event_property(self) -> None:
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=self.event_prop,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+
+ sql = self._compile_select("SELECT input.secret_field FROM posthog.ai_events")
+
+ assert "JSONExtract" in sql
+ assert "NULL AS secret_field" not in sql
def test_properties_blob_no_wrapping_without_restrictions(self):
sql = self._compile_select("SELECT properties FROM events")
diff --git a/posthog/hogql/restricted_properties.py b/posthog/hogql/restricted_properties.py
index 900976187dc6..550b0cc6f9b3 100644
--- a/posthog/hogql/restricted_properties.py
+++ b/posthog/hogql/restricted_properties.py
@@ -3,6 +3,7 @@ import structlog
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.postgres_table import PostgresTable
+from posthog.hogql.database.schema.ai_events import AI_PROPERTY_TO_COLUMN, AiEventsTable
from posthog.hogql.database.schema.events import EventsGroupSubTable, EventsPersonSubTable, EventsTable
from posthog.hogql.database.schema.flag_evaluations import FlagEvaluationsTable
from posthog.hogql.database.schema.groups import GroupsTable, RawGroupsTable
@@ -39,6 +40,9 @@ _FLAG_EVALUATIONS_MIRRORED_COLUMNS: dict[str, str] = {
}
+_AI_EVENTS_MIRRORED_COLUMNS = {column: property_name for property_name, column in AI_PROPERTY_TO_COLUMN.items()}
+
+
def mirrored_property_for_column(table_type: ast.Type, column_name: str, context: HogQLContext) -> str | None:
"""The event property a typed column copies verbatim, or None when the column copies nothing.
@@ -57,6 +61,8 @@ def mirrored_property_for_column(table_type: ast.Type, column_name: str, context
logger.warning("mirrored_property_table_resolution_failed", table_type=type(table_type).__name__)
return None
+ if isinstance(table, AiEventsTable):
+ return _AI_EVENTS_MIRRORED_COLUMNS.get(column_name)
if isinstance(table, FlagEvaluationsTable):
return _FLAG_EVALUATIONS_MIRRORED_COLUMNS.get(column_name)
return None
@@ -98,7 +104,7 @@ def restricted_property_keys_for_table_type(
elif isinstance(table, EventsGroupSubTable):
prop_def_type = PropertyDefinition.Type.GROUP
group_type_index = table.group_index
- elif isinstance(table, EventsTable | FlagEvaluationsTable):
+ elif isinstance(table, EventsTable | FlagEvaluationsTable | AiEventsTable):
prop_def_type = PropertyDefinition.Type.EVENT
elif isinstance(table, (PersonsTable, RawPersonsTable)):
prop_def_type = PropertyDefinition.Type.PERSON
diff --git a/posthog/hogql/test/test_restricted_properties.py b/posthog/hogql/test/test_restricted_properties.py
index 6aeea11697fe..dfd206bd8bd3 100644
--- a/posthog/hogql/test/test_restricted_properties.py
+++ b/posthog/hogql/test/test_restricted_properties.py
@@ -27,6 +27,7 @@ _GROUP_KEYS = tuple(f"restricted_group_{index}_property" for index in range(GROU
# quietly shrinking the walk below.
_MASKED_BLOBS: dict[str, frozenset[str]] = {
"events.properties (EventsTable)": frozenset({_EVENT_KEY}),
+ "ai_events.properties (AiEventsTable)": frozenset({_EVENT_KEY}),
"events.person_properties (EventsPersonSubTable)": frozenset({_PERSON_KEY}),
**{
f"events.group{index}_properties (EventsGroupSubTable)": frozenset({_GROUP_KEYS[index]})
@@ -54,9 +55,6 @@ _UNMASKED_BLOBS: frozenset[str] = frozenset(
"accounts.properties (PostgresTable)",
# Metadata attached to an embedded item.
"pg_embeddings.properties (PgEmbeddingsTable)",
- # Carries event properties, so unlike the two above this one is owed a branch. Tracked with
- # team-ai-observability, who own the table.
- "ai_events.properties (AiEventsTable)",
}
)
diff --git a/posthog/hogql/transforms/clickhouse_property_resolution.py b/posthog/hogql/transforms/clickhouse_property_resolution.py
index 3d258e658ab0..4eebe261d487 100644
--- a/posthog/hogql/transforms/clickhouse_property_resolution.py
+++ b/posthog/hogql/transforms/clickhouse_property_resolution.py
@@ -515,6 +515,13 @@ def _map_value_read(blob: ast.Expr, key: str) -> ast.Expr:
)
+def _mirrored_source_property(field_type: ast.FieldType, context: HogQLContext) -> str | None:
+ resolved_field = field_type.resolve_database_field(context)
+ if not isinstance(resolved_field, DatabaseField):
+ return None
+ return mirrored_property_for_column(field_type.table_type, resolved_field.name, context)
+
+
def _substitute_value_read(node: ast.PropertyAccess, context: HogQLContext) -> ast.Expr | None:
"""The backing-column read for a `PropertyAccess`, or None to leave it as the JSON extract.
@@ -534,7 +541,8 @@ def _substitute_value_read(node: ast.PropertyAccess, context: HogQLContext) -> a
# JSONDropKeys strips the key, so extracting it always yields '' which scrubs to NULL — so return that constant
# directly and skip the wasted drop-then-extract. (The column resolvers also decline, so comparisons over a
# restricted property never read the backing column either; their operand falls through to this same NULL.)
- if first_key in restricted_property_keys_for_table_type(field_type.table_type, context):
+ source_property = _mirrored_source_property(field_type, context)
+ if (source_property or first_key) in restricted_property_keys_for_table_type(field_type.table_type, context):
_record_property_usage(context, None)
return ast.Constant(value=None, type=ast.StringType(nullable=True))
@@ -896,10 +904,7 @@ class ClickHousePropertyResolver(CloningVisitor):
Must match what `_substitute_value_read` builds for the source property, so the mirror column and
its source property become the same AST node and agree on nullability and comparison printing.
"""
- resolved_field = field_type.resolve_database_field(self.context)
- if not isinstance(resolved_field, DatabaseField):
- return None
- source_property = mirrored_property_for_column(field_type.table_type, resolved_field.name, self.context)
+ source_property = _mirrored_source_property(field_type, self.context)
if source_property is None:
return None
if source_property not in restricted_property_keys_for_table_type(field_type.table_type, self.context):
diff --git a/posthog/hogql_queries/ai/ai_property_rewriter.py b/posthog/hogql_queries/ai/ai_property_rewriter.py
index de052d4f15fc..91b1c1089e78 100644
--- a/posthog/hogql_queries/ai/ai_property_rewriter.py
+++ b/posthog/hogql_queries/ai/ai_property_rewriter.py
@@ -5,69 +5,9 @@ Follows the `ExprTransformer` / `CloningVisitor` pattern from
"""
from posthog.hogql import ast
+from posthog.hogql.database.schema.ai_events import AI_PROPERTY_TO_COLUMN
from posthog.hogql.visitor import CloningVisitor
-# Mapping from AI property names to their dedicated ai_events column names.
-# Properties not in this mapping remain as JSONExtract on the `properties` column.
-AI_PROPERTY_TO_COLUMN: dict[str, str] = {
- # Trace structure
- "$ai_trace_id": "trace_id",
- "$ai_session_id": "session_id",
- "$ai_parent_id": "parent_id",
- "$ai_span_id": "span_id",
- "$ai_span_type": "span_type",
- "$ai_generation_id": "generation_id",
- "$ai_experiment_id": "experiment_id",
- # Names
- "$ai_span_name": "span_name",
- "$ai_trace_name": "trace_name",
- "$ai_prompt_name": "prompt_name",
- # Model info
- "$ai_model": "model",
- "$ai_provider": "provider",
- "$ai_framework": "framework",
- # Token counts
- "$ai_total_tokens": "total_tokens",
- "$ai_input_tokens": "input_tokens",
- "$ai_output_tokens": "output_tokens",
- "$ai_text_input_tokens": "text_input_tokens",
- "$ai_text_output_tokens": "text_output_tokens",
- "$ai_image_input_tokens": "image_input_tokens",
- "$ai_image_output_tokens": "image_output_tokens",
- "$ai_audio_input_tokens": "audio_input_tokens",
- "$ai_audio_output_tokens": "audio_output_tokens",
- "$ai_video_input_tokens": "video_input_tokens",
- "$ai_video_output_tokens": "video_output_tokens",
- "$ai_reasoning_tokens": "reasoning_tokens",
- "$ai_cache_read_input_tokens": "cache_read_input_tokens",
- "$ai_cache_creation_input_tokens": "cache_creation_input_tokens",
- "$ai_web_search_count": "web_search_count",
- # Costs
- "$ai_input_cost_usd": "input_cost_usd",
- "$ai_output_cost_usd": "output_cost_usd",
- "$ai_total_cost_usd": "total_cost_usd",
- "$ai_request_cost_usd": "request_cost_usd",
- "$ai_web_search_cost_usd": "web_search_cost_usd",
- "$ai_audio_cost_usd": "audio_cost_usd",
- "$ai_image_cost_usd": "image_cost_usd",
- "$ai_video_cost_usd": "video_cost_usd",
- # Timing
- "$ai_latency": "latency",
- "$ai_time_to_first_token": "time_to_first_token",
- # Errors
- "$ai_is_error": "is_error",
- "$ai_error": "error",
- "$ai_error_type": "error_type",
- "$ai_error_normalized": "error_normalized",
- # Heavy columns
- "$ai_input": "input",
- "$ai_output": "output",
- "$ai_output_choices": "output_choices",
- "$ai_input_state": "input_state",
- "$ai_output_state": "output_state",
- "$ai_tools": "tools",
-}
-
_BOOLEAN_PROPERTIES: frozenset[str] = frozenset({"$ai_is_error"})
# Values that map to UInt8 1 (truthy) for boolean AI property columns
diff --git a/posthog/hogql_queries/ai/ai_table_resolver.py b/posthog/hogql_queries/ai/ai_table_resolver.py
index fd8e909d788d..bab46c0320d2 100644
--- a/posthog/hogql_queries/ai/ai_table_resolver.py
+++ b/posthog/hogql_queries/ai/ai_table_resolver.py
@@ -37,7 +37,7 @@ if TYPE_CHECKING:
from posthog.hogql.timings import HogQLTimings
from posthog.clickhouse.client.connection import Workload
- from posthog.models import Team
+ from posthog.models import Team, User
class AIEventsUnavailableError(Exception):
@@ -75,6 +75,7 @@ def query_ai_events(
team: Team,
query_type: str,
*,
+ user: User | None = None,
fall_back_to_events: bool = False,
fallback_placeholders: dict[str, ast.Expr] | None = None,
timings: HogQLTimings | None = None,
@@ -102,13 +103,16 @@ def query_ai_events(
``fallback_placeholders`` lets callers keep predicates required by shared events out of
the dedicated table query. They use the ai_events schema and are rewritten before execution.
+ Pass the requesting ``user`` for interactive reads so member and role property rules
+ apply on every read path. Userless background reads apply the project's default rules.
+
`workload` should be specified explicitly for batch / scheduled callers (e.g. usage
reports). Inside a Celery task the `task_prerun` signal sets `Workload.OFFLINE` on
the thread default, but outside Celery (Django shell, pytest, management commands)
that signal does not fire — so callers that must run on a specific pool should not
rely on it implicitly.
"""
- kwargs: dict[str, Any] = {"query_type": query_type, "team": team}
+ kwargs: dict[str, Any] = {"query_type": query_type, "team": team, "user": user}
if timings is not None:
kwargs["timings"] = timings
if modifiers is not None:
@@ -139,6 +143,7 @@ def query_ai_events(
**kwargs,
"context": HogQLContext(
team_id=team.pk,
+ user=user,
use_new_events_schema=events_schema,
property_type_overrides=EVENTS_FALLBACK_PROPERTY_TYPE_OVERRIDES,
),
diff --git a/posthog/hogql_queries/ai/sentiment_evaluations.py b/posthog/hogql_queries/ai/sentiment_evaluations.py
index 6f070232f55f..5b660ba30112 100644
--- a/posthog/hogql_queries/ai/sentiment_evaluations.py
+++ b/posthog/hogql_queries/ai/sentiment_evaluations.py
@@ -17,7 +17,7 @@ if TYPE_CHECKING:
from posthog.hogql.modifiers import HogQLQueryModifiers
from posthog.hogql.timings import HogQLTimings
- from posthog.models import Team
+ from posthog.models import Team, User
SentimentMessage = dict[str, Any]
@@ -114,6 +114,7 @@ def load_generation_sentiment_evaluations_for_traces(
*,
team: Team,
trace_ids: Sequence[str],
+ user: User | None = None,
generation_ids: Sequence[str] | None = None,
timings: HogQLTimings | None = None,
modifiers: HogQLQueryModifiers | None = None,
@@ -148,6 +149,7 @@ def load_generation_sentiment_evaluations_for_traces(
),
},
team=team,
+ user=user,
query_type=query_type,
fall_back_to_events=True,
timings=timings,
@@ -180,6 +182,7 @@ def load_trace_sentiment_evaluations(
*,
team: Team,
trace_ids: Sequence[str],
+ user: User | None = None,
timings: HogQLTimings | None = None,
modifiers: HogQLQueryModifiers | None = None,
limit_context: LimitContext | None = None,
@@ -197,6 +200,7 @@ def load_trace_sentiment_evaluations(
"limit": ast.Constant(value=len(unique_trace_ids)),
},
team=team,
+ user=user,
query_type=query_type,
fall_back_to_events=True,
timings=timings,
diff --git a/posthog/hogql_queries/ai/session_query_runner.py b/posthog/hogql_queries/ai/session_query_runner.py
index 775b1325e608..1ee969721817 100644
--- a/posthog/hogql_queries/ai/session_query_runner.py
+++ b/posthog/hogql_queries/ai/session_query_runner.py
@@ -136,6 +136,7 @@ class SessionQueryRunner(AnalyticsQueryRunner[SessionQueryResponse]):
if self.query.includeSentiment and results and columns:
sentiment_lookup = load_generation_sentiment_evaluations_for_traces(
team=self.team,
+ user=self.user,
trace_ids=self._trace_ids_from_results(columns, results),
timings=self.timings,
modifiers=self.modifiers,
diff --git a/posthog/hogql_queries/ai/test/test_ai_table_resolver.py b/posthog/hogql_queries/ai/test/test_ai_table_resolver.py
index 570cc257c12f..8f8c278d70ea 100644
--- a/posthog/hogql_queries/ai/test/test_ai_table_resolver.py
+++ b/posthog/hogql_queries/ai/test/test_ai_table_resolver.py
@@ -76,10 +76,12 @@ class TestQueryAiEvents:
mock_execute.side_effect = [ai_result, events_result]
team = Mock(id=1, organization_id="org")
+ user = Mock()
result = query_ai_events(
query=self._make_query(),
placeholders={},
team=team,
+ user=user,
query_type="TestQuery",
fall_back_to_events=True,
)
@@ -87,6 +89,8 @@ class TestQueryAiEvents:
assert result is events_result
assert mock_execute.call_count == 2
assert mock_execute.call_args.kwargs["context"].use_new_events_schema is True
+ assert mock_execute.call_args.kwargs["context"].user is user
+ assert all(call.kwargs["user"] is user for call in mock_execute.call_args_list)
@patch("posthog.hogql_queries.ai.ai_table_resolver.use_new_events_schema", return_value=False)
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
@@ -95,14 +99,18 @@ class TestQueryAiEvents:
mock_execute.side_effect = [self._make_result([]), self._make_result([[1]])]
team = Mock(id=1, organization_id="org")
+ user = Mock()
with pytest.raises(AIEventsExpiredError):
query_ai_events(
query=self._make_query(),
placeholders={},
team=team,
+ user=user,
query_type="TestQuery",
)
assert mock_execute.call_count == 2
+ assert mock_execute.call_args.kwargs["context"].user is user
+ assert all(call.kwargs["user"] is user for call in mock_execute.call_args_list)
@patch("posthog.hogql_queries.ai.ai_table_resolver.use_new_events_schema", return_value=False)
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
@@ -191,6 +199,7 @@ class TestQueryAiEvents:
limit_context = Mock()
settings = Mock()
workload = Mock()
+ user = Mock()
query_ai_events(
query=self._make_query(),
@@ -202,6 +211,7 @@ class TestQueryAiEvents:
limit_context=limit_context,
settings=settings,
workload=workload,
+ user=user,
)
kwargs = mock_execute.call_args.kwargs
@@ -210,6 +220,7 @@ class TestQueryAiEvents:
assert kwargs["limit_context"] is limit_context
assert kwargs["settings"] is settings
assert kwargs["workload"] is workload
+ assert kwargs["user"] is user
@patch("posthog.hogql_queries.ai.ai_table_resolver.execute_hogql_query")
def test_omits_unset_optional_kwargs(self, mock_execute):
@@ -231,3 +242,4 @@ class TestQueryAiEvents:
assert "limit_context" not in kwargs
assert "settings" not in kwargs
assert "workload" not in kwargs
+ assert kwargs["user"] is None
diff --git a/posthog/hogql_queries/ai/test/test_trace_query_runner.py b/posthog/hogql_queries/ai/test/test_trace_query_runner.py
index 11008edb2a37..2875edac9e6a 100644
--- a/posthog/hogql_queries/ai/test/test_trace_query_runner.py
+++ b/posthog/hogql_queries/ai/test/test_trace_query_runner.py
@@ -8,20 +8,35 @@ import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, snapshot_clickhouse_queries
from unittest.mock import patch
+from parameterized import parameterized
+
from posthog.schema import (
+ CachedSessionQueryResponse,
+ CachedTraceQueryResponse,
+ CachedTracesQueryResponse,
DateRange,
EventPropertyFilter,
LLMTrace,
LLMTraceEvent,
PersonPropertyFilter,
PropertyOperator,
+ SessionQuery,
TraceQuery,
+ TracesQuery,
)
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.constants import AvailableFeature
+from posthog.hogql_queries.ai.session_query_runner import SessionQueryRunner
from posthog.hogql_queries.ai.trace_query_runner import TraceQueryRunner
-from posthog.models import PropertyDefinition, Team
+from posthog.hogql_queries.ai.traces_query_runner import TracesQueryRunner
+from posthog.models import PropertyDefinition, Team, User
from posthog.models.ai_events.test_util import bulk_create_ai_events
+from posthog.models.event.util import bulk_create_events
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.access_control.backend.property_access_control import PropertyAccessLevel
from products.event_definitions.backend.models.property_definition import PropertyType
@@ -272,6 +287,166 @@ class TestTraceQueryRunner(ClickhouseTestMixin, BaseTest):
for field, value in expected_event.items():
self.assertEqual(getattr(event, field), value, f"Field {field} does not match")
+ @parameterized.expand(
+ [
+ ("trace", "ai_events"),
+ ("trace", "events"),
+ ("session", "ai_events"),
+ ("session", "events"),
+ ("traces", "events"),
+ ]
+ )
+ @time_machine.travel("2025-01-15T12:00:00Z", tick=False)
+ def test_member_property_denial_survives_reconstruction_and_cache(self, runner_kind: str, table: str) -> None:
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ denied_user = self._create_user("[email protected]")
+ denied_membership = denied_user.organization_memberships.get(organization=self.organization)
+ denied_properties = {
+ "$ai_input",
+ "$ai_input_state",
+ "$ai_output_state",
+ "$ai_tools",
+ "$ai_input_tokens",
+ "$ai_total_cost_usd",
+ "$ai_is_error",
+ "private_note",
+ }
+ for name in denied_properties | {"$ai_sentiment_messages"}:
+ property_definition, _ = PropertyDefinition.objects.get_or_create(
+ team=self.team, name=name, type=PropertyDefinition.Type.EVENT
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=property_definition,
+ organization_member=denied_membership,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+
+ events: list[dict[str, Any]] = [
+ {
+ "event": event_name,
+ "team": self.team,
+ "distinct_id": "person1",
+ "timestamp": datetime(2025, 1, 15, 0, minute, tzinfo=UTC),
+ "properties": {
+ "$ai_trace_id": "restricted-trace",
+ "$ai_generation_id": "restricted-generation",
+ "$ai_session_id": "restricted-session",
+ "$ai_parent_id": "restricted-trace",
+ "$ai_input": [{"role": "user", "content": "Private input"}],
+ "$ai_input_state": {"note": "Private input state"},
+ "$ai_output_state": {"note": "Private output state"},
+ "$ai_tools": [{"name": "private_tool"}],
+ "$ai_output": "Public output",
+ "$ai_input_tokens": 7,
+ "$ai_total_cost_usd": 0.25,
+ "$ai_is_error": True,
+ "private_note": "Private custom property",
+ "public_note": "Public custom property",
+ },
+ }
+ for minute, event_name in enumerate(("$ai_trace", "$ai_generation"))
+ ]
+ events.append(
+ {
+ "event": "$ai_evaluation",
+ "team": self.team,
+ "distinct_id": "person1",
+ "timestamp": datetime(2025, 1, 15, 0, 2, tzinfo=UTC),
+ "properties": {
+ "$ai_trace_id": "restricted-trace",
+ "$ai_evaluation_runtime": "sentiment",
+ "$ai_target_event_id": "restricted-generation",
+ "$ai_sentiment_label": "negative",
+ "$ai_sentiment_score": 0.8,
+ "$ai_sentiment_scores": {"positive": 0.1, "neutral": 0.1, "negative": 0.8},
+ "$ai_sentiment_messages": {"0": {"label": "negative", "score": 0.8}},
+ "$ai_sentiment_message_count": 1,
+ },
+ }
+ )
+ if table == "ai_events":
+ bulk_create_ai_events(events)
+ else:
+ bulk_create_events(events)
+
+ def make_runner(user: User) -> TraceQueryRunner | SessionQueryRunner | TracesQueryRunner:
+ date_range = DateRange(date_from="2025-01-15T00:00:00Z", date_to="2025-01-15T01:00:00Z")
+ if runner_kind == "trace":
+ return TraceQueryRunner(
+ team=self.team,
+ user=user,
+ query=TraceQuery(traceId="restricted-trace", dateRange=date_range, includeSentiment=True),
+ )
+ if runner_kind == "session":
+ return SessionQueryRunner(
+ team=self.team,
+ user=user,
+ query=SessionQuery(sessionId="restricted-session", dateRange=date_range, includeSentiment=True),
+ )
+ return TracesQueryRunner(
+ team=self.team, user=user, query=TracesQuery(dateRange=date_range, includeSentiment=True)
+ )
+
+ allowed_runner = make_runner(self.user)
+ allowed = allowed_runner.run()
+ assert isinstance(allowed, (CachedTraceQueryResponse, CachedSessionQueryResponse, CachedTracesQueryResponse))
+ assert len(allowed.results) == 1
+ allowed_trace = allowed.results[0]
+ assert allowed_trace.inputState == events[0]["properties"]["$ai_input_state"]
+ assert allowed_trace.outputState == events[0]["properties"]["$ai_output_state"]
+ assert allowed_trace.events
+ for event in allowed_trace.events:
+ for property_name in denied_properties:
+ assert event.properties[property_name] == events[0]["properties"][property_name]
+ assert allowed_trace.sentiment is not None
+ assert allowed_trace.sentiment.messages
+ if runner_kind != "traces":
+ generation = next(event for event in allowed_trace.events if event.event == "$ai_generation")
+ assert generation.sentiment is not None
+ assert generation.sentiment.messages
+
+ denied_runner = make_runner(denied_user)
+ assert denied_runner.get_cache_key() != allowed_runner.get_cache_key()
+ for index, response in enumerate((denied_runner.run(), make_runner(denied_user).run())):
+ assert isinstance(
+ response, (CachedTraceQueryResponse, CachedSessionQueryResponse, CachedTracesQueryResponse)
+ )
+ assert len(response.results) == 1
+ trace = response.results[0]
+ assert trace.inputState is None
+ assert trace.outputState is None
+ assert trace.sentiment is not None
+ assert not trace.sentiment.messages
+ assert trace.events
+ for event in trace.events:
+ if event.sentiment is not None:
+ assert not event.sentiment.messages
+ assert denied_properties.isdisjoint(event.properties)
+ assert event.properties["$ai_output"] == "Public output"
+ assert event.properties["public_note"] == "Public custom property"
+ if index == 1:
+ assert response.is_cached
+
+ if table == "ai_events":
+ aggregates = execute_hogql_query(
+ query="""
+ SELECT sum(input_tokens), sum(total_cost_usd), countIf(is_error),
+ countIf(input_tokens > 0), countIf(total_cost_usd > 0)
+ FROM posthog.ai_events
+ """,
+ team=self.team,
+ user=denied_user,
+ )
+ assert len(aggregates.results) == 1
+ tokens, cost, errors, positive_tokens, positive_cost = aggregates.results[0]
+ assert tokens in (None, 0)
+ assert cost in (None, 0)
+ assert (errors, positive_tokens, positive_cost) == (0, 0, 0)
+
def test_field_mapping(self):
"""Test that field mapping works correctly for a single trace."""
_create_person(distinct_ids=["person1"], team=self.team)
diff --git a/posthog/hogql_queries/ai/trace_neighbors_query_runner.py b/posthog/hogql_queries/ai/trace_neighbors_query_runner.py
index 84cc28dd32dd..38e2ac99dcc0 100644
--- a/posthog/hogql_queries/ai/trace_neighbors_query_runner.py
+++ b/posthog/hogql_queries/ai/trace_neighbors_query_runner.py
@@ -33,6 +33,7 @@ class TraceNeighborsQueryRunner(AnalyticsQueryRunner[TraceNeighborsQueryResponse
query=self._build_query(),
placeholders=self._get_placeholders(),
team=self.team,
+ user=self.user,
query_type="TraceNeighborsQuery",
fall_back_to_events=True,
timings=self.timings,
diff --git a/posthog/hogql_queries/ai/trace_query_runner.py b/posthog/hogql_queries/ai/trace_query_runner.py
index ef983d3e3d3f..754026fa3f31 100644
--- a/posthog/hogql_queries/ai/trace_query_runner.py
+++ b/posthog/hogql_queries/ai/trace_query_runner.py
@@ -107,6 +107,7 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):
query=self._build_query(),
placeholders={"filter_conditions": self._get_where_clause(include_timestamp_bounds=False)},
team=self.team,
+ user=self.user,
query_type=NodeKind.TRACE_QUERY,
fall_back_to_events=True,
fallback_placeholders={"filter_conditions": self._get_where_clause()},
@@ -120,6 +121,7 @@ class TraceQueryRunner(AnalyticsQueryRunner[TraceQueryResponse]):
if self.query.includeSentiment and query_result.results:
sentiment_lookup = load_generation_sentiment_evaluations_for_traces(
team=self.team,
+ user=self.user,
trace_ids=[self.query.traceId],
timings=self.timings,
modifiers=self.modifiers,
diff --git a/posthog/hogql_queries/ai/traces_query_runner.py b/posthog/hogql_queries/ai/traces_query_runner.py
index 609cafdd1915..461f6053e0b5 100644
--- a/posthog/hogql_queries/ai/traces_query_runner.py
+++ b/posthog/hogql_queries/ai/traces_query_runner.py
@@ -223,6 +223,7 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):
sentiment_lookup = SentimentEvaluationLookup(
by_trace_id=load_trace_sentiment_evaluations(
team=self.team,
+ user=self.user,
trace_ids=result_trace_ids,
timings=self.timings,
modifiers=self.modifiers,
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index baf2fa199e12..330cf2574d62 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -192,6 +192,7 @@ from posthog.slo.types import SloArea, SloOperation, SloOutcome
from posthog.synthetic_user import SyntheticUser
from posthog.utils import generate_cache_key, get_from_dict_or_attr, to_json
+from products.access_control.backend.facade.property_access import sort_restricted_properties
from products.access_control.backend.facade.user_access_control import (
WAREHOUSE_ACCESS_SCOPES,
UserAccessControl,
@@ -3008,6 +3009,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
restricted = self._get_property_access_restrictions()
if restricted:
payload["restricted_properties"] = restricted
+ # A cache hit skips masking. Bump this when masking expands to new tables or mirror columns
+ # so restricted results cached before that change are invalidated.
+ payload["property_access_control_version"] = 1
# Vary the cache key by the events-retention floor: a cache hit returns before the printer applies the floor,
# so without this a result cached pre-enforcement (or at a longer period) would keep surfacing events past
@@ -3056,14 +3060,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
"property_type": restriction.property_type,
"group_type_index": restriction.group_type_index,
}
- for restriction in sorted(
- restricted,
- key=lambda restriction: (
- restriction.name,
- restriction.property_type,
- restriction.group_type_index if restriction.group_type_index is not None else -1,
- ),
- )
+ for restriction in sort_restricted_properties(restricted)
]
def get_cache_key(self) -> str:
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index f4278b116d06..fac42947773e 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -113,11 +113,15 @@ from posthog.query_cache.storage import entry_redis_key
from posthog.query_scan.flag import QueryScanFlag, QueryScanMode
from posthog.shared_link_user import SharedLinkUser
from posthog.slo.types import SloOutcome
+from posthog.utils import generate_cache_key, to_json
from products.access_control.backend.facade.user_access_control import UserAccessControl, UserAccessControlError
from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
+from products.access_control.backend.property_access_control import PropertyAccessLevel
from products.customer_analytics.backend.facade.constants import DEFAULT_ACTIVITY_EVENT
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.product_analytics.backend.facade.queries import TrendsQueryRunner
from products.revenue_analytics.backend.views.test.data.structure import REVENUE_ANALYTICS_CONFIG_SAMPLE_EVENT
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
@@ -797,6 +801,50 @@ class TestQueryRunner(BaseTest):
assert "restricted_objects" not in runner.get_cache_payload()
+ @time_machine.travel("2023-02-04T13:37:42Z", tick=False)
+ def test_restricted_user_does_not_receive_pre_enforcement_cached_results(self) -> None:
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ property_definition = PropertyDefinition.objects.create(
+ team=self.team, name="$ai_input", type=PropertyDefinition.Type.EVENT
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=property_definition,
+ organization_member=self.organization_membership,
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ runner = self.setup_test_query_runner_class()(query={"some_attr": "bla"}, team=self.team, user=self.user)
+ legacy_payload = runner.get_cache_payload()
+ legacy_payload.pop("property_access_control_version", None)
+ legacy_cache_key = generate_cache_key(self.team.pk, f"query_{to_json(legacy_payload).decode()}")
+ now = datetime.now(tz=UTC)
+ legacy_response = TheTestCachedBasicQueryResponse(
+ results=[["private prompt"]],
+ cache_key=legacy_cache_key,
+ is_cached=False,
+ last_refresh=now,
+ next_allowed_client_refresh=now + timedelta(minutes=4),
+ timezone=self.team.timezone,
+ )
+ legacy_cache = QueryCache(team_id=self.team.pk, cache_key=legacy_cache_key)
+ assert legacy_cache.store_result(response=legacy_response.model_dump(), target_age=None)
+ legacy_entry = legacy_cache.lookup().entry
+ assert legacy_entry is not None
+ stored_response = legacy_entry.as_full_response()
+ assert stored_response is not None
+ assert stored_response["results"] == [["private prompt"]]
+
+ response = runner.run(execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE)
+ assert isinstance(response, CacheMissResponse)
+
+ response = runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)
+ assert isinstance(response, TheTestCachedBasicQueryResponse)
+ assert response.is_cached is False
+ assert response.results[0] == ["row", 1, 2, 3]
+
@mock.patch("django.db.transaction.on_commit")
def test_cache_response(self, mock_on_commit):
TestQueryRunner = self.setup_test_query_runner_class()
diff --git a/posthog/temporal/ai_observability/run_session_evaluation.py b/posthog/temporal/ai_observability/run_session_evaluation.py
index 5d012d9b2b7f..892c526bc718 100644
--- a/posthog/temporal/ai_observability/run_session_evaluation.py
+++ b/posthog/temporal/ai_observability/run_session_evaluation.py
@@ -8,7 +8,7 @@ only the fetch-and-evaluate half is session-specific.
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
-from typing import Any
+from typing import TYPE_CHECKING, Any
import temporalio
import posthoganalytics
@@ -45,6 +45,10 @@ from posthog.temporal.ai_observability.message_utils import extract_text_from_me
from posthog.temporal.ai_observability.run_trace_evaluation import TRACE_EVENTS_LOOKBACK
from posthog.temporal.common.utils import close_db_connections
+from products.access_control.backend.facade.api import (
+ get_restricted_properties_with_group_type_index_for_team,
+ split_restricted_property_names,
+)
from products.ai_observability.backend.models.evaluation_configs import (
EVALUATION_TEST_LOOKBACK_DAYS,
MAX_SESSION_EVAL_EVENTS,
@@ -64,7 +68,15 @@ JUDGE_SESSION_MAX_CHARS = 500_000
# Floor so a session with many traces still renders each one readably instead of one line each.
_MIN_TRACE_CHARS_IN_SESSION = 2_000
+if TYPE_CHECKING:
+ from posthog.models import User
+
+
_SESSION_SKIP_REASONING = {
+ "property_access_restricted": (
+ "Default project permissions hide event properties, so this session was not evaluated. "
+ "Review the project's property access rules before running this evaluation."
+ ),
"session_not_found": "No session events were found within the evaluation window; evaluation skipped.",
"session_has_no_traces": (
"This session's events have no trace id, so there was nothing to evaluate. Set $ai_trace_id "
@@ -148,7 +160,9 @@ WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$a
"""
-def _sum_session_payload_bytes(team: Team, session_id: str, date_from: datetime, date_to: datetime) -> int:
+def _sum_session_payload_bytes(
+ team: Team, session_id: str, date_from: datetime, date_to: datetime, *, user: "User | None" = None
+) -> int:
with tags_context(product=Product.LLM_ANALYTICS):
result = query_ai_events(
query=parse_select(_SESSION_PAYLOAD_BYTES_SQL),
@@ -158,6 +172,7 @@ def _sum_session_payload_bytes(team: Team, session_id: str, date_from: datetime,
"date_to": ast.Constant(value=date_to),
},
team=team,
+ user=user,
query_type="SessionEvaluationPayloadBytes",
fall_back_to_events=False,
workload=Workload.OFFLINE,
@@ -192,7 +207,9 @@ class _SessionEventCount:
first_seen: datetime | None
-def _count_session_events(team: Team, session_id: str, date_from: datetime, date_to: datetime) -> _SessionEventCount:
+def _count_session_events(
+ team: Team, session_id: str, date_from: datetime, date_to: datetime, *, user: "User | None" = None
+) -> _SessionEventCount:
"""Cheap preflight so a runaway session id is skipped before pulling its payload, and the
source of the session's real start time (see `fetch_session_for_evaluation`).
@@ -209,6 +226,7 @@ def _count_session_events(team: Team, session_id: str, date_from: datetime, date
"date_to": ast.Constant(value=date_to),
},
team=team,
+ user=user,
query_type="SessionEvaluationEventCount",
fall_back_to_events=False,
workload=Workload.OFFLINE,
@@ -220,7 +238,12 @@ def _count_session_events(team: Team, session_id: str, date_from: datetime, date
def fetch_session_for_evaluation(
- team_id: int, session_id: str, window_start: datetime, window_end: datetime | None = None
+ team_id: int,
+ session_id: str,
+ window_start: datetime,
+ window_end: datetime | None = None,
+ *,
+ user: "User | None" = None,
) -> SessionFetchOutcome:
"""Fetch every trace of a session for an online evaluation, bounded by retention.
@@ -234,17 +257,25 @@ def fetch_session_for_evaluation(
window is chosen.
"""
team = Team.objects.get(id=team_id)
+ # Hog evaluations can read any event property, so masking can change the verdict even outside input/output.
+ if (
+ user is None
+ and split_restricted_property_names(
+ get_restricted_properties_with_group_type_index_for_team(user=None, team_id=team_id)
+ ).event
+ ):
+ return SessionFetchOutcome(traces=None, skip_reason="property_access_restricted", event_count=0)
retention_floor = window_start - timedelta(days=AI_EVENTS_RETENTION_DAYS)
date_to = window_end or datetime.now(UTC)
- preflight = _count_session_events(team, session_id, retention_floor, date_to)
+ preflight = _count_session_events(team, session_id, retention_floor, date_to, user=user)
if preflight.event_count == 0:
return SessionFetchOutcome(traces=None, skip_reason="session_not_found", event_count=0)
if preflight.event_count > MAX_SESSION_EVAL_EVENTS:
return SessionFetchOutcome(traces=None, skip_reason="session_too_large", event_count=preflight.event_count)
# Only now that the row count looks plausible is it worth reading the payload columns to size it.
- payload_bytes = _sum_session_payload_bytes(team, session_id, retention_floor, date_to)
+ payload_bytes = _sum_session_payload_bytes(team, session_id, retention_floor, date_to, user=user)
if should_skip_for_payload(
target="session",
payload_bytes=payload_bytes,
@@ -262,6 +293,7 @@ def fetch_session_for_evaluation(
runner = SessionQueryRunner(
team=team,
+ user=user,
query=SessionQuery(
sessionId=session_id,
dateRange=DateRange(date_from=date_from.isoformat(), date_to=date_to.isoformat()),
@@ -568,6 +600,8 @@ def _sample_quiet_sessions(
date_from: datetime,
date_to: datetime,
quiet_cutoff: datetime,
+ *,
+ user: "User | None" = None,
) -> list[str]:
with tags_context(product=Product.LLM_ANALYTICS):
response = query_ai_events(
@@ -580,6 +614,7 @@ def _sample_quiet_sessions(
"condition_filter": condition_filter if condition_filter is not None else ast.Constant(value=True),
},
team=team,
+ user=user,
query_type="EvaluationTestHogSessionSample",
fall_back_to_events=True,
)
@@ -611,6 +646,7 @@ def run_hog_eval_over_recent_sessions(
allows_na: bool,
quiet_period_seconds: int,
lookback_days: int = EVALUATION_TEST_LOOKBACK_DAYS,
+ user: "User | None" = None,
) -> list[SessionHogTestResult]:
"""Sample sessions that have gone quiet and run session-level Hog bytecode against each.
@@ -622,11 +658,11 @@ def run_hog_eval_over_recent_sessions(
now = datetime.now(UTC)
quiet_cutoff = now - timedelta(seconds=quiet_period_seconds)
date_from = now - timedelta(days=lookback_days)
- session_ids = _sample_quiet_sessions(team, condition_filter, sample_count, date_from, now, quiet_cutoff)
+ session_ids = _sample_quiet_sessions(team, condition_filter, sample_count, date_from, now, quiet_cutoff, user=user)
results: list[SessionHogTestResult] = []
for session_id in session_ids:
- outcome = fetch_session_for_evaluation(team.pk, session_id, now)
+ outcome = fetch_session_for_evaluation(team.pk, session_id, now, user=user)
if outcome.skip_reason or outcome.traces is None:
results.append(
SessionHogTestResult(
diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.py
index cf9acd2ce6c0..2133985578d6 100644
--- a/posthog/temporal/ai_observability/run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py
@@ -16,7 +16,7 @@ import json
import asyncio
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
-from typing import Any
+from typing import TYPE_CHECKING, Any
import structlog
import temporalio
@@ -73,6 +73,10 @@ from posthog.temporal.ai_observability.team_capture import capture_ai_internal_f
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.utils import close_db_connections
+from products.access_control.backend.facade.api import (
+ get_restricted_properties_with_group_type_index_for_team,
+ split_restricted_property_names,
+)
from products.ai_observability.backend.models.evaluation_configs import (
EVALUATION_TEST_LOOKBACK_DAYS,
TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
@@ -85,6 +89,9 @@ from products.ai_observability.backend.text_repr.formatters import (
llm_trace_to_formatter_format,
)
+if TYPE_CHECKING:
+ from posthog.models import User
+
logger = structlog.get_logger(__name__)
# How far back from the workflow start to look for trace events. The trigger is the first
@@ -115,6 +122,10 @@ HAVING event_count > 0
"""
_SKIP_REASONING = {
+ "property_access_restricted": (
+ "Default project permissions hide event properties, so this trace was not evaluated. "
+ "Review the project's property access rules before running this evaluation."
+ ),
"trace_not_found": "No trace events were found within the evaluation window; evaluation skipped.",
"trace_too_large": (
f"Trace exceeds {MAX_TRACE_EVAL_EVENTS} events — likely a shared or runaway trace id; evaluation skipped."
@@ -171,7 +182,9 @@ class TraceFetchOutcome:
event_count: int
-def _count_trace_events(team: Team, trace_id: str, date_from: datetime, date_to: datetime) -> int:
+def _count_trace_events(
+ team: Team, trace_id: str, date_from: datetime, date_to: datetime, *, user: "User | None" = None
+) -> int:
result = query_ai_events(
query=parse_select(_TRACE_EVENT_COUNT_SQL),
placeholders={
@@ -180,6 +193,7 @@ def _count_trace_events(team: Team, trace_id: str, date_from: datetime, date_to:
"date_to": ast.Constant(value=date_to),
},
team=team,
+ user=user,
query_type="TraceEvaluationEventCount",
fall_back_to_events=True,
)
@@ -198,7 +212,9 @@ WHERE event IN ('$ai_span', '$ai_generation', '$ai_embedding', '$ai_metric', '$a
"""
-def _sum_trace_payload_bytes(team: Team, trace_id: str, date_from: datetime, date_to: datetime) -> int:
+def _sum_trace_payload_bytes(
+ team: Team, trace_id: str, date_from: datetime, date_to: datetime, *, user: "User | None" = None
+) -> int:
result = query_ai_events(
query=parse_select(_TRACE_PAYLOAD_BYTES_SQL),
placeholders={
@@ -207,6 +223,7 @@ def _sum_trace_payload_bytes(team: Team, trace_id: str, date_from: datetime, dat
"date_to": ast.Constant(value=date_to),
},
team=team,
+ user=user,
query_type="TraceEvaluationPayloadBytes",
fall_back_to_events=False,
)
@@ -216,14 +233,20 @@ def _sum_trace_payload_bytes(team: Team, trace_id: str, date_from: datetime, dat
def _fetch_trace(
- team: Team, trace_id: str, date_from: datetime, date_to: datetime, *, bound_to_date_to: bool = False
+ team: Team,
+ trace_id: str,
+ date_from: datetime,
+ date_to: datetime,
+ *,
+ bound_to_date_to: bool = False,
+ user: "User | None" = None,
) -> TraceFetchOutcome:
"""Fetch a single full trace from ClickHouse over an explicit window, with a cheap count
preflight so degenerate traces are skipped before pulling their payload.
`bound_to_date_to` grades the trace as of `date_to`. A live run leaves it off and reads the
whole trace, which is what it graded before backfills existed."""
- event_count = _count_trace_events(team, trace_id, date_from, date_to)
+ event_count = _count_trace_events(team, trace_id, date_from, date_to, user=user)
if event_count == 0:
return TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=0)
if event_count > MAX_TRACE_EVAL_EVENTS:
@@ -235,12 +258,13 @@ def _fetch_trace(
# trace budget with evidence, and flipping it to enforcing is a deliberate follow-up.
should_skip_for_payload(
target="trace",
- payload_bytes=_sum_trace_payload_bytes(team, trace_id, date_from, date_to),
+ payload_bytes=_sum_trace_payload_bytes(team, trace_id, date_from, date_to, user=user),
budget_bytes=payload_budget_bytes(JUDGE_TRACE_MAX_CHARS),
)
runner = TraceQueryRunner(
team=team,
+ user=user,
query=TraceQuery(
traceId=trace_id,
dateRange=DateRange(date_from=date_from.isoformat(), date_to=date_to.isoformat()),
@@ -269,6 +293,11 @@ def fetch_trace_for_evaluation(
) -> TraceFetchOutcome:
"""Fetch the full trace for an online evaluation run, looking back from the workflow start."""
team = Team.objects.get(id=team_id)
+ # Hog evaluations can read any event property, so masking can change the verdict even outside input/output.
+ if split_restricted_property_names(
+ get_restricted_properties_with_group_type_index_for_team(user=None, team_id=team_id)
+ ).event:
+ return TraceFetchOutcome(trace=None, skip_reason="property_access_restricted", event_count=0)
date_from = window_start - TRACE_EVENTS_LOOKBACK
date_to = window_end or datetime.now(UTC)
return _fetch_trace(team, trace_id, date_from, date_to, bound_to_date_to=window_end is not None)
@@ -310,6 +339,8 @@ def _sample_recent_traces(
sample_count: int,
date_from: datetime,
date_to: datetime,
+ *,
+ user: "User | None" = None,
) -> list[TraceHogTestSample]:
"""Pick the most recent distinct trace ids whose *triggering* generation matches the
evaluation's conditions — mirroring the online scheduler, which starts a trace-eval run
@@ -356,6 +387,7 @@ def _sample_recent_traces(
query=query,
placeholders={"where_clause": ast.And(exprs=where_exprs)},
team=team,
+ user=user,
query_type="EvaluationTestHogTraceSample",
fall_back_to_events=True,
)
@@ -389,6 +421,7 @@ def run_hog_eval_over_recent_traces(
allows_na: bool,
window_seconds: int = TRACE_EVAL_DEFAULT_WINDOW_SECONDS,
lookback_days: int = EVALUATION_TEST_LOOKBACK_DAYS,
+ user: "User | None" = None,
) -> list[TraceHogTestResult]:
"""Sample recent traces matching the conditions and run trace-level Hog bytecode against each.
@@ -407,13 +440,14 @@ def run_hog_eval_over_recent_traces(
sample_count,
sample_date_from,
sample_date_to,
+ user=user,
)
results: list[TraceHogTestResult] = []
for sample in trace_samples:
trace_date_from = sample.trigger_timestamp - TRACE_EVENTS_LOOKBACK
trace_date_to = sample.trigger_timestamp + window
- outcome = _fetch_trace(team, sample.trace_id, trace_date_from, trace_date_to)
+ outcome = _fetch_trace(team, sample.trace_id, trace_date_from, trace_date_to, user=user)
if outcome.skip_reason or outcome.trace is None:
results.append(
TraceHogTestResult(
diff --git a/posthog/temporal/ai_observability/test_run_session_evaluation.py b/posthog/temporal/ai_observability/test_run_session_evaluation.py
index bd3309a07c72..37a403ae37ea 100644
--- a/posthog/temporal/ai_observability/test_run_session_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_session_evaluation.py
@@ -1,4 +1,5 @@
import uuid
+from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
import pytest
@@ -12,6 +13,7 @@ from posthog.schema import LLMTrace, LLMTraceEvent
from posthog.hogql.constants import MAX_SELECT_TRACES_LIMIT_EXPORT
+from posthog.cdp.validation import compile_hog
from posthog.temporal.ai_observability.evaluation_payload import payload_budget_bytes
from posthog.temporal.ai_observability.run_session_evaluation import (
_SESSION_EVENT_COUNT_SQL,
@@ -26,6 +28,7 @@ from posthog.temporal.ai_observability.run_session_evaluation import (
execute_session_llm_judge_activity,
fetch_session_for_evaluation,
format_session_for_judge,
+ run_hog_eval_over_recent_sessions,
session_fetch_lookback,
)
@@ -219,8 +222,57 @@ class TestCountSessionEvents:
assert mock_query_ai_events.call_args.kwargs["fall_back_to_events"] is False
+class TestRunHogEvalOverRecentSessions:
+ @time_machine.travel(FROZEN_NOW, tick=False)
+ def test_preview_applies_user_to_sampling_and_session_reads(self) -> None:
+ team = Mock(pk=1)
+ user = Mock()
+ trace = _trace("t1", cost=0, latency=0, event_count=2)
+ bytecode = compile_hog("return target.type == 'session' and length(evaluation_events) == 2", "destination")
+ with (
+ patch("posthog.temporal.ai_observability.run_session_evaluation.Team") as mock_team,
+ patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.query_ai_events",
+ side_effect=[
+ Mock(results=[["s-1"]]),
+ Mock(results=[[2, FROZEN_NOW - timedelta(hours=1)]]),
+ Mock(results=[[0]]),
+ ],
+ ) as mock_query,
+ patch("posthog.temporal.ai_observability.run_session_evaluation.SessionQueryRunner") as mock_runner,
+ ):
+ mock_team.objects.get.return_value = team
+ mock_runner.return_value.calculate.return_value = Mock(results=[trace], hasMore=False)
+ results = run_hog_eval_over_recent_sessions(
+ team=team,
+ user=user,
+ bytecode=bytecode,
+ condition_filter=None,
+ sample_count=1,
+ allows_na=False,
+ quiet_period_seconds=120,
+ )
+
+ assert len(results) == 1
+ assert results[0].session_id == "s-1"
+ assert results[0].verdict is True
+ assert results[0].error is None
+ for query_call in mock_query.call_args_list:
+ assert query_call.kwargs["user"] is user
+ assert mock_runner.call_args.kwargs["user"] is user
+
+
class TestFetchSessionForEvaluation:
+ @pytest.fixture(autouse=True)
+ def unrestricted_project_defaults(self) -> Iterator[None]:
+ with patch(
+ "posthog.temporal.ai_observability.run_session_evaluation.get_restricted_properties_with_group_type_index_for_team",
+ return_value=set(),
+ ):
+ yield
+
def test_queries_in_evaluation_mode_with_both_date_bounds(self):
+ user = Mock()
with (
patch("posthog.temporal.ai_observability.run_session_evaluation.Team"),
patch(
@@ -238,10 +290,11 @@ class TestFetchSessionForEvaluation:
mock_session_query_runner.return_value.calculate.return_value = Mock(
results=[_trace("t1", cost=0, latency=0)], hasMore=False
)
- fetch_session_for_evaluation(1, "s-1", datetime(2026, 7, 20, tzinfo=UTC))
+ fetch_session_for_evaluation(1, "s-1", datetime(2026, 7, 20, tzinfo=UTC), user=user)
kwargs = mock_session_query_runner.call_args.kwargs
assert kwargs["for_evaluation"] is True
+ assert kwargs["user"] is user
assert kwargs["query"].dateRange.date_from is not None
assert kwargs["query"].dateRange.date_to is not None
# SessionQueryRunner defaults to 100 rows under LimitContext.QUERY, which would drop the
@@ -410,7 +463,13 @@ class TestFetchSessionForEvaluation:
class TestExecuteSessionActivities:
@pytest.mark.parametrize(
"skip_reason",
- ["session_not_found", "session_too_large", "session_payload_too_large", "session_truncated"],
+ [
+ "session_not_found",
+ "session_too_large",
+ "session_payload_too_large",
+ "session_truncated",
+ "property_access_restricted",
+ ],
)
def test_hog_skips_carry_a_session_specific_reason(self, skip_reason):
with patch(
@@ -444,11 +503,12 @@ class TestExecuteSessionActivities:
)
)
- def test_judge_skips_without_judging_when_the_session_is_truncated(self):
+ @pytest.mark.parametrize("skip_reason", ["session_truncated", "property_access_restricted"])
+ def test_judge_skips_without_judging(self, skip_reason: str) -> None:
with (
patch(
"posthog.temporal.ai_observability.run_session_evaluation.fetch_session_for_evaluation",
- return_value=SessionFetchOutcome(traces=None, skip_reason="session_truncated", event_count=0),
+ return_value=SessionFetchOutcome(traces=None, skip_reason=skip_reason, event_count=0),
),
patch("posthog.temporal.ai_observability.run_session_evaluation.call_llm_judge") as mock_call_llm_judge,
):
@@ -466,7 +526,9 @@ class TestExecuteSessionActivities:
)
)
assert result["skipped"] is True
- assert result["skip_reason"] == "session_truncated"
+ assert result["skip_reason"] == skip_reason
+ if skip_reason == "property_access_restricted":
+ assert "property access rules" in result["reasoning"]
# The whole point of the truncation-as-skip choice: never grade a partial transcript.
mock_call_llm_judge.assert_not_called()
diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
index 824409fbaee4..592b73d744d7 100644
--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py
@@ -16,8 +16,12 @@ from posthog.hogql import ast
from posthog.api.capture import CaptureInternalError
from posthog.cdp.validation import compile_hog
-from posthog.models import Organization, Team
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, PropertyDefinition, Team, User
+from posthog.temporal.ai_observability.run_session_evaluation import fetch_session_for_evaluation
+from products.access_control.backend.facade.contracts import PropertyAccessLevel
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
from products.ai_observability.backend.models.evaluations import Evaluation
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
@@ -316,6 +320,65 @@ class TestBuildTraceSkipResult:
assert result["skip_reason"] == "trace_not_found"
+class TestBackgroundEvaluationPropertyAccess:
+ @pytest.mark.django_db
+ @pytest.mark.parametrize("target", ["trace", "session"])
+ @pytest.mark.parametrize(
+ "property_type,member_only,access_level,should_skip",
+ [
+ (PropertyDefinition.Type.EVENT, False, PropertyAccessLevel.NONE, True),
+ (PropertyDefinition.Type.EVENT, True, PropertyAccessLevel.NONE, False),
+ (PropertyDefinition.Type.EVENT, False, PropertyAccessLevel.READ, False),
+ (PropertyDefinition.Type.PERSON, False, PropertyAccessLevel.NONE, False),
+ (PropertyDefinition.Type.GROUP, False, PropertyAccessLevel.NONE, False),
+ ],
+ )
+ def test_only_default_event_denials_skip_before_reading_content(
+ self,
+ setup_data: dict[str, object],
+ target: str,
+ property_type: int,
+ member_only: bool,
+ access_level: PropertyAccessLevel,
+ should_skip: bool,
+ ) -> None:
+ organization = cast(Organization, setup_data["organization"])
+ team = cast(Team, setup_data["team"])
+ organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ organization.save()
+ member = None
+ if member_only:
+ user = User.objects.create_and_join(organization, "[email protected]", "test-password")
+ member = user.organization_memberships.get(organization=organization)
+ definition = PropertyDefinition.objects.create(
+ team=team,
+ name="$ai_input",
+ type=property_type,
+ group_type_index=0 if property_type == PropertyDefinition.Type.GROUP else None,
+ )
+ PropertyAccessControl.objects.create(
+ team=team,
+ property_definition=definition,
+ organization_member=member,
+ access_level=access_level.value,
+ )
+ with patch(
+ f"posthog.temporal.ai_observability.run_{target}_evaluation.query_ai_events",
+ return_value=MagicMock(results=[]),
+ ) as mock_query:
+ fetch = fetch_trace_for_evaluation if target == "trace" else fetch_session_for_evaluation
+ outcome = fetch(team.id, "missing-unit", FROZEN_NOW)
+
+ assert outcome.skip_reason == ("property_access_restricted" if should_skip else f"{target}_not_found")
+ assert outcome.event_count == 0
+ if should_skip:
+ mock_query.assert_not_called()
+ else:
+ mock_query.assert_called_once()
+
+
class TestFetchTraceForEvaluation:
@pytest.mark.django_db(transaction=True)
def test_skips_when_no_events_found(self, setup_data):
@@ -446,6 +509,7 @@ class TestRunHogEvalOverRecentTraces:
@time_machine.travel(FROZEN_NOW, tick=False)
def test_uses_the_sampled_trigger_and_configured_aggregation_window(self):
team = MagicMock(spec=Team)
+ user = MagicMock()
trigger_timestamp = FROZEN_NOW - timedelta(hours=2)
trace = create_trace(
[
@@ -462,12 +526,17 @@ class TestRunHogEvalOverRecentTraces:
"posthog.temporal.ai_observability.run_trace_evaluation._sample_recent_traces",
return_value=[TraceHogTestSample(trace_id="trace-123", trigger_timestamp=trigger_timestamp)],
) as mock_sample:
- with patch(
- "posthog.temporal.ai_observability.run_trace_evaluation._fetch_trace",
- return_value=TraceFetchOutcome(trace=trace, skip_reason=None, event_count=2),
- ) as mock_fetch:
+ with (
+ patch(
+ "posthog.temporal.ai_observability.run_trace_evaluation.query_ai_events",
+ side_effect=[MagicMock(results=[[2]]), MagicMock(results=[[0]])],
+ ) as mock_query,
+ patch("posthog.temporal.ai_observability.run_trace_evaluation.TraceQueryRunner") as mock_runner,
+ ):
+ mock_runner.return_value.calculate.return_value = MagicMock(results=[trace])
results = run_hog_eval_over_recent_traces(
team=team,
+ user=user,
bytecode=bytecode,
condition_filter=None,
sample_count=1,
@@ -481,13 +550,15 @@ class TestRunHogEvalOverRecentTraces:
1,
FROZEN_NOW - timedelta(seconds=120, days=7),
FROZEN_NOW - timedelta(seconds=120),
+ user=user,
)
- mock_fetch.assert_called_once_with(
- team,
- "trace-123",
- trigger_timestamp - TRACE_EVENTS_LOOKBACK,
- trigger_timestamp + timedelta(seconds=120),
- )
+ for query_call in mock_query.call_args_list:
+ assert query_call.kwargs["user"] is user
+ runner_kwargs = mock_runner.call_args.kwargs
+ assert runner_kwargs["user"] is user
+ assert runner_kwargs["query"].traceId == "trace-123"
+ assert runner_kwargs["query"].dateRange.date_from == (trigger_timestamp - TRACE_EVENTS_LOOKBACK).isoformat()
+ assert runner_kwargs["query"].dateRange.date_to == (trigger_timestamp + timedelta(seconds=120)).isoformat()
assert results[0].verdict is True
assert results[0].input_preview == "first"
assert results[0].output_preview == "two"
@@ -535,24 +606,31 @@ class TestExecuteTraceLLMJudgeActivity:
assert result["verdict"] is True
assert result["reasoning"] == "Resolved both questions"
- @pytest.mark.django_db(transaction=True)
- def test_skips_without_llm_call_when_trace_missing(self, setup_data):
+ @pytest.mark.parametrize("skip_reason", ["trace_not_found", "property_access_restricted"])
+ def test_skips_without_llm_call(self, skip_reason: str) -> None:
with patch(
"posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",
- return_value=TraceFetchOutcome(trace=None, skip_reason="trace_not_found", event_count=0),
+ return_value=TraceFetchOutcome(trace=None, skip_reason=skip_reason, event_count=0),
):
with patch("posthog.temporal.ai_observability.evaluation_llm_judge.Client") as mock_client_class:
result = execute_trace_llm_judge_activity(
ExecuteTraceEvaluationInputs(
- evaluation=evaluation_dict(setup_data),
- team_id=setup_data["team"].id,
+ evaluation={
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Is the response correct?"},
+ "output_type": "boolean",
+ "output_config": {},
+ },
+ team_id=1,
trace_id="trace-123",
window_start=FROZEN_NOW.isoformat(),
)
)
assert result["skipped"] is True
- assert result["skip_reason"] == "trace_not_found"
+ assert result["skip_reason"] == skip_reason
+ if skip_reason == "property_access_restricted":
+ assert "property access rules" in result["reasoning"]
mock_client_class.assert_not_called()
@@ -589,30 +667,29 @@ class TestExecuteTraceHogEvalActivity:
assert result["verdict"] is True
@pytest.mark.asyncio
- @pytest.mark.django_db(transaction=True)
- async def test_skips_when_trace_too_large(self, setup_data):
+ @pytest.mark.parametrize("skip_reason", ["trace_too_large", "property_access_restricted"])
+ async def test_skips_without_running_hog(self, skip_reason: str) -> None:
bytecode = compile_hog("return true", "destination")
- evaluation = evaluation_dict(
- setup_data,
- evaluation_type="hog",
- evaluation_config={"source": "return true", "bytecode": bytecode},
- )
+ evaluation = {
+ "evaluation_type": "hog",
+ "evaluation_config": {"source": "return true", "bytecode": bytecode},
+ }
with patch(
"posthog.temporal.ai_observability.run_trace_evaluation.fetch_trace_for_evaluation",
- return_value=TraceFetchOutcome(trace=None, skip_reason="trace_too_large", event_count=10_000),
+ return_value=TraceFetchOutcome(trace=None, skip_reason=skip_reason, event_count=10_000),
):
result = await execute_trace_hog_eval_activity(
ExecuteTraceEvaluationInputs(
evaluation=evaluation,
- team_id=setup_data["team"].id,
+ team_id=1,
trace_id="trace-123",
window_start=FROZEN_NOW.isoformat(),
)
)
assert result["skipped"] is True
- assert result["skip_reason"] == "trace_too_large"
+ assert result["skip_reason"] == skip_reason
@pytest.mark.asyncio
@pytest.mark.django_db(transaction=True)
diff --git a/products/access_control/backend/facade/property_access.py b/products/access_control/backend/facade/property_access.py
new file mode 100644
index 000000000000..79dabee5efa4
--- /dev/null
+++ b/products/access_control/backend/facade/property_access.py
@@ -0,0 +1,26 @@
+import json
+import hashlib
+from collections.abc import Collection
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from posthog.hogql.property_access_types import RestrictedProperty
+
+
+def sort_restricted_properties(restrictions: Collection["RestrictedProperty"]) -> list["RestrictedProperty"]:
+ return sorted(
+ restrictions,
+ key=lambda restriction: (
+ restriction.name,
+ restriction.property_type,
+ restriction.group_type_index if restriction.group_type_index is not None else -1,
+ ),
+ )
+
+
+def restriction_fingerprint(restrictions: Collection["RestrictedProperty"]) -> str:
+ metadata = [
+ (restriction.name, restriction.property_type, restriction.group_type_index)
+ for restriction in sort_restricted_properties(restrictions)
+ ]
+ return hashlib.sha256(json.dumps(metadata).encode()).hexdigest()
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index dcbf33887400..adcf1efb2a70 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import TYPE_CHECKING, Any, cast
from django.db import transaction
from django.db.models import Q, QuerySet
@@ -75,6 +75,9 @@ from ..models.model_configuration import LLMModelConfiguration
from ..models.provider_keys import LLMProvider, LLMProviderKey
from .metrics import llma_track_latency
+if TYPE_CHECKING:
+ from posthog.models import User
+
logger = structlog.get_logger(__name__)
@@ -870,6 +873,7 @@ def _test_hog_over_sessions(
try:
session_results = run_hog_eval_over_recent_sessions(
team=team,
+ user=cast("User", request.user),
bytecode=bytecode,
condition_filter=condition_filter,
sample_count=sample_count,
@@ -940,6 +944,7 @@ def _test_hog_over_traces(
try:
trace_results = run_hog_eval_over_recent_traces(
team=team,
+ user=cast("User", request.user),
bytecode=bytecode,
condition_filter=condition_filter,
sample_count=sample_count,
@@ -1296,6 +1301,7 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
query=query,
placeholders={"where_clause": ast.And(exprs=where_exprs)},
team=team,
+ user=cast("User", request.user),
query_type="EvaluationTestHog",
fall_back_to_events=False,
limit_context=None,
diff --git a/products/ai_observability/backend/api/offline_evaluations.py b/products/ai_observability/backend/api/offline_evaluations.py
index c608d12740c2..c822fbd1fb69 100644
--- a/products/ai_observability/backend/api/offline_evaluations.py
+++ b/products/ai_observability/backend/api/offline_evaluations.py
@@ -1,4 +1,5 @@
from collections import namedtuple
+from typing import TYPE_CHECKING, cast
import structlog
from drf_spectacular.types import OpenApiTypes
@@ -21,6 +22,9 @@ from posthog.permissions import AccessControlPermission
from products.ai_observability.backend.api.metrics import llma_track_latency
+if TYPE_CHECKING:
+ from posthog.models import User
+
logger = structlog.get_logger(__name__)
OFFLINE_EXPERIMENT_ITEMS_LIMIT = 20000
@@ -176,6 +180,7 @@ class AIObservabilityOfflineEvaluationsViewSet(TeamAndOrgViewSetMixin, viewsets.
query=preflight_query,
placeholders={},
team=self.team,
+ user=cast("User", request.user),
query_type="LLMOfflineEvaluationItemsResolve",
limit_context=LimitContext.QUERY,
)
@@ -213,6 +218,7 @@ class AIObservabilityOfflineEvaluationsViewSet(TeamAndOrgViewSetMixin, viewsets.
"ts_end": ast.Constant(value=ts_end),
},
team=self.team,
+ user=cast("User", request.user),
query_type="LLMOfflineEvaluationItems",
fall_back_to_events=True,
limit_context=LimitContext.QUERY,
diff --git a/products/ai_observability/backend/api/summarization.py b/products/ai_observability/backend/api/summarization.py
index 61633fa169d8..abd150c008b4 100644
--- a/products/ai_observability/backend/api/summarization.py
+++ b/products/ai_observability/backend/api/summarization.py
@@ -11,7 +11,7 @@ Endpoints:
import time
from datetime import datetime
-from typing import Any
+from typing import TYPE_CHECKING, Any, cast
from django.core.cache import cache
@@ -49,11 +49,18 @@ from posthog.rate_limit import (
AIObservabilitySummarizationSustainedThrottle,
)
+from products.access_control.backend.facade.api import (
+ get_restricted_properties_with_group_type_index_for_team,
+ split_restricted_property_names,
+)
from products.ai_observability.backend.api.metrics import llma_track_latency
from products.ai_observability.backend.summarization.budget import bounded_text_repr, text_repr_budget
from products.ai_observability.backend.summarization.llm import summarize
from products.ai_observability.backend.summarization.models import SummarizationMode
-from products.ai_observability.backend.summarization.utils import get_summary_cache_key
+from products.ai_observability.backend.summarization.utils import (
+ get_summarization_lookup_date_range,
+ get_summary_cache_key,
+)
from products.ai_observability.backend.text_repr.formatters import (
FormatterOptions,
format_event_text_repr,
@@ -61,6 +68,9 @@ from products.ai_observability.backend.text_repr.formatters import (
llm_trace_to_formatter_format,
)
+if TYPE_CHECKING:
+ from posthog.models import User
+
logger = structlog.get_logger(__name__)
# Event types the formatters can render on their own, so a single one of them can be summarized by UUID.
@@ -251,7 +261,16 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Gener
mode: Summary detail level ('minimal' or 'detailed')
model: LLM model
"""
- return get_summary_cache_key(self.team_id, summarize_type, entity_id, mode, model)
+ return get_summary_cache_key(
+ self.team_id,
+ summarize_type,
+ entity_id,
+ mode,
+ model,
+ restricted_properties=get_restricted_properties_with_group_type_index_for_team(
+ user=cast("User", self.request.user), team_id=self.team_id
+ ),
+ )
def _extract_entity_id(self, summarize_type: str, data: dict) -> tuple[str, dict]:
"""Extract entity ID and validated entity data based on summarize type.
@@ -293,6 +312,7 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Gener
)
runner = TraceQueryRunner(
team=self.team,
+ user=cast("User", self.request.user),
query=TraceQuery(traceId=trace_id, dateRange=date_range),
)
response = runner.calculate()
@@ -344,6 +364,7 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Gener
"date_to": date_to_expr,
},
team=self.team,
+ user=cast("User", self.request.user),
)
if not result.results:
@@ -400,6 +421,7 @@ class AIObservabilitySummarizationViewSet(TeamAndOrgViewSetMixin, viewsets.Gener
query=query,
placeholders=placeholders,
team=self.team,
+ user=cast("User", self.request.user),
query_type="LLMAnalyticsSummarizationHeavyFetch",
)
except AIEventsExpiredError:
@@ -603,6 +625,22 @@ The response includes the structured summary, the text representation, and metad
else:
data = serializer.validated_data["data"]
entity_id, entity_data = self._extract_entity_id(summarize_type, data)
+ restrictions = get_restricted_properties_with_group_type_index_for_team(
+ user=cast("User", request.user), team_id=self.team_id
+ )
+ # Client payloads may contain values fetched before permissions changed, so refetch to mask them.
+ # Formatters render only event properties. Other restrictions must not force a lookup
+ # that could reject a client-only entity without protecting any formatted content.
+ if split_restricted_property_names(restrictions).event:
+ if summarize_type == "trace":
+ trace_id = entity_id
+ else:
+ generation_id = entity_id
+ date_range = get_summarization_lookup_date_range(
+ entity_data["event"].get("timestamp"), date_from=date_from, date_to=date_to
+ )
+ date_from = date_range.date_from
+ date_to = date_range.date_to
cache_key = self._get_cache_key(summarize_type, entity_id, mode, model)
if not force_refresh:
diff --git a/products/ai_observability/backend/api/taggers.py b/products/ai_observability/backend/api/taggers.py
index 27e599e15958..117cef0f5a8c 100644
--- a/products/ai_observability/backend/api/taggers.py
+++ b/products/ai_observability/backend/api/taggers.py
@@ -1,5 +1,5 @@
import json
-from typing import Any, cast
+from typing import TYPE_CHECKING, Any, cast
from django.core.validators import EMPTY_VALUES
from django.db import transaction
@@ -43,6 +43,9 @@ from ..models.provider_keys import LLMProvider, LLMProviderKey
from ..models.taggers import Tagger, TaggerType, validate_tagger_config
from .metrics import llma_track_latency
+if TYPE_CHECKING:
+ from posthog.models import User
+
logger = structlog.get_logger(__name__)
@@ -604,7 +607,7 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
)
tag_queries(product=Product.LLM_ANALYTICS, feature=QueryFeature.QUERY)
- response = execute_hogql_query(query=query, team=team, limit_context=None)
+ response = execute_hogql_query(query=query, team=team, user=cast("User", request.user), limit_context=None)
if not response.results:
return Response({"results": [], "message": "No recent AI events found in the last 7 days"})
diff --git a/products/ai_observability/backend/api/test/test_evaluations.py b/products/ai_observability/backend/api/test/test_evaluations.py
index cca163537cf8..daafde50586f 100644
--- a/products/ai_observability/backend/api/test/test_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_evaluations.py
@@ -1295,6 +1295,7 @@ class TestTestHogEndpoint(APIBaseTest):
self.assertEqual(r["output_preview"], "4")
query = mock_query.call_args.kwargs["query"]
+ self.assertEqual(mock_query.call_args.kwargs["user"], self.user)
self.assertEqual(query.select_from.table.chain, ["posthog", "ai_events"])
self.assertEqual(query.select[4].chain, ["timestamp"])
self.assertEqual([field.chain for field in query.select[5:]], [[name] for name in HEAVY_COLUMN_NAMES])
@@ -1385,6 +1386,7 @@ class TestTestHogEndpoint(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(mock_run_over_traces.call_args.kwargs["window_seconds"], 120)
+ self.assertEqual(mock_run_over_traces.call_args.kwargs["user"], self.user)
# The generation query path must not run for a trace target.
mock_query.assert_not_called()
results = response.json()["results"]
diff --git a/products/ai_observability/backend/api/test/test_offline_evaluations.py b/products/ai_observability/backend/api/test/test_offline_evaluations.py
index 540235c4ce96..30a0baab38ce 100644
--- a/products/ai_observability/backend/api/test/test_offline_evaluations.py
+++ b/products/ai_observability/backend/api/test/test_offline_evaluations.py
@@ -171,6 +171,8 @@ class TestOfflineEvaluationItemsEndpoint(APIBaseTest):
}
assert mock_preflight.call_args.kwargs["query_type"] == "LLMOfflineEvaluationItemsResolve"
assert mock_heavy.call_args.kwargs["query_type"] == "LLMOfflineEvaluationItems"
+ assert mock_preflight.call_args.kwargs["user"] == self.user
+ assert mock_heavy.call_args.kwargs["user"] == self.user
@patch("products.ai_observability.backend.api.offline_evaluations.query_ai_events")
@patch("products.ai_observability.backend.api.offline_evaluations.execute_hogql_query")
diff --git a/products/ai_observability/backend/api/test/test_summarization.py b/products/ai_observability/backend/api/test/test_summarization.py
index 1585f4552089..b574e595094a 100644
--- a/products/ai_observability/backend/api/test/test_summarization.py
+++ b/products/ai_observability/backend/api/test/test_summarization.py
@@ -9,16 +9,20 @@ from datetime import UTC, datetime, timedelta
from typing import Any
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.conf import settings
from parameterized import parameterized
from rest_framework import status
+from posthog.constants import AvailableFeature
+from posthog.models import PropertyDefinition
from posthog.models.ai_events.test_util import bulk_create_ai_events
from posthog.models.event.util import bulk_create_events
+from products.access_control.backend.facade.contracts import PropertyAccessLevel
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.ai_observability.backend.summarization.llm.schema import (
InterestingNote,
SummarizationResponse,
@@ -448,6 +452,140 @@ class TestSummarizationByID(ClickhouseTestMixin, APIBaseTest):
bulk_create_events([{**row, "properties": metadata}])
bulk_create_ai_events([{**row, "properties": {**metadata, **content}}])
+ @parameterized.expand([("trace",), ("event",)])
+ @patch("products.ai_observability.backend.api.summarization.summarize")
+ def test_cache_and_client_payload_follow_current_property_permissions(
+ self, summarize_type: str, mock_summarize: MagicMock
+ ) -> None:
+ self._approve_ai_processing()
+ reader = self._create_user("[email protected]")
+ self.client.force_login(reader)
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ event_uuid = uuid.uuid4()
+ trace_id = str(uuid.uuid4())
+ timestamp = datetime.now(UTC)
+ metadata = {"$ai_trace_id": trace_id, "$ai_span_name": "generation"}
+ content = {
+ "$ai_input": [{"role": "user", "content": "private-input"}],
+ "$ai_output_choices": [{"role": "assistant", "content": "public-output"}],
+ }
+ self._ingest_ai_event("$ai_generation", event_uuid, timestamp, metadata, content)
+ event = {"id": str(event_uuid), "event": "$ai_generation", "properties": {**metadata, **content}}
+ data = (
+ {"trace": {"id": trace_id, "properties": metadata}, "hierarchy": [{"event": event, "children": []}]}
+ if summarize_type == "trace"
+ else {"event": event}
+ )
+ request_data = {
+ "summarize_type": summarize_type,
+ "data": data,
+ "date_from": (timestamp - timedelta(days=1)).isoformat(),
+ "date_to": (timestamp + timedelta(days=1)).isoformat(),
+ }
+ url = f"/api/projects/{self.team.id}/llm_analytics/summarization/"
+ mock_summarize.return_value = SummarizationResponse(
+ title="private-input", flow_diagram="Start", summary_bullets=[], interesting_notes=[]
+ )
+ unrestricted = self.client.post(url, request_data, format="json")
+ self.assertEqual(unrestricted.status_code, status.HTTP_200_OK, unrestricted.data)
+ self.assertIn("private-input", unrestricted.data["text_repr"])
+
+ definition = PropertyDefinition.objects.create(
+ team=self.team, name="$ai_input", type=PropertyDefinition.Type.EVENT
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=definition,
+ organization_member=reader.organization_memberships.get(organization=self.organization),
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ if summarize_type == "trace":
+ titles = self.client.post(url + "batch_check/", {"trace_ids": [trace_id]}, format="json")
+ self.assertEqual(titles.status_code, status.HTTP_200_OK, titles.data)
+ self.assertEqual(titles.data["summaries"], [])
+
+ mock_summarize.return_value = SummarizationResponse(
+ title="public-output", flow_diagram="Start", summary_bullets=[], interesting_notes=[]
+ )
+ restricted = self.client.post(url, request_data, format="json")
+ self.assertEqual(restricted.status_code, status.HTTP_200_OK, restricted.data)
+ self.assertEqual(restricted.data["summary"]["title"], "public-output")
+ self.assertNotIn("private-input", restricted.data["text_repr"])
+ self.assertIn("public-output", restricted.data["text_repr"])
+ self.assertNotIn("private-input", mock_summarize.call_args.kwargs["text_repr"])
+
+ id_request = {"trace_id": trace_id} if summarize_type == "trace" else {"generation_id": str(event_uuid)}
+ cached = self.client.post(url, id_request, format="json")
+ self.assertEqual(cached.status_code, status.HTTP_200_OK, cached.data)
+ self.assertEqual(cached.data, restricted.data)
+ self.assertEqual(mock_summarize.call_count, 2)
+ if summarize_type == "trace":
+ titles = self.client.post(url + "batch_check/", {"trace_ids": [trace_id]}, format="json")
+ self.assertEqual(
+ titles.data["summaries"], [{"trace_id": trace_id, "title": "public-output", "cached": True}]
+ )
+
+ @parameterized.expand(
+ [
+ (summarize_type, property_type)
+ for summarize_type in ("trace", "event")
+ for property_type in (PropertyDefinition.Type.PERSON, PropertyDefinition.Type.EVENT)
+ ]
+ )
+ @patch("products.ai_observability.backend.api.summarization.summarize")
+ def test_client_only_payload_requires_no_event_property_restrictions(
+ self, summarize_type: str, property_type: int, mock_summarize: MagicMock
+ ) -> None:
+ self._approve_ai_processing()
+ reader = self._create_user("[email protected]")
+ self.client.force_login(reader)
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ definition = PropertyDefinition.objects.create(team=self.team, name="$ai_input", type=property_type)
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=definition,
+ organization_member=reader.organization_memberships.get(organization=self.organization),
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ event = {
+ "id": str(uuid.uuid4()) if property_type == PropertyDefinition.Type.EVENT else "client-only-event",
+ "event": "$ai_generation",
+ "properties": {
+ "$ai_span_name": "generation",
+ "$ai_input": [{"role": "user", "content": "client-supplied-input"}],
+ },
+ }
+ data = (
+ {
+ "trace": {"id": "client-only-trace", "properties": {"$ai_span_name": "generation"}},
+ "hierarchy": [{"event": event, "children": []}],
+ }
+ if summarize_type == "trace"
+ else {"event": event}
+ )
+ mock_summarize.return_value = SummarizationResponse(
+ title="client-supplied-input", flow_diagram="Start", summary_bullets=[], interesting_notes=[]
+ )
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/llm_analytics/summarization/",
+ {"summarize_type": summarize_type, "data": data},
+ format="json",
+ )
+
+ if property_type == PropertyDefinition.Type.EVENT:
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.data)
+ mock_summarize.assert_not_called()
+ else:
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
+ self.assertIn("client-supplied-input", response.data["text_repr"])
+
@parameterized.expand(
[
(
@@ -501,8 +639,11 @@ class TestSummarizationByID(ClickhouseTestMixin, APIBaseTest):
for fragment in expected:
self.assertIn(fragment, text_repr)
+ @parameterized.expand([("by_id", False), ("restricted_client_data", True)])
@patch("products.ai_observability.backend.api.summarization.summarize")
- def test_summarizes_an_event_predating_the_ai_events_split(self, mock_summarize):
+ def test_summarizes_an_event_predating_the_ai_events_split(
+ self, _name: str, use_client_data: bool, mock_summarize: MagicMock
+ ) -> None:
self._approve_ai_processing()
mock_summarize.return_value = SummarizationResponse(
title="Event Summary",
@@ -512,7 +653,12 @@ class TestSummarizationByID(ClickhouseTestMixin, APIBaseTest):
)
event_uuid = uuid.uuid4()
- timestamp = datetime(2026, 1, 15, 12, 0, tzinfo=UTC)
+ timestamp = datetime.now(UTC) - timedelta(days=45)
+ properties = {
+ "$ai_trace_id": "trace-1",
+ "$ai_input": [{"role": "user", "content": "how do i reset my password"}],
+ "$ai_output_choices": [{"role": "assistant", "content": "private-output"}],
+ }
bulk_create_events(
[
{
@@ -521,22 +667,49 @@ class TestSummarizationByID(ClickhouseTestMixin, APIBaseTest):
"distinct_id": "user-1",
"timestamp": timestamp,
"event_uuid": str(event_uuid),
- "properties": {
- "$ai_trace_id": "trace-1",
- "$ai_input": [{"role": "user", "content": "how do i reset my password"}],
- },
+ "properties": properties,
}
]
)
- response = self.client.post(
- f"/api/environments/{self.team.id}/llm_analytics/summarization/",
- {
+ if use_client_data:
+ reader = self._create_user("[email protected]")
+ self.client.force_login(reader)
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ definition = PropertyDefinition.objects.create(
+ team=self.team, name="$ai_output_choices", type=PropertyDefinition.Type.EVENT
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=definition,
+ organization_member=reader.organization_memberships.get(organization=self.organization),
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ request_data = {
+ "summarize_type": "event",
+ "data": {
+ "event": {
+ "id": str(event_uuid),
+ "event": "$ai_generation",
+ "timestamp": timestamp.isoformat(),
+ "properties": properties,
+ }
+ },
+ }
+ else:
+ request_data = {
"generation_id": str(event_uuid),
"mode": "minimal",
"date_from": (timestamp - timedelta(days=1)).isoformat(),
"date_to": (timestamp + timedelta(days=1)).isoformat(),
- },
+ }
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/llm_analytics/summarization/",
+ request_data,
format="json",
)
@@ -547,6 +720,8 @@ class TestSummarizationByID(ClickhouseTestMixin, APIBaseTest):
else:
self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
self.assertIn("how do i reset my password", response.data["text_repr"].lower())
+ if use_client_data:
+ self.assertNotIn("private-output", response.data["text_repr"])
def test_unknown_event_uuid_is_reported_as_not_found(self):
self._approve_ai_processing()
diff --git a/products/ai_observability/backend/api/test/test_taggers.py b/products/ai_observability/backend/api/test/test_taggers.py
index 10e366f558e2..50239894310d 100644
--- a/products/ai_observability/backend/api/test/test_taggers.py
+++ b/products/ai_observability/backend/api/test/test_taggers.py
@@ -1,15 +1,19 @@
+from datetime import UTC, datetime
from uuid import uuid4
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
-from posthog.models import Organization, OrganizationMembership, Project, Team, User
+from posthog.models import Organization, OrganizationMembership, Project, PropertyDefinition, Team, User
+from posthog.models.event.util import bulk_create_events
+from products.access_control.backend.facade.contracts import PropertyAccessLevel
from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.ai_observability.backend.models.provider_keys import LLMProvider
from products.ai_observability.backend.models.taggers import Tagger, TaggerType
@@ -526,3 +530,49 @@ class TestTaggersAccessControl(APIBaseTest):
)
assert edit_response.status_code == status.HTTP_200_OK
assert edit_response.data["name"] == "Renamed by editor"
+
+
+class TestTaggerPreviewPropertyAccess(ClickhouseTestMixin, APIBaseTest):
+ def test_hog_preview_masks_member_restricted_properties(self) -> None:
+ self.organization.available_product_features = [
+ {"name": AvailableFeature.PROPERTY_ACCESS_CONTROL, "key": AvailableFeature.PROPERTY_ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ reader = self._create_user("[email protected]")
+ definition = PropertyDefinition.objects.create(
+ team=self.team, name="private_note", type=PropertyDefinition.Type.EVENT
+ )
+ PropertyAccessControl.objects.create(
+ team=self.team,
+ property_definition=definition,
+ organization_member=reader.organization_memberships.get(organization=self.organization),
+ access_level=PropertyAccessLevel.NONE.value,
+ )
+ bulk_create_events(
+ [
+ {
+ "event": "$ai_generation",
+ "team": self.team,
+ "distinct_id": "tagger-test-person",
+ "timestamp": datetime.now(UTC),
+ "properties": {"private_note": "private-tagger-input", "public_note": "public-tagger-input"},
+ }
+ ]
+ )
+ with patch("posthog.permissions.posthog_feature_flag_enabled", return_value=True):
+ for user, can_read_private in ((self.user, True), (reader, False)):
+ self.client.force_login(user)
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/taggers/test_hog/",
+ {
+ "source": "print(properties.private_note); print(properties.public_note); return []",
+ "sample_count": 1,
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.data
+ assert len(response.data["results"]) == 1
+ result = response.data["results"][0]
+ assert result["error"] is None
+ assert "public-tagger-input" in result["reasoning"]
+ assert ("private-tagger-input" in result["reasoning"]) is can_read_private
diff --git a/products/ai_observability/backend/summarization/tests/test_utils.py b/products/ai_observability/backend/summarization/tests/test_utils.py
index 1659fa40f4ab..8480502ba8e7 100644
--- a/products/ai_observability/backend/summarization/tests/test_utils.py
+++ b/products/ai_observability/backend/summarization/tests/test_utils.py
@@ -3,7 +3,65 @@ import pytest
from django.template import TemplateDoesNotExist
from django.utils.safestring import SafeString
-from products.ai_observability.backend.summarization.utils import load_summarization_template
+from posthog.hogql.property_access_types import RestrictedProperty
+
+from products.ai_observability.backend.summarization.utils import (
+ get_summarization_lookup_date_range,
+ get_summary_cache_key,
+ load_summarization_template,
+)
+from products.event_definitions.backend.models.property_definition import PropertyDefinition
+
+
+class TestSummarizationLookupDateRange:
+ @pytest.mark.parametrize(
+ "date_from,date_to,expected_from,expected_to",
+ [
+ (None, None, "2026-01-14T12:00:00+00:00", "2026-01-16T12:00:00+00:00"),
+ ("-7d", None, "-7d", "2026-01-16T12:00:00+00:00"),
+ (None, "2026-02-01", "2026-01-14T12:00:00+00:00", "2026-02-01"),
+ ("-7d", "2026-02-01", "-7d", "2026-02-01"),
+ ],
+ )
+ def test_fills_only_missing_bounds_from_event_timestamp(
+ self, date_from: str | None, date_to: str | None, expected_from: str, expected_to: str
+ ) -> None:
+ date_range = get_summarization_lookup_date_range("2026-01-15T12:00:00Z", date_from=date_from, date_to=date_to)
+
+ assert date_range.date_from == expected_from
+ assert date_range.date_to == expected_to
+
+ @pytest.mark.parametrize("timestamp", [None, 42, "not-a-timestamp", "2026-02-30T12:00:00Z", "0001-01-01T12:00:00Z"])
+ def test_invalid_timestamp_preserves_lookup_defaults(self, timestamp: object) -> None:
+ date_range = get_summarization_lookup_date_range(timestamp, date_to="2026-02-01")
+
+ assert date_range.date_from is None
+ assert date_range.date_to == "2026-02-01"
+
+
+class TestSummaryCacheKey:
+ def test_scopes_cache_by_effective_restrictions(self) -> None:
+ unrestricted_key = get_summary_cache_key(1, "trace", "trace-1")
+ assert unrestricted_key == "llm_summary:1:trace:trace-1:minimal:default"
+ assert get_summary_cache_key(1, "trace", "trace-1", restricted_properties=[]) == unrestricted_key
+
+ restrictions = [
+ RestrictedProperty(name="input", property_type=PropertyDefinition.Type.EVENT),
+ RestrictedProperty(name="output", property_type=PropertyDefinition.Type.EVENT),
+ RestrictedProperty(name="input", property_type=PropertyDefinition.Type.PERSON),
+ RestrictedProperty(name="input", property_type=PropertyDefinition.Type.GROUP),
+ RestrictedProperty(name="input", property_type=PropertyDefinition.Type.GROUP, group_type_index=0),
+ RestrictedProperty(name="input", property_type=PropertyDefinition.Type.GROUP, group_type_index=1),
+ ]
+ scoped_keys = {
+ get_summary_cache_key(1, "trace", "trace-1", restricted_properties=[restriction])
+ for restriction in restrictions
+ }
+ assert len(scoped_keys) == len(restrictions)
+ assert unrestricted_key not in scoped_keys
+ assert get_summary_cache_key(
+ 1, "trace", "trace-1", restricted_properties=restrictions
+ ) == get_summary_cache_key(1, "trace", "trace-1", restricted_properties=list(reversed(restrictions)))
class TestLoadSummarizationTemplate:
diff --git a/products/ai_observability/backend/summarization/utils.py b/products/ai_observability/backend/summarization/utils.py
index 24f7a4730a54..65fc39b50108 100644
--- a/products/ai_observability/backend/summarization/utils.py
+++ b/products/ai_observability/backend/summarization/utils.py
@@ -1,8 +1,39 @@
"""Utility functions for summarization."""
+from collections.abc import Collection
+from datetime import timedelta
from pathlib import Path
+from typing import TYPE_CHECKING
from django.template import Context, Engine
+from django.utils.dateparse import parse_datetime
+
+from posthog.schema import DateRange
+
+from products.access_control.backend.facade.property_access import restriction_fingerprint
+
+if TYPE_CHECKING:
+ from posthog.hogql.property_access_types import RestrictedProperty
+
+
+def get_summarization_lookup_date_range(
+ timestamp: object, *, date_from: str | None = None, date_to: str | None = None
+) -> DateRange:
+ date_range = DateRange(date_from=date_from, date_to=date_to)
+ if not isinstance(timestamp, str) or (date_from and date_to):
+ return date_range
+
+ try:
+ parsed_timestamp = parse_datetime(timestamp)
+ if parsed_timestamp is not None:
+ return DateRange(
+ date_from=date_from or (parsed_timestamp - timedelta(days=1)).isoformat(),
+ date_to=date_to or (parsed_timestamp + timedelta(days=1)).isoformat(),
+ )
+ except (ValueError, OverflowError):
+ pass
+
+ return date_range
def get_summary_cache_key(
@@ -11,9 +42,16 @@ def get_summary_cache_key(
entity_id: str,
mode: str = "minimal",
model: str | None = None,
+ *,
+ restricted_properties: Collection["RestrictedProperty"] = (),
) -> str:
model_key = model or "default"
- return f"llm_summary:{team_id}:{summarize_type}:{entity_id}:{mode}:{model_key}"
+ cache_key = f"llm_summary:{team_id}:{summarize_type}:{entity_id}:{mode}:{model_key}"
+ if not restricted_properties:
+ return cache_key
+
+ fingerprint = restriction_fingerprint(restricted_properties)
+ return f"{cache_key}:properties:{fingerprint}"
def load_summarization_template(template_path: str, context: dict) -> str:
diff --git a/products/ai_observability/backend/tools/run_hog_eval.py b/products/ai_observability/backend/tools/run_hog_eval.py
index 0f0837738ed4..3ec893de0557 100644
--- a/products/ai_observability/backend/tools/run_hog_eval.py
+++ b/products/ai_observability/backend/tools/run_hog_eval.py
@@ -186,6 +186,7 @@ class RunHogEvalTestTool(MaxTool):
query=query,
placeholders={},
team=team,
+ user=self._user,
query_type="RunHogEvalTest",
fall_back_to_events=True,
)
@@ -284,6 +285,7 @@ class RunHogEvalTestTool(MaxTool):
trace_results = await database_sync_to_async(run_hog_eval_over_recent_traces)(
team=self._team,
+ user=self._user,
bytecode=bytecode,
condition_filter=None,
sample_count=sample_count,
@@ -312,6 +314,7 @@ class RunHogEvalTestTool(MaxTool):
session_results = await database_sync_to_async(run_hog_eval_over_recent_sessions)(
team=self._team,
+ user=self._user,
bytecode=bytecode,
condition_filter=None,
# Same bound the editor endpoint applies: each sampled session is fetched in full, so
diff --git a/products/ai_observability/backend/tools/test_run_hog_eval.py b/products/ai_observability/backend/tools/test_run_hog_eval.py
index 4e6e2b7d432c..f46e413d2ca9 100644
--- a/products/ai_observability/backend/tools/test_run_hog_eval.py
+++ b/products/ai_observability/backend/tools/test_run_hog_eval.py
@@ -10,6 +10,8 @@ from parameterized import parameterized
from pydantic import ValidationError
from posthog.hogql_queries.ai.utils import HEAVY_COLUMN_NAMES
+from posthog.temporal.ai_observability.run_session_evaluation import SessionHogTestResult
+from posthog.temporal.ai_observability.run_trace_evaluation import TraceHogTestResult
from products.ai_observability.backend.tools.run_hog_eval import RunHogEvalTestArgs, RunHogEvalTestTool
@@ -217,11 +219,9 @@ class TestRunHogEvalTestTool(BaseTest):
assert "Result: true" in result, f"expected true after heavy-merge, got: {result}"
- @patch("posthog.temporal.ai_observability.run_trace_evaluation.run_hog_eval_over_recent_traces")
- def test_trace_target_evaluates_whole_traces(self, mock_run_over_traces):
- from posthog.temporal.ai_observability.run_trace_evaluation import TraceHogTestResult
-
- mock_run_over_traces.return_value = [
+ @parameterized.expand([("trace", "window_seconds"), ("session", "quiet_period_seconds")])
+ def test_target_evaluates_whole_units(self, target: str, period_parameter: str) -> None:
+ sample_result = (
TraceHogTestResult(
trace_id="trace-1",
verdict=True,
@@ -230,20 +230,33 @@ class TestRunHogEvalTestTool(BaseTest):
input_preview="hello",
output_preview="world",
)
- ]
-
- tool = self._make_tool()
- result, artifact = _run_tool(
- tool,
- source="return target.type == 'trace';",
- sample_count=2,
- target="trace",
- window_seconds=120,
+ if target == "trace"
+ else SessionHogTestResult(
+ session_id="session-1",
+ verdict=True,
+ reasoning="looks good",
+ error=None,
+ input_preview="hello",
+ output_preview="world",
+ )
)
+ tool = self._make_tool()
+ with patch(
+ f"posthog.temporal.ai_observability.run_{target}_evaluation.run_hog_eval_over_recent_{target}s",
+ return_value=[sample_result],
+ ) as mock_run_over_units:
+ result, artifact = _run_tool(
+ tool,
+ source=f"return target.type == '{target}';",
+ sample_count=2,
+ target=target,
+ **{period_parameter: 120},
+ )
assert artifact is None
- assert mock_run_over_traces.call_args.kwargs["window_seconds"] == 120
- assert "Trace trace-1" in result
+ assert mock_run_over_units.call_args.kwargs[period_parameter] == 120
+ assert mock_run_over_units.call_args.kwargs["user"] == self.user
+ assert f"{target.capitalize()} {target}-1" in result
assert "Result: true" in result
@patch("products.ai_observability.backend.tools.run_hog_eval.query_ai_events")
@@ -257,6 +270,7 @@ class TestRunHogEvalTestTool(BaseTest):
_run_tool(tool, source="return true;", sample_count=1)
kwargs = mock_query.call_args.kwargs
+ assert kwargs["user"] == self.user
select = kwargs["query"]
assert isinstance(select, ast.SelectQuery)
from_chain = select.select_from.table.chain # type: ignore[union-attr]
diff --git a/products/experiments/backend/session_buckets.py b/products/experiments/backend/session_buckets.py
index aad8afbf6f16..dfb025bd1235 100644
--- a/products/experiments/backend/session_buckets.py
+++ b/products/experiments/backend/session_buckets.py
@@ -65,6 +65,7 @@ from posthog.session_recordings.data_retention import retention_period_in_days
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from posthog.utils import get_safe_cache, safe_cache_set
+from products.access_control.backend.facade.property_access import sort_restricted_properties
from products.access_control.backend.property_access_control import (
get_restricted_properties_with_group_type_index_for_team,
)
@@ -380,13 +381,8 @@ def _restriction_signature(team: Team, user: User) -> str:
"property_type": restriction.property_type,
"group_type_index": restriction.group_type_index,
}
- for restriction in sorted(
- get_restricted_properties_with_group_type_index_for_team(user=user, team=team),
- key=lambda restriction: (
- restriction.name,
- restriction.property_type,
- restriction.group_type_index if restriction.group_type_index is not None else -1,
- ),
+ for restriction in sort_restricted_properties(
+ get_restricted_properties_with_group_type_index_for_team(user=user, team=team)
)
]
)
diff --git a/products/experiments/backend/session_event_deltas.py b/products/experiments/backend/session_event_deltas.py
index 843228859b0e..c6f305dd19c8 100644
--- a/products/experiments/backend/session_event_deltas.py
+++ b/products/experiments/backend/session_event_deltas.py
@@ -132,6 +132,7 @@ from posthog.models.user import User
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from posthog.utils import get_safe_cache, pluralize, safe_cache_set
+from products.access_control.backend.facade.property_access import sort_restricted_properties
from products.access_control.backend.property_access_control import (
get_restricted_properties_with_group_type_index_for_team,
)
@@ -953,13 +954,8 @@ def _cache_key(
"property_type": restriction.property_type,
"group_type_index": restriction.group_type_index,
}
- for restriction in sorted(
- get_restricted_properties_with_group_type_index_for_team(user=user, team=team),
- key=lambda restriction: (
- restriction.name,
- restriction.property_type,
- restriction.group_type_index if restriction.group_type_index is not None else -1,
- ),
+ for restriction in sort_restricted_properties(
+ get_restricted_properties_with_group_type_index_for_team(user=user, team=team)
)
],
]
diff --git a/rust/property-defs-rs/README.md b/rust/property-defs-rs/README.md
index 7a645da32713..3b1ec7e0784f 100644
--- a/rust/property-defs-rs/README.md
+++ b/rust/property-defs-rs/README.md
@@ -13,6 +13,19 @@ Production consumes `team_event_partitioned_events_json`, set via `KAFKA_CONSUME
That topic is produced by a WarpStream Bento pipeline that repartitions `clickhouse_events_json` by team, under the separate `property-defs-rs-ws` consumer group.
The in-code default is `clickhouse_events_json`, which is what a local run gets.
+AI ingestion removes heavy properties such as `$ai_input` from the shared events output.
+Definition discovery must also consume the full `clickhouse_ai_events_json` output, either through the same repartitioning pipeline or through another instance of this service with its own consumer group.
+The payload uses the same event format and creates the same canonical event-property definitions.
+The writer's conflict keys and caches deduplicate ordinary properties received from both streams and preserve existing definition IDs and access rules.
+Never send the full AI payload back to the shared ClickHouse events input to repair discovery.
+
+The local process configuration and Docker Compose configurations run `property-defs-ai` alongside `property-defs-rs`.
+It uses `KAFKA_CONSUMER_TOPIC=clickhouse_ai_events_json` and `KAFKA_CONSUMER_GROUP=property-defs-ai`.
+Hosted installations must include the AI output in their definition-discovery input configuration too; deploying application code alone does not change that configuration.
+
+Enabling the AI input fixes discovery for subsequent events.
+It does not backfill definitions from past events.
+
## Dependencies worth knowing about
- **personhog** resolves group names to group type indexes over gRPC. With `PERSONHOG_ADDR` unset there is no client, resolution fails, and every group property definition is dropped before the write. Definitions for events and non-group properties are unaffected.
diff --git a/rust/property-defs-rs/tests/types.rs b/rust/property-defs-rs/tests/types.rs
index 0ccb210ad8bc..0ac154f9a03e 100644
--- a/rust/property-defs-rs/tests/types.rs
+++ b/rust/property-defs-rs/tests/types.rs
@@ -1,7 +1,8 @@
use chrono::Utc;
use property_defs_rs::types::{
- detect_property_type, floor_last_seen, last_seen_jitter_seed, Event, PropertyValueType, Update,
- DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS, MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS,
+ detect_property_type, floor_last_seen, last_seen_jitter_seed, Event, PropertyParentType,
+ PropertyValueType, Update, DEFAULT_EVENTDEF_LAST_SEEN_FLOOR_SECS,
+ MAX_EVENTDEF_LAST_SEEN_FLOOR_SECS,
};
use rstest::rstest;
use serde_json::{json, Map, Number, Value};
@@ -828,16 +829,22 @@ fn test_groupidentify_emits_zero_event_properties() {
);
}
-#[test]
-fn test_plain_event_properties_still_emitted() {
- let props = json!({
- "page": "/home",
- "referrer": "https://google.com"
- });
+#[rstest]
+#[case("$pageview", json!({"page": "/home", "referrer": "https://example.com"}))]
+#[case("$ai_generation", json!({
+ "$ai_input": [{"role": "user", "content": "A sample question"}],
+ "$ai_output": "A sample answer",
+ "$ai_output_choices": [{"message": {"content": "A sample answer"}}],
+ "$ai_input_state": {"step": 1},
+ "$ai_output_state": {"step": 2},
+ "$ai_tools": [{"name": "sample_tool"}],
+ "$ai_model": "sample-model"
+}))]
+fn test_plain_event_properties_still_emitted(#[case] name: &str, #[case] props: Value) {
let event = Event {
team_id: 1,
project_id: 1,
- event: "$pageview".to_string(),
+ event: name.to_string(),
properties: Some(props.to_string()),
};
@@ -851,13 +858,27 @@ fn test_plain_event_properties_still_emitted() {
})
.collect();
- assert_eq!(
- event_property_keys.len(),
- 2,
- "expected exactly 2 EventProperty updates: {event_property_keys:?}"
- );
- assert!(event_property_keys.contains(&"page"));
- assert!(event_property_keys.contains(&"referrer"));
+ let expected_keys: Vec<&str> = props
+ .as_object()
+ .unwrap()
+ .keys()
+ .map(String::as_str)
+ .collect();
+ assert_eq!(event_property_keys, expected_keys);
+ let definitions: Vec<_> = updates
+ .iter()
+ .filter_map(|update| match update {
+ Update::Property(definition) => Some(definition),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(definitions.len(), expected_keys.len());
+ for definition in definitions {
+ assert!(expected_keys.contains(&definition.name.as_str()));
+ assert_eq!(definition.event_type, PropertyParentType::Event);
+ assert_eq!(definition.group_type_index, None);
+ assert_eq!(definition.project_id, 1);
+ }
}
#[rstest]