Skip to content

fix(api): strip ORDER BY from pagination count subquery - #45735

Merged
wylswz merged 8 commits into
langgenius:mainfrom
Wang-Zephyr:fix/pagination-count-order-by
Nov 12, 2026
Merged

wylswz merged 8 commits into
langgenius:mainfrom
Wang-Zephyr:fix/pagination-count-order-by

Conversation

@Wang-Zephyr

@Wang-Zephyr Wang-Zephyr commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Important

  1. Make sure you have read our contribution guidelines
  2. Ensure there is an associated issue
  3. Use the correct syntax to link this PR: Fixes #<issue number>.

Summary

Refs #45734

paginate_query (api/libs/pagination.py) wrapped the full statement — with its ORDER BY and column list 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. The incident in #45734 showed a sampled trace where the count consumed 99.81% of a 17 s request on a ~179M-row conversations table, and five overlapping limit=1 requests pushed read IOPS past the 90% alarm threshold.

What changed

The count now derives from a copy of the statement with ORDER BY, LIMIT, and OFFSET stripped before subquerying:

count_base = stmt.order_by(None).limit(None).offset(None)
count_stmt = select(func.count()).select_from(count_base.subquery())

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:

  1. test_count_strips_order_by_from_the_wrapped_statement — feeds paginate_query an ordered statement through a mock session, captures the count statement, compiles it to PostgreSQL SQL, and asserts no ORDER BY appears. Fails on the base revision, passes after the fix.
  2. test_page_query_retains_order_by — captures the page statement and asserts ORDER BY is 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. Using Refs rather than Fixes to reflect that.

Screenshots

Before After
N/A N/A

Not applicable — backend-only change, no UI surface.

Checklist

  • This change requires a documentation update, included: Dify Document
  • I understand that this PR may be closed in case there was no previous discussion or issues. (This doesn't apply to typos!)
  • I've verified the change and added or updated tests where meaningful regression risk justifies coverage.
  • I've updated the documentation accordingly.
  • I ran make lint && make type-check (backend) and vp staged (frontend) to appease the lint gods

make lint and make type-check were not run in this environment; CI is the first run. The production change is two lines in one function, and the test uses only sqlalchemy.compile + unittest.mock (no database fixture needed).

From WorkBuddy

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
@github-actions github-actions Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Nov 6, 2026

@GYJ99 GYJ99 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@Wang-Zephyr

Copy link
Copy Markdown
Contributor Author

Thanks @GYJ99 — both points are fair.

Fixes → Refs: Done. Updated the PR body to Refs #45734 and added a scope note acknowledging that the larger bitmap heap-read / lazy-totals strategy is separate work tracked in the issue itself. The count-sort regression this PR targets is unambiguous, but I agree it should not auto-close the broader incident.

Parity check: Added test_page_query_retains_order_by (commit d3dca55) — captures the page statement through the same mock session and asserts ORDER BY is present, so the fix is confirmed to affect the count branch alone. A full filtered-count parity check or post-change PostgreSQL EXPLAIN would need a live database fixture; the two compile-time SQL assertions cover the query-construction guarantee this PR makes without that dependency.

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Diff

base → 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]

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Pyrefly Type Coverage

Metric Base PR Delta
Type coverage 85.22% 85.22% +0.00%
Strict coverage 84.88% 84.88% +0.00%
Typed symbols 90,298 90,305 +7
Untyped symbols 15,725 15,725 0
Modules 4477 4477 0

@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.16%. Comparing base (0c4b96e) to head (de3f345).
⚠️ Report is 1 commits behind head on main.

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     
Flag Coverage Δ
api 90.02% <100.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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 GYJ99 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@Wang-Zephyr

Copy link
Copy Markdown
Contributor Author

Good catch on the semantic regression, @GYJ99 — you're right that .limit(None).offset(None) widens a pre-limited input statement to the full table in the count subquery.

Fixed in the latest two commits (15c5949 + 0012692):

  1. Removed .limit(None).offset(None) from count_base — only .order_by(None) is retained, which is the actual regression target (the ORDER BY that forces PostgreSQL to sort inside COUNT(*)). LIMIT/OFFSET on the input statement now pass through unchanged, so a pre-limited statement counts the correct window.

  2. Added test_count_preserves_caller_limit_and_offset — constructs select(...).order_by(...).limit(2).offset(1), runs it through paginate_query, and asserts the compiled count SQL contains both LIMIT and OFFSET, locking in the fix.

  3. Fixed the Pyrefly missing-attribute errors on .compile() calls in the test mock by widening captured from dict[str, object] to dict[str, Any] (the value is a SQLAlchemy Select at runtime, but Pyrefly could not infer it through the MagicMock side_effect chain).

The comment in pagination.py is also updated to explain why only ORDER BY is stripped and why LIMIT/OFFSET are intentionally preserved.

@wylswz

wylswz commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

The fix LGTM, but the style check still fails. @Wang-Zephyr

Copy link
Copy Markdown
Contributor Author

Thanks, @wylswz. I fixed the remaining Pyrefly error in de3f3459 by narrowing the captured SQLAlchemy statement to Select before compiling it. Python Style now passes.

@wylswz
wylswz added this pull request to the merge queue Nov 12, 2026
Merged via the queue into langgenius:main with commit d62f079 Nov 12, 2026
51 checks passed
@wylswz wylswz mentioned this pull request Nov 17, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants