Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(query): put the query and its resolved modifiers on the query events (#113498)

Sandy Spicer3b84bdf99bcf
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index e512382b14a5..de0af2485380 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -329,6 +329,9 @@ class QueryRun:
cache_key: str
query_identity: QueryIdentity
+ # The query as the runner received it, serialized as the cache key serializes it (defaults
+ # and None dropped, tags removed), so the events can be queried by what was asked.
+ query: dict[str, Any]
query_id: Optional[str]
execution_mode: ExecutionMode
query_type: str
@@ -342,7 +345,7 @@ class QueryRun:
def elapsed_ms(self) -> float:
return round((perf_counter() - self.start_time) * 1000, 2)
- def event_properties(self) -> dict[str, Any]:
+ def event_properties(self, modifiers: HogQLQueryModifiers) -> dict[str, Any]:
return {
"query_hash": self.query_identity.query_hash,
"runtime_hash": self.query_identity.runtime_hash,
@@ -355,6 +358,11 @@ class QueryRun:
"query_type": self.query_type,
"cache_key": self.cache_key,
"request_trigger": self.trigger,
+ "query": self.query,
+ # The modifiers in effect for the run, set keys only, the same dict the ClickHouse log
+ # comment carries. Passed in rather than stored, because the fresh path adds the user's
+ # modifiers after the cache key, and the event has to say what the run actually used.
+ "modifiers": {k: v for k, v in modifiers.model_dump(mode="json").items() if v is not None},
}
@@ -2402,6 +2410,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
query_run = QueryRun(
cache_key=cache_key,
query_identity=self._query_identity,
+ query=self._query_for_events,
query_id=self.query_id,
execution_mode=execution_mode,
query_type=query_type,
@@ -2651,7 +2660,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
phase_times = compute_phase_times(self.timings.to_dict(), before=self._timings_before_run)
query_executed_props = {
- **query_run.event_properties(),
+ **query_run.event_properties(self.modifiers),
"cache_hit": isinstance(results, self.cached_response_type),
"cache_age_override": self._cache_age_override,
"response_time_ms": query_run.elapsed_ms(),
@@ -2684,7 +2693,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
stats = phase.stats
refused = getattr(error, "served_from_query_failure_cache", False)
query_failed_props = {
- **query_run.event_properties(),
+ **query_run.event_properties(self.modifiers),
"calculation_trigger": query_run.trigger,
"failed_in": phase.name,
"outcome": "refused" if refused else "failed",
@@ -2903,7 +2912,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
self._serve_query_scan(response, query_run.user)
phase_times = compute_phase_times(self.timings.to_dict(), before=self._timings_before_run)
query_executed_props = {
- **query_run.event_properties(),
+ **query_run.event_properties(self.modifiers),
"cache_hit": False,
"last_refresh": last_refresh.isoformat(),
"cache_write_success": stored,
@@ -3180,6 +3189,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):
# Taken from what the key hashes, before the fresh path adds user modifiers, so a hit and a
# fresh run agree, and the payload is built once per run.
self._query_identity = self._query_identity_for(payload, variant)
+ self._query_for_events = payload["query"]
return f"{self._cache_key_for(payload)}{variant}"
def get_cache_key_variant(self) -> str:
diff --git a/posthog/hogql_queries/test/test_query_runner.py b/posthog/hogql_queries/test/test_query_runner.py
index 37be731ade4f..0abac3c4cc73 100644
--- a/posthog/hogql_queries/test/test_query_runner.py
+++ b/posthog/hogql_queries/test/test_query_runner.py
@@ -902,6 +902,8 @@ class TestQueryRunner(BaseTest):
def test_cache_hit_and_fresh_events_carry_one_identity(self) -> None:
runner_class = setup_test_query_runner_class()
+ self.team.modifiers = {"useNewEventsSchema": True}
+ self.team.save()
with (
mock.patch(
"posthog.hogql_queries.query_runner.create_default_modifiers_for_user", side_effect=_add_user_modifier
@@ -909,11 +911,11 @@ class TestQueryRunner(BaseTest):
mock.patch("posthog.hogql_queries.query_runner.report_user_or_team_action") as report,
):
runner_class(query={"some_attr": "bla"}, team=self.team, user=self.user).run(
- execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS
+ execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS, user=self.user
)
fresh_props = report.call_args.args[1]
runner_class(query={"some_attr": "bla"}, team=self.team, user=self.user).run(
- execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE, user=self.user
)
hit_props = report.call_args.args[1]
@@ -927,6 +929,11 @@ class TestQueryRunner(BaseTest):
assert hit_props["direct_connection_source_ids"] is None
assert fresh_props["query_hash"] == hit_props["query_hash"]
assert fresh_props["runtime_hash"] == hit_props["runtime_hash"]
+ assert fresh_props["query"] == hit_props["query"] == {"kind": "TestQuery", "some_attr": "bla"}
+ assert fresh_props["modifiers"]["useNewEventsSchema"] is True
+ assert hit_props["modifiers"]["useNewEventsSchema"] is True
+ assert fresh_props["modifiers"]["typeAwareCastSimplification"] is True
+ assert "typeAwareCastSimplification" not in hit_props["modifiers"]
def test_fresh_event_carries_clickhouse_counters_with_the_scan_flag_off(self) -> None:
TestQueryRunner = self.setup_test_query_runner_class()
@@ -991,6 +998,7 @@ class TestQueryRunner(BaseTest):
assert props["error_type"] == error_class.__name__
assert props["cache_key"] == runner.get_cache_key()
assert props["query_hash"] == runner.get_query_identity().query_hash
+ assert props["query"]["some_attr"] == "bla"
assert props["failed_after_ms"] >= 0
if failed_in == "calculate":
assert (props["clickhouse_rows_read"], props["clickhouse_workload"]) == (90, "ONLINE")