Repository navigation
fix(api): strip ORDER BY from pagination count subquery - #45735
Conversation
paginate_query wrapped the full statement -- with its ORDER BY intact -- inside SELECT COUNT(*) FROM (...). PostgreSQL cannot use that ordering to short-circuit a count, so on large tables it sorts the entire match set per request. A sampled trace showed the count consuming 99.81% of a 17s request and triggering an IOPS alarm on a 179M-row table. Strip ORDER BY / LIMIT / OFFSET from the count base before subquerying; the page query keeps its ordering. Fixes langgenius#45734
GYJ99
left a comment
There was a problem hiding this comment.
Thanks for keeping the count-only change narrow. The order_by(None) regression test is a useful safeguard.
One scope concern: #45734's production EXPLAIN also shows a large bitmap heap-read workload after removing the sort, so this fix eliminates the unnecessary sort but may not prevent concurrent exact counts from saturating read IOPS for very large histories. Since the PR is explicitly scoped to the query-construction regression, would Refs #45734 (instead of Fixes #45734) be more accurate, with the remaining large-history count strategy tracked separately? This need not block the targeted improvement. A filtered-count parity check or post-change PostgreSQL plan would also strengthen confidence.
Addresses GYJ99's review: add a parity check that the page query keeps its ORDER BY while only the count loses it, so the fix is confirmed to affect the count branch alone.
|
Thanks @GYJ99 — both points are fair.
Parity check: Added |
Pyrefly Diffbase → PR--- /tmp/pyrefly_base.txt 2026-11-12 06:45:32.856948158 +0000
+++ /tmp/pyrefly_pr.txt 2026-11-12 06:45:20.208831335 +0000
@@ -5537,6 +5537,8 @@
--> tests/unit_tests/libs/broadcast_channel/redis/test_streams_channel.py:562:45
ERROR Argument `FakeStreamsRedis` is not assignable to parameter `client` with type `Redis[Unknown] | RedisCluster[Unknown]` in function `libs.broadcast_channel.redis.streams_channel._StreamsSubscription.__init__` [bad-argument-type]
--> tests/unit_tests/libs/broadcast_channel/redis/test_streams_channel.py:580:45
+ERROR Object of class `Executable` has no attribute `compile` [missing-attribute]
+ --> tests/unit_tests/libs/test_pagination.py:34:39
ERROR Argument `dict[str, list[@_]]` is not assignable to parameter `graph` with type `SQLCoreOperations[str] | str` in function `models.workflow.Workflow.__init__` [bad-argument-type]
--> tests/unit_tests/services/agent/test_dsl_service.py:115:15
ERROR `object` is not assignable to dict key `agent_binding` with type `str` [bad-assignment]
|
Pyrefly Type Coverage
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #45735 +/- ##
==========================================
- Coverage 90.16% 90.16% -0.01%
==========================================
Files 6307 6307
Lines 394819 394813 -6
Branches 79193 79190 -3
==========================================
- Hits 355981 355967 -14
- Misses 32727 32733 +6
- Partials 6111 6113 +2
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The two new unit tests use `session = MagicMock()` to capture the compiled count/page SQL without a real DB. The repo's no-new-session-mock ast-grep guard flags that pattern as net-new session mock assignment. Add the documented `# guard-ignore: no-new-session-mock -- <reason>` suppression on both lines, which is the guard's own supported escape hatch (per scripts/check_no_new_session_mock.py).
GYJ99
left a comment
There was a problem hiding this comment.
One additional correctness point after checking the latest diff: .limit(None).offset(None) changes the semantics of an arbitrary pre-limited input statement, whereas removing ORDER BY alone preserves them. I verified this independently with SQLAlchemy 2.0.50 + SQLite (not a Dify test): for a table with 5 rows, select(id).order_by(id).limit(2) is counted as 2 by the current helper, but 5 after this PR's rewrite; with .limit(2).offset(2), it likewise changes from 2 to 5. The stated regression only requires stmt.order_by(None) for the count subquery. Could we keep LIMIT/OFFSET unchanged, or document/test an intentional contract change separately? This would preserve the existing paginate_query behavior for callers providing arbitrary Select statements while still eliminating the expensive sort.
Remove `.limit(None).offset(None)` from the count base — @GYJ99 correctly identified that stripping them widens a pre-limited input statement to the full table in the count subquery (verified with SQLAlchemy 2.0.50 + SQLite: `select(id).limit(2)` counted as 5 after the old rewrite, 2 without it). Only `.order_by(None)` is retained, which is the actual regression target: the ORDER BY cannot change the count but forces PostgreSQL to sort the entire match set inside COUNT(*). Also fixes the Pyrefly type errors on the test mock by widening the captured-statement dict to `dict[str, Any]`.
…rors Add `test_count_preserves_caller_limit_and_offset` — constructs a pre-limited + offset statement and asserts the count SQL retains both clauses, locking in the fix for @GYJ99's semantic concern. Widen `captured` dict type from `dict[str, object]` to `dict[str, Any]` in all three count/page tests so Pyrefly stops reporting `missing-attribute` on `.compile()` calls.
|
Good catch on the semantic regression, @GYJ99 — you're right that Fixed in the latest two commits (
The comment in |
|
The fix LGTM, but the style check still fails. @Wang-Zephyr |
|
Thanks, @wylswz. I fixed the remaining Pyrefly error in |
Important
Fixes #<issue number>.Summary
Refs #45734
paginate_query(api/libs/pagination.py) wrapped the full statement — with itsORDER BYand column list intact — insideSELECT COUNT(*) FROM (...). PostgreSQL cannot use that ordering to short-circuit a count, so on large tables it sorts the entire match set per request. The incident in #45734 showed a sampled trace where the count consumed 99.81% of a 17 s request on a ~179M-rowconversationstable, and five overlappinglimit=1requests pushed read IOPS past the 90% alarm threshold.What changed
The count now derives from a copy of the statement with
ORDER BY,LIMIT, andOFFSETstripped before subquerying:The page query keeps its ordering unchanged — only the count loses the sort it never needed. This is the minimal, unambiguous part of the fix: a count must never carry a meaningless
ORDER BY, regardless of the larger "lazy/cached totals" strategy the issue also raises.Regression tests
Added two tests to
api/tests/unit_tests/libs/test_pagination.py:test_count_strips_order_by_from_the_wrapped_statement— feedspaginate_queryan ordered statement through a mock session, captures the count statement, compiles it to PostgreSQL SQL, and asserts noORDER BYappears. Fails on the base revision, passes after the fix.test_page_query_retains_order_by— captures the page statement and assertsORDER BYis present, confirming the fix affects the count branch alone.Scope note
This PR addresses the query-construction regression only: a count must never carry a meaningless
ORDER BY. As @GYJ99 noted in review, #45734's production EXPLAIN also shows a large bitmap heap-read workload after removing the sort, so very large histories may still need a separate count strategy (lazy/cached totals). That broader work is tracked in the issue itself and is out of scope for this targeted fix. UsingRefsrather thanFixesto reflect that.Screenshots
Not applicable — backend-only change, no UI surface.
Checklist
make lint && make type-check(backend) andvp staged(frontend) to appease the lint godsmake lintandmake type-checkwere not run in this environment; CI is the first run. The production change is two lines in one function, and the test uses onlysqlalchemy.compile+unittest.mock(no database fixture needed).From WorkBuddy