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(conversations): keep SLA sort stable across ticket list pages (#73870)

Christian Raffertyd880aafb2212
diff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.py
index eb256740e0e8..7650d128a8b2 100644
--- a/products/conversations/backend/api/tests/test_tickets.py
+++ b/products/conversations/backend/api/tests/test_tickets.py
@@ -546,6 +546,40 @@ class TestTicketAPI(APIBaseTest):
self.assertEqual(results[0]["id"], str(urgent_ticket.id))
self.assertEqual(results[1]["id"], str(self.ticket.id))
+ @parameterized.expand(
+ [
+ ("sla_due_at", ["soon", "later", "null_c", "null_b", "null_a"]),
+ ("-sla_due_at", ["later", "soon", "null_c", "null_b", "null_a"]),
+ ]
+ )
+ def test_order_by_sla_due_at_is_stable_across_pages(self, mock_on_commit, order_by, expected):
+ # Most tickets have no SLA (NULL sla_due_at), so the sort key ties across many rows.
+ # Without a unique tiebreaker the tied rows have no stable order across the separate
+ # LIMIT/OFFSET page queries, so paging duplicates or drops rows and the sort looks lost.
+ # ticket_numbers: null_a=1 (setUp), null_b=2, null_c=3, soon=4, later=5.
+ now = timezone.now()
+ tickets: dict[str, Ticket] = {"null_a": self.ticket}
+ for key in ("null_b", "null_c", "soon", "later"):
+ tickets[key] = Ticket.objects.create_with_number(
+ team=self.team,
+ channel_source=Channel.WIDGET,
+ widget_session_id=key,
+ distinct_id=key,
+ sla_due_at={"soon": now + timedelta(hours=1), "later": now + timedelta(hours=5)}.get(key),
+ )
+
+ seen: list[str] = []
+ for offset in range(0, len(tickets), 2):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/conversations/tickets/?order_by={order_by}&limit=2&offset={offset}"
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ seen.extend(r["id"] for r in response.json()["results"])
+
+ # Real deadlines sort first (ascending/descending), no-SLA tickets last, ties broken by
+ # -ticket_number — a single total order, so the pages concatenate back to exactly it.
+ self.assertEqual(seen, [str(tickets[key].id) for key in expected])
+
def test_filter_multiple_priorities_excludes_null(self, mock_on_commit):
"""Test that multiple priority filter excludes tickets with NULL priority."""
self.ticket.priority = Priority.LOW
diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.py
index 9271f2c46b7a..67831a6345e1 100644
--- a/products/conversations/backend/api/tickets.py
+++ b/products/conversations/backend/api/tickets.py
@@ -7,7 +7,7 @@ from datetime import timedelta
from typing import Any
from django.db import transaction
-from django.db.models import CharField, Exists, OuterRef, Q, QuerySet, Sum
+from django.db.models import CharField, Exists, F, OrderBy, OuterRef, Q, QuerySet, Sum
from django.db.models.functions import Cast
from django.http import Http404
from django.utils import timezone
@@ -584,7 +584,22 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, viewsets.Mod
if order_by not in allowed_orderings:
order_by = "-updated_at"
- return queryset.order_by(order_by)
+ field_name = order_by.lstrip("-")
+ primary: OrderBy | str
+ if field_name in ("sla_due_at", "snoozed_until"):
+ # A ticket with no SLA (or no snooze) sorts to the bottom either direction — an
+ # absent deadline isn't more urgent than a real one, and it keeps the large NULL
+ # block off the first pages so the SLA-sorted rows are what the user actually sees.
+ descending = order_by.startswith("-")
+ primary = F(field_name).desc(nulls_last=True) if descending else F(field_name).asc(nulls_last=True)
+ else:
+ primary = order_by
+
+ # ticket_number is unique per team (the queryset is already team-scoped), so it breaks
+ # ties deterministically. Without it, rows equal on the primary key — every no-SLA
+ # ticket shares NULL sla_due_at — have no stable order across the separate LIMIT/OFFSET
+ # page queries, so pages overlap or drop rows and the sort looks lost past page 1.
+ return queryset.order_by(primary, "-ticket_number")
def safely_get_object(self, queryset):
"""
diff --git a/products/conversations/backend/migrations/0053_ticket_sla_snooze_desc_indexes.py b/products/conversations/backend/migrations/0053_ticket_sla_snooze_desc_indexes.py
new file mode 100644
index 000000000000..9bcddc8241e8
--- /dev/null
+++ b/products/conversations/backend/migrations/0053_ticket_sla_snooze_desc_indexes.py
@@ -0,0 +1,33 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Concurrent index builds cannot run inside a transaction; keep them in their own migration.
+ atomic = False
+
+ dependencies = [
+ ("conversations", "0052_ticket_organization_id_source"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="ticket",
+ index=models.Index(
+ models.F("team_id"),
+ models.F("sla_due_at").desc(nulls_last=True),
+ models.F("ticket_number").desc(),
+ name="posthog_con_sla_desc_idx",
+ ),
+ ),
+ SafeAddIndexConcurrently(
+ model_name="ticket",
+ index=models.Index(
+ models.F("team_id"),
+ models.F("snoozed_until").desc(nulls_last=True),
+ models.F("ticket_number").desc(),
+ name="posthog_con_snooze_desc_idx",
+ ),
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/0054_ticket_sla_snooze_asc_indexes.py b/products/conversations/backend/migrations/0054_ticket_sla_snooze_asc_indexes.py
new file mode 100644
index 000000000000..9bbd633920e8
--- /dev/null
+++ b/products/conversations/backend/migrations/0054_ticket_sla_snooze_asc_indexes.py
@@ -0,0 +1,44 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently, SafeRemoveIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # Concurrent index builds cannot run inside a transaction.
+ atomic = False
+
+ dependencies = [
+ ("conversations", "0053_ticket_sla_snooze_desc_indexes"),
+ ]
+
+ operations = [
+ # Add the ascending expression indexes first so (team_id, sla_due_at) / (team_id,
+ # snoozed_until) lookups keep index coverage throughout, then drop the now-redundant
+ # plain single-column indexes they supersede.
+ SafeAddIndexConcurrently(
+ model_name="ticket",
+ index=models.Index(
+ models.F("team_id"),
+ models.F("sla_due_at").asc(nulls_last=True),
+ models.F("ticket_number").desc(),
+ name="posthog_con_sla_asc_idx",
+ ),
+ ),
+ SafeAddIndexConcurrently(
+ model_name="ticket",
+ index=models.Index(
+ models.F("team_id"),
+ models.F("snoozed_until").asc(nulls_last=True),
+ models.F("ticket_number").desc(),
+ name="posthog_con_snooze_asc_idx",
+ ),
+ ),
+ SafeRemoveIndexConcurrently(
+ model_name="ticket",
+ name="posthog_con_team_sla_idx",
+ ),
+ SafeRemoveIndexConcurrently(
+ model_name="ticket",
+ name="posthog_con_team_snooze_idx",
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txt
index 5d3b541940ca..2171c438fdea 100644
--- a/products/conversations/backend/migrations/max_migration.txt
+++ b/products/conversations/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0052_ticket_organization_id_source
+0054_ticket_sla_snooze_asc_indexes
diff --git a/products/conversations/backend/models/ticket.py b/products/conversations/backend/models/ticket.py
index 305d252e950b..cdb354c9ce03 100644
--- a/products/conversations/backend/models/ticket.py
+++ b/products/conversations/backend/models/ticket.py
@@ -142,10 +142,37 @@ class Ticket(UUIDTModel):
models.Index(fields=["team", "-updated_at"], name="posthog_con_team_updated_idx"),
# Dashboard filtered + ordered queries
models.Index(fields=["team", "status", "-updated_at"], name="posthog_con_status_upd_idx"),
- # SLA sort/filter queries
- models.Index(fields=["team", "sla_due_at"], name="posthog_con_team_sla_idx"),
- # Snooze: dashboard filter/sort by team
- models.Index(fields=["team", "snoozed_until"], name="posthog_con_team_snooze_idx"),
+ # SLA sort + filter. The dashboard sorts by "sla_due_at <dir> NULLS LAST, ticket_number
+ # DESC"; one expression index per direction makes each page a top-N index scan instead
+ # of a full sort of the mostly-NULL table (a plain ascending index can't serve DESC
+ # NULLS LAST, and lacks the ticket_number tiebreaker). The leading (team_id, sla_due_at)
+ # prefix also serves the SLA state filter, so these supersede a plain (team, sla_due_at).
+ models.Index(
+ models.F("team_id"),
+ models.F("sla_due_at").asc(nulls_last=True),
+ models.F("ticket_number").desc(),
+ name="posthog_con_sla_asc_idx",
+ ),
+ models.Index(
+ models.F("team_id"),
+ models.F("sla_due_at").desc(nulls_last=True),
+ models.F("ticket_number").desc(),
+ name="posthog_con_sla_desc_idx",
+ ),
+ # Snooze sort + filter: same asc/desc expression-index pair. The leading prefix serves
+ # the snoozed isnull filter, so these supersede a plain (team, snoozed_until) index.
+ models.Index(
+ models.F("team_id"),
+ models.F("snoozed_until").asc(nulls_last=True),
+ models.F("ticket_number").desc(),
+ name="posthog_con_snooze_asc_idx",
+ ),
+ models.Index(
+ models.F("team_id"),
+ models.F("snoozed_until").desc(nulls_last=True),
+ models.F("ticket_number").desc(),
+ name="posthog_con_snooze_desc_idx",
+ ),
# Snooze: wake task (cross-team, only non-null rows)
models.Index(
fields=["snoozed_until"],