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(insights): stop dropping events that share a timestamp when paginating (#74190)

posthog[bot]51e35eb4befb
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
index b647b3a97e43..9fa1570a5754 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.test.ts
@@ -240,7 +240,7 @@ describe('dataNodeLogic', () => {
nextQuery: setLatestVersionsOnQuery({
kind: NodeKind.EventsQuery,
select: ['*', 'event', 'timestamp'],
- before: '2022-12-24T17:00:41.165000Z',
+ before: '2022-12-24T17:00:41.165000Z|01853a90-ba94-0000-8776-e8df5617c3ec',
limit: 100,
}),
response: partial({ results }),
@@ -269,7 +269,7 @@ describe('dataNodeLogic', () => {
nextQuery: setLatestVersionsOnQuery({
kind: NodeKind.EventsQuery,
select: ['*', 'event', 'timestamp'],
- before: '2022-12-24T17:00:41.165000Z',
+ before: '2022-12-24T17:00:41.165000Z|01853a90-ba94-0000-8776-e8df5617c3ec',
limit: 100,
}),
response: partial({ results }),
@@ -282,7 +282,7 @@ describe('dataNodeLogic', () => {
nextQuery: setLatestVersionsOnQuery({
kind: NodeKind.EventsQuery,
select: ['*', 'event', 'timestamp'],
- before: '2022-12-23T17:00:41.165000Z',
+ before: '2022-12-23T17:00:41.165000Z|new',
limit: 100,
}),
response: partial({ results: [...results, ...results2] }),
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
index 54b2e9c1be29..cc2d8bfd8759 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.ts
@@ -1529,15 +1529,19 @@ export const dataNodeLogic = kea<dataNodeLogicType>([
: (query.orderBy?.[0] ?? 'timestamp DESC')
if (isEventsQuery(query) && sortKey === 'timestamp DESC') {
const typedResults = (response as EventsQueryResponse)?.results
- const sortColumnIndex = query.select
- .map((hql) => removeExpressionComment(hql))
- .indexOf('timestamp')
+ const cleanedColumns = query.select.map((hql) => removeExpressionComment(hql))
+ const sortColumnIndex = cleanedColumns.indexOf('timestamp')
if (sortColumnIndex !== -1) {
- const lastTimestamp = typedResults?.[typedResults.length - 1]?.[sortColumnIndex]
+ const lastRow = typedResults?.[typedResults.length - 1]
+ const lastTimestamp = lastRow?.[sortColumnIndex]
if (lastTimestamp) {
+ // Encode the last row's uuid into the cursor so pagination advances
+ // through events sharing a timestamp instead of dropping the ties past
+ // the page boundary. The backend splits `<timestamp>|<uuid>` back apart.
+ const lastUuid = extractCursorUuid(lastRow, cleanedColumns)
const newQuery: EventsQuery = {
...query,
- before: lastTimestamp,
+ before: lastUuid ? `${lastTimestamp}|${lastUuid}` : lastTimestamp,
limit: Math.max(
100,
Math.min(2 * (typedResults?.length || 100), effectivePaginationLimit)
@@ -2056,3 +2060,23 @@ const dedupeResults = (arr: any[], key: string): any[] => {
}, {})
)
}
+
+// Pull the event uuid out of a result row to use as a stable pagination tiebreaker. It lives either
+// in the expanded `*` column (an object) or in an explicit `uuid` column.
+function extractCursorUuid(row: any[] | undefined, columns: string[]): string | undefined {
+ if (!row) {
+ return undefined
+ }
+ const starIndex = columns.indexOf('*')
+ if (starIndex !== -1) {
+ const starValue = row[starIndex]
+ if (starValue && typeof starValue === 'object' && typeof starValue.uuid === 'string') {
+ return starValue.uuid
+ }
+ }
+ const uuidIndex = columns.indexOf('uuid')
+ if (uuidIndex !== -1 && typeof row[uuidIndex] === 'string') {
+ return row[uuidIndex]
+ }
+ return undefined
+}
diff --git a/posthog/hogql_queries/events_query_runner.py b/posthog/hogql_queries/events_query_runner.py
index d57acce8921c..5461c90caa4d 100644
--- a/posthog/hogql_queries/events_query_runner.py
+++ b/posthog/hogql_queries/events_query_runner.py
@@ -56,6 +56,19 @@ SELECT_STAR_FROM_EVENTS_FIELDS = [
# Wide columns that defeat presorted optimization
WIDE_COLUMNS = {"elements_chain", "properties"}
+# Pagination cursors are encoded as ``<timestamp>|<uuid>`` so a stable uuid tiebreaker can advance
+# past events that share the boundary timestamp instead of dropping every tied row beyond the page
+# limit (which happens with a plain exclusive ``timestamp <`` filter). Coarse-precision sources such
+# as bulk imports routinely land hundreds of events on the same second, so ties are not rare there.
+CURSOR_DELIMITER = "|"
+
+
+def split_pagination_cursor(value: str) -> tuple[str, str | None]:
+ """Split a ``<timestamp>|<uuid>`` cursor. Plain user-supplied date filters have no delimiter and
+ pass through unchanged with a ``None`` tiebreaker."""
+ timestamp, delimiter, uuid = value.partition(CURSOR_DELIMITER)
+ return timestamp, (uuid if delimiter else None)
+
class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
query: EventsQuery
@@ -131,9 +144,9 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
return True
def apply_pagination_cursor(self, cursor: str) -> None:
- # NB: This uses the last row's timestamp as the cursor, so events sharing
- # the exact same timestamp as the page boundary may be skipped. In practice
- # this is rare since the events table uses DateTime64(6) (microsecond precision).
+ # The cursor is a ``<timestamp>|<uuid>`` pair (see ``split_pagination_cursor``); ``to_query``
+ # turns it into a timestamp filter with a uuid tiebreaker so events sharing the boundary
+ # timestamp are not skipped. Bare-timestamp cursors from older clients still work.
order: str = "DESC"
if self.query.orderBy:
order = parse_order_expr(self.query.orderBy[0]).order
@@ -160,6 +173,17 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
return val.isoformat()
return str(val)
+ def _extract_last_uuid(self, row: list) -> str | None:
+ select_input = self.select_input_raw()
+ if "*" in select_input:
+ star_idx = select_input.index("*")
+ if isinstance(row[star_idx], dict) and row[star_idx].get("uuid") is not None:
+ return str(row[star_idx]["uuid"])
+ for i, col in enumerate(select_input):
+ if col.split("--")[0].strip() == "uuid" and row[i] is not None:
+ return str(row[i])
+ return None
+
def _raise_on_restricted_property_select(self, select: list[ast.Expr]) -> None:
# User-authored ``select`` entries that explicitly reference a restricted event or person
# property must fail loudly — the printer's silent JSONDropKeys strip would otherwise turn
@@ -298,27 +322,57 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
with self.timings.measure("timestamps"):
# prevent accidentally future events from being visible by default
before = self.query.before or (now() + timedelta(seconds=5)).isoformat()
- parsed_date = relative_date_parse(before, self.team.timezone_info)
- where_exprs.append(
- parse_expr(
- "timestamp < {timestamp}",
- {"timestamp": ast.Constant(value=parsed_date)},
- timings=self.timings,
+ before_timestamp, before_uuid = split_pagination_cursor(before)
+ parsed_date = relative_date_parse(before_timestamp, self.team.timezone_info)
+ if before_uuid:
+ # Advance past events sharing the boundary timestamp using uuid as a tiebreaker,
+ # matching the ``timestamp DESC, uuid DESC`` ordering applied below.
+ where_exprs.append(
+ parse_expr(
+ "timestamp < {before} OR (timestamp = {before_eq} AND uuid < {before_uuid})",
+ {
+ "before": ast.Constant(value=parsed_date),
+ "before_eq": ast.Constant(value=parsed_date),
+ "before_uuid": ast.Call(name="toUUID", args=[ast.Constant(value=before_uuid)]),
+ },
+ timings=self.timings,
+ )
)
- )
-
- # limit to the last 24h by default
- after = self.query.after or "-24h"
- if after != "all":
- parsed_date = relative_date_parse(after, self.team.timezone_info)
+ else:
where_exprs.append(
parse_expr(
- "timestamp > {timestamp}",
+ "timestamp < {timestamp}",
{"timestamp": ast.Constant(value=parsed_date)},
timings=self.timings,
)
)
+ # limit to the last 24h by default
+ after = self.query.after or "-24h"
+ if after != "all":
+ after_timestamp, after_uuid = split_pagination_cursor(after)
+ parsed_date = relative_date_parse(after_timestamp, self.team.timezone_info)
+ if after_uuid:
+ where_exprs.append(
+ parse_expr(
+ "timestamp > {after} OR (timestamp = {after_eq} AND uuid > {after_uuid})",
+ {
+ "after": ast.Constant(value=parsed_date),
+ "after_eq": ast.Constant(value=parsed_date),
+ "after_uuid": ast.Call(name="toUUID", args=[ast.Constant(value=after_uuid)]),
+ },
+ timings=self.timings,
+ )
+ )
+ else:
+ where_exprs.append(
+ parse_expr(
+ "timestamp > {timestamp}",
+ {"timestamp": ast.Constant(value=parsed_date)},
+ timings=self.timings,
+ )
+ )
+
# where & having
with self.timings.measure("where"):
where_list = [expr for expr in where_exprs if not has_aggregation(expr)]
@@ -361,6 +415,14 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
and first_order.chain == ["timestamp"]
)
+ # When ordering by timestamp, append uuid as a stable secondary sort so the ordering
+ # is total. Ties on timestamp would otherwise be arbitrary and shift between pages,
+ # which is what lets cursor pagination silently skip events sharing a timestamp.
+ if self._cursor_eligible and not any(
+ isinstance(o.expr, ast.Field) and o.expr.chain == ["uuid"] for o in order_by
+ ):
+ order_by.append(ast.OrderExpr(expr=ast.Field(chain=["uuid"]), order=order_by[0].order))
+
with self.timings.measure("select"):
if self.query.source is not None:
# Kludge: If the events_query has logic in select that the where clauses depends on, this will potentially error.
@@ -519,7 +581,10 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
next_cursor = None
if self._cursor_eligible and self.paginator.has_more() and self.paginator.results:
last_row = self.paginator.results[-1]
- next_cursor = self._extract_last_timestamp(last_row)
+ last_timestamp = self._extract_last_timestamp(last_row)
+ if last_timestamp is not None:
+ last_uuid = self._extract_last_uuid(last_row)
+ next_cursor = f"{last_timestamp}{CURSOR_DELIMITER}{last_uuid}" if last_uuid else last_timestamp
return EventsQueryResponse(
results=self.paginator.results,
@@ -576,8 +641,11 @@ class EventsQueryRunner(AnalyticsQueryRunner[EventsQueryResponse]):
# Use the date range from the query to optimize the search
after = self.query.after or "-24h"
before = self.query.before or (now() + timedelta(seconds=5)).isoformat()
- date_from = relative_date_parse(after, self.team.timezone_info) if after != "all" else None
- date_to = relative_date_parse(before, self.team.timezone_info)
+ # before/after may carry a `<timestamp>|<uuid>` pagination cursor — only the timestamp matters here.
+ after_timestamp = split_pagination_cursor(after)[0]
+ before_timestamp = split_pagination_cursor(before)[0]
+ date_from = relative_date_parse(after_timestamp, self.team.timezone_info) if after != "all" else None
+ date_to = relative_date_parse(before_timestamp, self.team.timezone_info)
where_conditions: list[ast.Expr] = [
ast.CompareOperation(
diff --git a/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr b/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr
index 502f2ee0e21b..c81e50e31e76 100644
--- a/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr
+++ b/posthog/hogql_queries/test/__snapshots__/test_events_query_runner.ambr
@@ -7,9 +7,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), equals(events.event, '$pageview'), less(events.timestamp, toDateTime64('2020-01-12 23:59:59.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-12 00:00:00.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 101)), and(equals(events.event, '$pageview'), less(events.timestamp, toDateTime64('2020-01-12 23:59:59.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-12 00:00:00.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 101
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -162,9 +162,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 3)), and(less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 3
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -189,9 +189,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-11 12:00:02.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 3)), and(less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-11 12:00:02.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 3
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -216,9 +216,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-11 12:00:04.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 3)), and(less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-11 12:00:04.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 3
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -324,9 +324,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.uuid DESC
LIMIT 3)), and(less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.uuid DESC
LIMIT 3
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -351,9 +351,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), less(events.timestamp, toDateTime64('2020-01-11 12:00:04.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.uuid DESC
LIMIT 3)), and(less(events.timestamp, toDateTime64('2020-01-11 12:00:04.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.uuid DESC
LIMIT 3
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -378,9 +378,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), less(events.timestamp, toDateTime64('2020-01-11 12:00:02.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.uuid DESC
LIMIT 3)), and(less(events.timestamp, toDateTime64('2020-01-11 12:00:02.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.uuid DESC
LIMIT 3
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -485,9 +485,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.uuid DESC
LIMIT 3)), and(less(events.timestamp, toDateTime64('2020-01-12 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2020-01-10 00:00:00.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.uuid DESC
LIMIT 3
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -539,9 +539,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), notILike(toString(events.elements_chain), '%div%'), equals(events.event, '$autocapture'), less(events.timestamp, toDateTime64('2021-01-21 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2021-01-20 00:00:00.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 101)), and(notILike(toString(events.elements_chain), '%div%'), equals(events.event, '$autocapture'), less(events.timestamp, toDateTime64('2021-01-21 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2021-01-20 00:00:00.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 101
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -593,9 +593,9 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'some_prop'), ''), 'null'), '^"|"$', ''), 'a'), 0), equals(events.event, '$pageview'), less(events.timestamp, toDateTime64('2021-01-21 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2021-01-14 00:00:00.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 101)), and(ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'some_prop'), ''), 'null'), '^"|"$', ''), 'a'), 0), equals(events.event, '$pageview'), less(events.timestamp, toDateTime64('2021-01-21 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2021-01-14 00:00:00.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') ASC, events.uuid ASC
LIMIT 101
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
@@ -647,9 +647,10 @@
(SELECT events.uuid AS uuid
FROM events
WHERE and(equals(events.team_id, 99999), equals(events.event, '$pageview'), less(events.timestamp, toDateTime64('2021-01-21 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2021-01-14 00:00:00.000000', 6, 'UTC')))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.event ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.event ASC, events.uuid DESC
LIMIT 101)), and(equals(events.event, '$pageview'), less(events.timestamp, toDateTime64('2021-01-21 00:00:05.000000', 6, 'UTC')), greater(events.timestamp, toDateTime64('2021-01-14 00:00:00.000000', 6, 'UTC'))))
- ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.event ASC
+ ORDER BY toTimeZone(events.timestamp, 'UTC') DESC, events.event ASC,
+ events.uuid DESC
LIMIT 101
OFFSET 0 SETTINGS readonly=2,
max_execution_time=60,
diff --git a/posthog/hogql_queries/test/test_events_query_runner.py b/posthog/hogql_queries/test/test_events_query_runner.py
index 69119e91cfc4..7800f4f68e5d 100644
--- a/posthog/hogql_queries/test/test_events_query_runner.py
+++ b/posthog/hogql_queries/test/test_events_query_runner.py
@@ -37,10 +37,13 @@ from products.access_control.backend.property_access_control import PropertyAcce
class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
maxDiff = None
- def _create_events(self, data: list[tuple[str, str, Any]], event="$pageview"):
+ def _create_events(self, data: list[tuple], event="$pageview"):
person_result = []
distinct_ids_handled = set()
- for distinct_id, timestamp, event_properties in data:
+ for row in data:
+ distinct_id, timestamp, event_properties = row[0], row[1], row[2]
+ # Optional 4th element pins the event uuid so cursor-pagination SQL stays deterministic.
+ event_uuid = row[3] if len(row) > 3 else None
with freeze_time(timestamp):
if distinct_id not in distinct_ids_handled:
person_result.append(
@@ -53,13 +56,16 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
)
distinct_ids_handled.add(distinct_id)
- _create_event(
- team=self.team,
- event=event,
- distinct_id=distinct_id,
- timestamp=timestamp,
- properties=event_properties,
- )
+ create_kwargs: dict[str, Any] = {
+ "team": self.team,
+ "event": event,
+ "distinct_id": distinct_id,
+ "timestamp": timestamp,
+ "properties": event_properties,
+ }
+ if event_uuid is not None:
+ create_kwargs["event_uuid"] = event_uuid
+ _create_event(**create_kwargs)
return person_result
def _create_boolean_field_test_events(self):
@@ -972,11 +978,11 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_cursor_pagination_multi_page_desc(self):
self._create_events(
data=[
- ("p1", "2020-01-11T12:00:05Z", {"idx": "5"}),
- ("p1", "2020-01-11T12:00:04Z", {"idx": "4"}),
- ("p1", "2020-01-11T12:00:03Z", {"idx": "3"}),
- ("p1", "2020-01-11T12:00:02Z", {"idx": "2"}),
- ("p1", "2020-01-11T12:00:01Z", {"idx": "1"}),
+ ("p1", "2020-01-11T12:00:05Z", {"idx": "5"}, "00000000-0000-0000-0000-000000000005"),
+ ("p1", "2020-01-11T12:00:04Z", {"idx": "4"}, "00000000-0000-0000-0000-000000000004"),
+ ("p1", "2020-01-11T12:00:03Z", {"idx": "3"}, "00000000-0000-0000-0000-000000000003"),
+ ("p1", "2020-01-11T12:00:02Z", {"idx": "2"}, "00000000-0000-0000-0000-000000000002"),
+ ("p1", "2020-01-11T12:00:01Z", {"idx": "1"}, "00000000-0000-0000-0000-000000000001"),
]
)
@@ -1012,11 +1018,11 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
def test_cursor_pagination_multi_page_asc(self):
self._create_events(
data=[
- ("p1", "2020-01-11T12:00:01Z", {"idx": "1"}),
- ("p1", "2020-01-11T12:00:02Z", {"idx": "2"}),
- ("p1", "2020-01-11T12:00:03Z", {"idx": "3"}),
- ("p1", "2020-01-11T12:00:04Z", {"idx": "4"}),
- ("p1", "2020-01-11T12:00:05Z", {"idx": "5"}),
+ ("p1", "2020-01-11T12:00:01Z", {"idx": "1"}, "00000000-0000-0000-0000-000000000001"),
+ ("p1", "2020-01-11T12:00:02Z", {"idx": "2"}, "00000000-0000-0000-0000-000000000002"),
+ ("p1", "2020-01-11T12:00:03Z", {"idx": "3"}, "00000000-0000-0000-0000-000000000003"),
+ ("p1", "2020-01-11T12:00:04Z", {"idx": "4"}, "00000000-0000-0000-0000-000000000004"),
+ ("p1", "2020-01-11T12:00:05Z", {"idx": "5"}, "00000000-0000-0000-0000-000000000005"),
]
)
@@ -1119,7 +1125,46 @@ class TestEventsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert isinstance(response, CachedEventsQueryResponse)
assert response.nextCursor is not None
- self.assertEqual(datetime.fromisoformat(response.nextCursor), datetime.fromisoformat("2020-01-11T12:00:02Z"))
+ cursor_timestamp = response.nextCursor.split("|")[0]
+ self.assertEqual(datetime.fromisoformat(cursor_timestamp), datetime.fromisoformat("2020-01-11T12:00:02Z"))
+
+ def test_cursor_pagination_advances_through_identical_timestamps(self):
+ # Bulk imports (e.g. Amplitude) land many events on the same second. An exclusive
+ # `timestamp <` cursor drops every tied event past the page limit; the uuid tiebreaker
+ # must page through all of them exactly once.
+ shared_timestamp = "2020-01-11T12:00:00Z"
+ self._create_events(
+ data=[
+ ("p1", shared_timestamp, {"idx": str(i)}, f"00000000-0000-0000-0000-00000000000{i}")
+ for i in range(1, 6)
+ ]
+ )
+
+ all_indices: list[str] = []
+ cursor = None
+ for _ in range(5):
+ with freeze_time("2020-01-12"):
+ query = EventsQuery(
+ kind="EventsQuery",
+ select=["uuid", "properties.idx", "timestamp"],
+ after="2020-01-10",
+ orderBy=["timestamp DESC"],
+ limit=2,
+ )
+ runner = EventsQueryRunner(query=query, team=self.team)
+ if cursor:
+ runner.apply_pagination_cursor(cursor)
+ response = runner.run()
+
+ assert isinstance(response, CachedEventsQueryResponse)
+ all_indices.extend(row[1] for row in response.results)
+
+ if response.nextCursor:
+ cursor = response.nextCursor
+ else:
+ break
+
+ self.assertEqual(sorted(all_indices), ["1", "2", "3", "4", "5"])
def test_action_steps_filters_events(self):
self._create_events(