Skip to content

fix(databases): count result rows for grouped and distinct list totals - #14536

Merged
abnegate merged 3 commits into
mainfrom
qfix-total
Oct 15, 2026
Merged

abnegate merged 3 commits into
mainfrom
qfix-total

Conversation

@abnegate

Copy link
Copy Markdown
Member

Release blocker for the query-lib migration (#11649), found by staging QA of appwrite-labs/cloud#5410.

Problem

total ignored groupBy, distinct and aggregates, because utopia-php/database Database::count() only forwards filters and joins. Measured on Postgres (count() vs real rows):

Query Key RLS user
groupBy 9 vs 4 6 vs 3
distinct 9 vs 4 6 vs 3
plain aggregate 9 vs 1 6 vs 1
left join + groupBy 8 vs 3 6 vs 3
distinct over a join 7 vs 5 4 vs 3

Fix

  • XList's count calls now go through a new countRows().
  • Plain and join-only reads still use count().
  • Grouped and distinct reads re-run the same aggregate()/find() without limit, offset, cursor or order, capped at APP_LIMIT_COUNT.
  • When the first page is shorter than its limit, that page is the whole result, so no second read runs.
  • Because it is the same read, the total gets the same permissions as the results.

Interim

This can load up to 5000 rows. A utopia-php/database fix is in progress (a wrapped COUNT in count()). Once it's released, countRows() collapses back to count().

Known gap: a distinct total inside a transaction is still wrong (TransactionState::countDocuments()).

Tests

New tests/e2e/Services/Databases/Queries/Totals.php (Legacy and TablesDB; key, session and console) covers:

  • groupBy, including the ttl cache and POST /query
  • distinct
  • an ungrouped aggregate
  • a left join with groupBy
  • a fan-out join plus distinct

total is checked on whole reads and on every page. These tests were not run locally (no Docker).

🤖 Generated with Claude Code

Database::count() reads only the filters and joins of a query, so a list
that groups, aggregates or selects distinct rows reported the number of
documents it read instead of the rows it returned: 7 for 4 groups, the
joined row count for a grouped join, and the document count instead of 1
for an ungrouped aggregate.

For those reads the total now counts the rows the same aggregate() or
find() returns without limit, offset, cursor or order, capped at
APP_LIMIT_COUNT. Reusing the read keeps row-level and join permissions
identical to the results. A first page shorter than its limit is already
the whole result, so it answers the total without a second read. Plain
and joined reads keep count(), whose joined row count already matches
the rows.

Every list path (documents and rows, GET and POST query, cached and
uncached) runs this action, so the E2E cover groupBy, distinct, a left
join grouped by a joined column, a fan-out join and its distinct rows,
and an ungrouped aggregate, against the readable rows of a session user
and of a key, page by page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Distinct/aggregation totals re-run the query and hydrate up to 5000 rows — XList.php:293

The PR replaces the single count() call used for total in Documents/XList with a countRows() helper that handles the semantics aggregations and distinct queries need. Grouped or aggregated queries are counted by group rather than by row, distinct totals are deduplicated, and join queries are counted against the fan-out rows. Paging methods are stripped from the counting query and re-capped at APP_LIMIT_COUNT, with a fast path returning the page size for simple unpaginated reads. E2E coverage for these total-count semantics is added to the Databases suite via a new Totals query trait and wiring in DatabasesBase.

Files Change
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php Adds countRows() and the PAGING_METHODS constant so aggregation, distinct, and join queries report accurate totals.
tests/e2e/Services/Databases/Queries/Totals.php New e2e trait asserting total counts for grouped, distinct, and fan-out join queries.
tests/e2e/Services/Databases/DatabasesBase.php Wires the new Totals trait into the Databases test suites.

Reviewed commit: 77da843

@ghost

ghost commented Oct 15, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental changes introduce no actionable defects.

Database list totals now follow the actual result rows for grouped, aggregated, and distinct queries, while ordinary reads retain the existing count path. The shared Databases e2e suite covers totals across permissions, joins, cache usage, query endpoints, and pagination, including reads larger than the default page.

Latest changes: The follow-up applies the default page limit when queries omit one, adjusts short-page total detection, silences the unpaged distinct recount, and adds coverage for totals beyond the default page.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 3
File Change
src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/XList.php Uses query result rows to calculate grouped and distinct totals, with regular count behavior retained for ordinary reads.
tests/e2e/Services/Databases/DatabasesBase.php Adds the totals test trait to the shared Databases e2e suite.
tests/e2e/Services/Databases/Queries/Totals.php Covers grouped, distinct, aggregate, and joined totals, including permissions, pagination, and totals beyond the default page.

Merged main (2c72744); no changes to this PR's code since f545ab3 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost 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.

🟢 Tier S · Looks good to merge. Summary

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review Bot 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.

This PR fixes total counting for aggregation, distinct, and join fan-out queries in the Documents list endpoint by adding a dedicated countRows() path, plus new e2e total-count tests.

Key findings

  • 🟡 Distinct/aggregation totals re-run the query and hydrate up to 5000 rows — XList.php:293

@github-actions

github-actions Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → qfix-total (after).

Metric Before After Change
🚀 Requests/sec 186.9 192.78 ⚪ +3.1%
⏱️ Latency P50 90.63 ms 90.05 ms ⚪ -0.6%
⏱️ Latency P95 215.39 ms 207.25 ms ⚪ -3.8%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 90.05 207.25 12,426 192.78 -8.14
Account 167.03 303.08 654 10.86 -25.1
TablesDB 87.01 167.39 6,758 108.32 +0.97
Storage 83.5 184.11 3,270 53.8 -9.97
Functions 126.97 234.35 1,744 29.34 -17.79

Top API waits (after)

API request Max wait (ms)
account.name.update 419.54
account.prefs.update 401.04
tablesdb.rows.create 370.75
functions.variables.create 362.72
functions.variables.update 358.98

A list without a limit query still reads one default page, but the
short-page shortcut required an explicit limit, so every unlimited
grouped, aggregate or distinct list re-ran its read to count rows the
page already held. The read now passes APP_LIMIT_LIST_DEFAULT itself
instead of leaning on the library's own literal default of 25, and the
shortcut compares the page against that effective limit.

The distinct re-read already projects only the selected columns; it now
also runs silent and without filters, so its rows skip attribute
decoding and the Metadata decorator's per-row relationship walk. Query
rewrite hooks, such as join authorization, still apply.

The re-read itself stays until utopia-php/database count() wraps
grouped, distinct and aggregate reads in a counted subquery, at which
point countRows() becomes a plain count().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@abnegate
abnegate merged commit a3ffaa0 into main Oct 15, 2026
35 checks passed
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant