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.

perf(error-tracking): fetch first/last events with a two-pass point lookup (#62804)

Catalin Irimiea498fb5f085e
diff --git a/posthog/test/base.py b/posthog/test/base.py
index bbea782004f1..b8cfce90d5b9 100644
--- a/posthog/test/base.py
+++ b/posthog/test/base.py
@@ -270,6 +270,13 @@ def clean_varying_query_parts(query, replace_all_numbers):
query = re.sub(r"flag_\d+_condition", r"flag_X_condition", query)
query = re.sub(r"flag_\d+_super_condition", r"flag_X_super_condition", query)
+ # event uuid point lookups (error tracking first/last event fetch) embed random fixture uuids
+ query = re.sub(
+ r"in\(((?:\w+\.)?uuid), \['[0-9a-f-]{36}'(?:, '[0-9a-f-]{36}')*\]\)",
+ r"in(\1, ['00000000-0000-0000-0000-000000000000' /* ... */])",
+ query,
+ )
+
# session_recording_linked_flag embeds feature flag IDs in JSON, normalize them
query = re.sub(
r"""session_recording_linked_flag" @> '{"id": \d+}'::jsonb""",
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py
index fc11c638a2af..397d77c524f6 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner.py
@@ -7,6 +7,8 @@ from posthog.hogql import ast
from posthog.hogql.constants import LimitContext
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.schema.error_tracking_fingerprint_issue_state import PENDING_UPDATES_HOGQL_CONTEXT_KEY
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
@@ -102,13 +104,66 @@ class ErrorTrackingQueryRunner(AnalyticsQueryRunner[ErrorTrackingQueryResponse])
context=self._hogql_context(),
)
- columns: list[str] = query_result.columns or []
+ columns, results = self._attach_events(query_result.columns or [], query_result.results)
return ErrorTrackingQueryResponse(
columns=columns,
- results=self._builder.process_results(columns, query_result.results),
+ results=self._builder.process_results(columns, results),
timings=query_result.timings,
hogql=query_result.hogql,
modifiers=self.modifiers,
**self.paginator.response_params(),
)
+
+ # Aggregation queries return only event uuids for first/last event (reading the
+ # properties blob inside argMin/argMax decompresses every matching event's blob);
+ # the payloads are fetched here with a point lookup over just the selected uuids.
+ EVENT_UUID_COLUMNS = {"first_event_uuid": "first_event", "last_event_uuid": "last_event"}
+
+ def _attach_events(self, columns: list[str], results: list) -> tuple[list[str], list]:
+ uuid_indexes = [index for index, column in enumerate(columns) if column in self.EVENT_UUID_COLUMNS]
+ if not uuid_indexes:
+ return columns, results
+
+ uuids = {str(row[index]) for row in results for index in uuid_indexes if row[index] is not None}
+ events: dict[str, tuple] = {}
+ if uuids:
+ with self.timings.measure("error_tracking_query_event_fetch"):
+ event_result = execute_hogql_query(
+ query=parse_select(
+ # The explicit LIMIT matters: without one, execute_hogql_query applies
+ # the default 100-row limit and silently drops payloads beyond it.
+ """
+ SELECT uuid, distinct_id, timestamp, properties
+ FROM events
+ WHERE event = '$exception'
+ AND uuid IN {uuids}
+ AND timestamp >= toDateTime({date_from})
+ AND timestamp <= toDateTime({date_to})
+ LIMIT 1 BY uuid
+ LIMIT {event_limit}
+ """,
+ placeholders={
+ "uuids": ast.Constant(value=sorted(uuids)),
+ "date_from": ast.Constant(value=self.date_from),
+ "date_to": ast.Constant(value=self.date_to),
+ "event_limit": ast.Constant(value=len(uuids)),
+ },
+ ),
+ team=self.team,
+ query_type="ErrorTrackingEventFetchQuery",
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ user=self.user,
+ )
+ events = {str(row[0]): row for row in event_result.results}
+
+ new_columns = [self.EVENT_UUID_COLUMNS.get(column, column) for column in columns]
+ new_results = []
+ for row in results:
+ row = list(row)
+ for index in uuid_indexes:
+ row[index] = events.get(str(row[index])) if row[index] is not None else None
+ new_results.append(row)
+ return new_columns, new_results
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.py
index 2e4eeb8215cd..2824cc63e21a 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_utils.py
@@ -175,45 +175,22 @@ def build_select_expressions(
]
)
+ # Only the uuid is aggregated here; the runner fetches the selected events' properties
+ # in a second point lookup. Aggregating the tuple directly would decompress every
+ # matching event's properties blob just to keep one row per issue.
if query.withFirstEvent:
exprs.append(
ast.Alias(
- alias="first_event",
- expr=ast.Call(
- name="argMin",
- args=[
- ast.Tuple(
- exprs=[
- ast.Field(chain=["uuid"]),
- ast.Field(chain=["distinct_id"]),
- ast.Field(chain=["timestamp"]),
- ast.Field(chain=["properties"]),
- ]
- ),
- ast.Field(chain=["timestamp"]),
- ],
- ),
+ alias="first_event_uuid",
+ expr=ast.Call(name="argMin", args=[ast.Field(chain=["uuid"]), ast.Field(chain=["timestamp"])]),
)
)
if query.withLastEvent:
exprs.append(
ast.Alias(
- alias="last_event",
- expr=ast.Call(
- name="argMax",
- args=[
- ast.Tuple(
- exprs=[
- ast.Field(chain=["uuid"]),
- ast.Field(chain=["distinct_id"]),
- ast.Field(chain=["timestamp"]),
- ast.Field(chain=["properties"]),
- ]
- ),
- ast.Field(chain=["timestamp"]),
- ],
- ),
+ alias="last_event_uuid",
+ expr=ast.Call(name="argMax", args=[ast.Field(chain=["uuid"]), ast.Field(chain=["timestamp"])]),
)
)
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v2.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v2.py
index a73689d39f03..600794532aea 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v2.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v2.py
@@ -223,10 +223,10 @@ class ErrorTrackingQueryV2Builder:
)
if self.query.withFirstEvent:
- exprs.append(ast.Alias(alias="first_event", expr=from_agg("first_event")))
+ exprs.append(ast.Alias(alias="first_event_uuid", expr=from_agg("first_event_uuid")))
if self.query.withLastEvent:
- exprs.append(ast.Alias(alias="last_event", expr=from_agg("last_event")))
+ exprs.append(ast.Alias(alias="last_event_uuid", expr=from_agg("last_event_uuid")))
exprs.append(ast.Alias(alias="library", expr=from_agg("library")))
diff --git a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v3.py b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v3.py
index 3bba8a90e70b..75f74a78f361 100644
--- a/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v3.py
+++ b/products/error_tracking/backend/hogql_queries/error_tracking_query_runner_v3.py
@@ -302,24 +302,17 @@ class ErrorTrackingQueryV3Builder:
)
)
+ # Only the uuid is aggregated here; the runner fetches the selected events' properties
+ # in a second point lookup. Aggregating the tuple directly would decompress every
+ # matching event's properties blob just to keep one row per fingerprint.
if self.query.withFirstEvent:
exprs.append(
ast.Alias(
- alias="first_event_state",
+ alias="first_event_uuid_state",
expr=_state(
ast.Call(
name="argMin",
- args=[
- ast.Tuple(
- exprs=[
- ast.Field(chain=["e", "uuid"]),
- ast.Field(chain=["e", "distinct_id"]),
- ast.Field(chain=["e", "timestamp"]),
- ast.Field(chain=["e", "properties"]),
- ]
- ),
- ast.Field(chain=["e", "timestamp"]),
- ],
+ args=[ast.Field(chain=["e", "uuid"]), ast.Field(chain=["e", "timestamp"])],
)
),
)
@@ -328,21 +321,11 @@ class ErrorTrackingQueryV3Builder:
if self.query.withLastEvent:
exprs.append(
ast.Alias(
- alias="last_event_state",
+ alias="last_event_uuid_state",
expr=_state(
ast.Call(
name="argMax",
- args=[
- ast.Tuple(
- exprs=[
- ast.Field(chain=["e", "uuid"]),
- ast.Field(chain=["e", "distinct_id"]),
- ast.Field(chain=["e", "timestamp"]),
- ast.Field(chain=["e", "properties"]),
- ]
- ),
- ast.Field(chain=["e", "timestamp"]),
- ],
+ args=[ast.Field(chain=["e", "uuid"]), ast.Field(chain=["e", "timestamp"])],
)
),
)
@@ -455,10 +438,10 @@ class ErrorTrackingQueryV3Builder:
)
if self.query.withFirstEvent:
- exprs.append(ast.Alias(alias="first_event", expr=_merge("first_event_state", "argMin")))
+ exprs.append(ast.Alias(alias="first_event_uuid", expr=_merge("first_event_uuid_state", "argMin")))
if self.query.withLastEvent:
- exprs.append(ast.Alias(alias="last_event", expr=_merge("last_event_state", "argMax")))
+ exprs.append(ast.Alias(alias="last_event_uuid", expr=_merge("last_event_uuid_state", "argMax")))
exprs.append(ast.Alias(alias="library", expr=_merge("library_state", "argMax")))
@@ -595,23 +578,13 @@ class ErrorTrackingQueryV3Builder:
)
)
+ # uuid-only here too — the runner attaches the event payloads in a second point lookup.
if self.query.withFirstEvent:
exprs.append(
ast.Alias(
- alias="first_event",
+ alias="first_event_uuid",
expr=ast.Call(
- name="argMin",
- args=[
- ast.Tuple(
- exprs=[
- ast.Field(chain=["e", "uuid"]),
- ast.Field(chain=["e", "distinct_id"]),
- ast.Field(chain=["e", "timestamp"]),
- ast.Field(chain=["e", "properties"]),
- ]
- ),
- ast.Field(chain=["e", "timestamp"]),
- ],
+ name="argMin", args=[ast.Field(chain=["e", "uuid"]), ast.Field(chain=["e", "timestamp"])]
),
)
)
@@ -619,20 +592,9 @@ class ErrorTrackingQueryV3Builder:
if self.query.withLastEvent:
exprs.append(
ast.Alias(
- alias="last_event",
+ alias="last_event_uuid",
expr=ast.Call(
- name="argMax",
- args=[
- ast.Tuple(
- exprs=[
- ast.Field(chain=["e", "uuid"]),
- ast.Field(chain=["e", "distinct_id"]),
- ast.Field(chain=["e", "timestamp"]),
- ast.Field(chain=["e", "properties"]),
- ]
- ),
- ast.Field(chain=["e", "timestamp"]),
- ],
+ name="argMax", args=[ast.Field(chain=["e", "uuid"]), ast.Field(chain=["e", "timestamp"])]
),
)
)
diff --git a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.ambr b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.ambr
index 1f18f1c642a9..f4e68e3cb684 100644
--- a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.ambr
+++ b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner.ambr
@@ -85,7 +85,7 @@
min(toTimeZone(e.timestamp, 'UTC')) AS first_seen,
argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$exception_functions', -1), ''), 'null'), '^"|"$', ''), toTimeZone(e.timestamp, 'UTC')) AS function,
argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$exception_sources', -1), ''), 'null'), '^"|"$', ''), toTimeZone(e.timestamp, 'UTC')) AS source,
- argMin(tuple(e.uuid, e.distinct_id, toTimeZone(e.timestamp, 'UTC'), e.properties), toTimeZone(e.timestamp, 'UTC')) AS first_event,
+ argMin(e.uuid, toTimeZone(e.timestamp, 'UTC')) AS first_event_uuid,
argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$lib'), ''), 'null'), '^"|"$', ''), toTimeZone(e.timestamp, 'UTC')) AS library
FROM events AS e
LEFT OUTER JOIN
@@ -114,6 +114,29 @@
'''
# ---
# name: TestErrorTrackingQueryRunner.test_column_names.3
+ '''
+ SELECT events.uuid AS uuid,
+ events.distinct_id AS distinct_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.properties AS properties
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.event, '$exception'), in(events.uuid, ['00000000-0000-0000-0000-000000000000' /* ... */]), greaterOrEquals(events.timestamp, toDateTime(toDateTime64('2018-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(events.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')))
+ LIMIT 1 BY events.uuid
+ LIMIT 3 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestErrorTrackingQueryRunner.test_column_names.4
'''
SELECT if(not(empty(e__exception_issue_override.issue_id)), e__exception_issue_override.issue_id, accurateCastOrNull(e.`mat_$exception_issue_id`, 'UUID')) AS id,
max(toTimeZone(e.timestamp, 'UTC')) AS last_seen,
@@ -124,7 +147,7 @@
count(DISTINCT nullIf(e.`$session_id`, '')) AS sessions,
count(DISTINCT coalesce(nullIf(toString(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)), '00000000-0000-0000-0000-000000000000'), e.distinct_id)) AS users,
sumForEach(arrayMap(bin -> if(and(greater(toTimeZone(e.timestamp, 'UTC'), bin), lessOrEquals(dateDiff('seconds', bin, toTimeZone(e.timestamp, 'UTC')), divide(dateDiff('seconds', toDateTime(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), 'UTC'), toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), 1))), 1, 0), arrayMap(i -> dateAdd(toDateTime(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), 'UTC'), toIntervalSecond(multiply(i, divide(dateDiff('seconds', toDateTime(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), 'UTC'), toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')), 1)))), range(0, 1)))) AS volumeRange,
- argMin(tuple(e.uuid, e.distinct_id, toTimeZone(e.timestamp, 'UTC'), e.properties), toTimeZone(e.timestamp, 'UTC')) AS first_event,
+ argMin(e.uuid, toTimeZone(e.timestamp, 'UTC')) AS first_event_uuid,
argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$lib'), ''), 'null'), '^"|"$', ''), toTimeZone(e.timestamp, 'UTC')) AS library
FROM events AS e
LEFT OUTER JOIN
@@ -159,6 +182,29 @@
use_hive_partitioning=0
'''
# ---
+# name: TestErrorTrackingQueryRunner.test_column_names.5
+ '''
+ SELECT events.uuid AS uuid,
+ events.distinct_id AS distinct_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.properties AS properties
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.event, '$exception'), in(events.uuid, ['00000000-0000-0000-0000-000000000000' /* ... */]), greaterOrEquals(events.timestamp, toDateTime(toDateTime64('2018-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(events.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')))
+ LIMIT 1 BY events.uuid
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestErrorTrackingQueryRunner.test_correctly_counts_persons
'''
SELECT if(not(empty(e__exception_issue_override.issue_id)), e__exception_issue_override.issue_id, accurateCastOrNull(e.`mat_$exception_issue_id`, 'UUID')) AS id,
diff --git a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v2.ambr b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v2.ambr
index 821d04bd847d..8376d613a9a1 100644
--- a/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v2.ambr
+++ b/products/error_tracking/backend/hogql_queries/test/__snapshots__/test_error_tracking_query_runner_v2.ambr
@@ -204,7 +204,7 @@
assignment.role_id AS assignee_role_id,
agg.function AS function,
agg.source AS source,
- agg.first_event AS first_event,
+ agg.first_event_uuid AS first_event_uuid,
agg.library AS library
FROM
(SELECT if(not(empty(e__exception_issue_override.issue_id)), e__exception_issue_override.issue_id, accurateCastOrNull(e.`mat_$exception_issue_id`, 'UUID')) AS id,
@@ -212,7 +212,7 @@
min(toTimeZone(e.timestamp, 'UTC')) AS first_seen,
argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$exception_functions', -1), ''), 'null'), '^"|"$', ''), toTimeZone(e.timestamp, 'UTC')) AS function,
argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$exception_sources', -1), ''), 'null'), '^"|"$', ''), toTimeZone(e.timestamp, 'UTC')) AS source,
- argMin(tuple(e.uuid, e.distinct_id, toTimeZone(e.timestamp, 'UTC'), e.properties), toTimeZone(e.timestamp, 'UTC')) AS first_event,
+ argMin(e.uuid, toTimeZone(e.timestamp, 'UTC')) AS first_event_uuid,
argMax(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$lib'), ''), 'null'), '^"|"$', ''), toTimeZone(e.timestamp, 'UTC')) AS library
FROM events AS e
LEFT OUTER JOIN
@@ -265,6 +265,29 @@
use_hive_partitioning=0
'''
# ---
+# name: TestErrorTrackingQueryRunnerV2.test_column_names.3
+ '''
+ SELECT events.uuid AS uuid,
+ events.distinct_id AS distinct_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.properties AS properties
+ FROM events
+ WHERE and(equals(events.team_id, 99999), equals(events.event, '$exception'), in(events.uuid, ['00000000-0000-0000-0000-000000000000' /* ... */]), greaterOrEquals(events.timestamp, toDateTime(toDateTime64('2018-01-11 12:11:00.000000', 6, 'UTC'), 'UTC')), lessOrEquals(events.timestamp, toDateTime(toDateTime64('today', 6, 'UTC'), 'UTC')))
+ LIMIT 1 BY events.uuid
+ LIMIT 3 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestErrorTrackingQueryRunnerV2.test_correctly_counts_persons
'''
WITH issue_ids AS