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(business-knowledge): make the sources list order total (#102042)

posthog[bot]bbfff8e8f5c2
diff --git a/products/business_knowledge/backend/logic.py b/products/business_knowledge/backend/logic.py
index 26f339a8bbcf..2ea5f4673652 100644
--- a/products/business_knowledge/backend/logic.py
+++ b/products/business_knowledge/backend/logic.py
@@ -524,7 +524,8 @@ def list_for_team(
term = search.strip()
if term:
queryset = queryset.filter(Q(name__icontains=term) | Q(source_url__icontains=term))
- return list(queryset.annotate(**_source_list_annotations()).order_by("-created_at"))
+ # `id` breaks created_at ties so paging over the list can't skip or repeat a source.
+ return list(queryset.annotate(**_source_list_annotations()).order_by("-created_at", "id"))
@with_team_scope(canonical=True)
diff --git a/products/business_knowledge/backend/tests/test_api.py b/products/business_knowledge/backend/tests/test_api.py
index dcaa4e600217..dcf8df87ffda 100644
--- a/products/business_knowledge/backend/tests/test_api.py
+++ b/products/business_knowledge/backend/tests/test_api.py
@@ -111,6 +111,31 @@ class TestKnowledgeSourceAPI(APIBaseTest):
assert names("source_type=file&search=gamma") == ["Gamma report"]
assert names("source_type=text&search=beta") == []
+ def test_list_pages_do_not_skip_or_repeat_sources_with_equal_timestamps(self, _ff) -> None:
+ created_ids = sorted(
+ str(
+ KnowledgeSource.objects.unscoped()
+ .create(team=self.team, name=f"Tied {index}", source_type="text", status="ready")
+ .id
+ )
+ for index in range(4)
+ )
+ sources = KnowledgeSource.objects.unscoped().filter(team=self.team)
+ sources.update(created_at=timezone.now())
+
+ def page(offset: int) -> list[str]:
+ resp = self.client.get(f"{self.url}?limit=2&offset={offset}")
+ assert resp.status_code == status.HTTP_200_OK, resp.content
+ return [row["id"] for row in resp.json()["results"]]
+
+ first_page = page(0)
+ # An edit between the two reads rewrites the row, which moves it in the
+ # database's own tie order. Only the id tie-breaker keeps the pages aligned.
+ sources.filter(id=first_page[0]).update(name="Edited between pages")
+ paged_ids = first_page + page(2)
+
+ assert paged_ids == created_ids
+
def test_list_rejects_unknown_source_type(self, _ff) -> None:
response = self.client.get(f"{self.url}?source_type=bogus")
assert response.status_code == status.HTTP_400_BAD_REQUEST