Skip to content

Reports - count pager totals without SQL_CALC_FOUND_ROWS - #37969

Merged
colemanw merged 3 commits into
civicrm:masterfrom
jfilter:perf-report-found-rows
Nov 26, 2026
Merged

colemanw merged 3 commits into
civicrm:masterfrom
jfilter:perf-report-found-rows

Conversation

@jfilter

@jfilter jfilter commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Overview

Report pager totals are counted without the deprecated SQL_CALC_FOUND_ROWS, which also fixes several wrong totals.

Before

Paged report templates add SQL_CALC_FOUND_ROWS to the main query and read FOUND_ROWS() for the pager. The modifier is deprecated since MySQL 8.0.17 and stops MySQL from using a top-N sort for ORDER BY … LIMIT (contribute/detail on MySQL 8.4, 300k contributions: 618 ms per page).

Several totals are wrong:

  • Repeat shows 1, because FOUND_ROWS() is read after other queries.
  • Empty reports show 1 instead of 0.
  • Top Donors never pages, because it checks an output mode that is no longer set; ranks also restart on every page.

After

buildRows() counts the rows it fetched. A page that is not full gives the total directly; otherwise the same query is counted once without its LIMIT (contribute/detail: 618 → 241 ms on MySQL 8.4, 115 → 145 ms on MariaDB 11.4). Grouped reports with several pages pay one extra count query that computes the aggregates again (contribute/sybunt: 1.5 → 3.0 s on MySQL 8.4, 1.0 → 1.6 s on MariaDB 11.4).

Reports that run their own query (Repeat, Sybunt, History, Lapse, Event Summary, Event Income Count Summary, Pledge Detail) call the new setRowsFound($sql, $fetched). Top Donors pages, and its ranks continue across pages.

Extensions that put SQL_CALC_FOUND_ROWS into SQL passed to buildRows() keep working; the modifier is removed and the query counted. Extensions that run their own query and read the total from FOUND_ROWS() get a deprecation warning; if they relied on limit() adding the modifier, they also get the page size as total (pager, "Total Row(s)" and the AJAX total). Calling setRowsFound($sql, $fetched) after the fetch fixes both.

@civibot

civibot Bot commented Nov 7, 2026

Copy link
Copy Markdown

🤖 Thank you for contributing to CiviCRM! ❤️ We will need to test and review this PR. 👷

Introduction for new contributors...
  • If this is your first PR, an admin will greenlight automated testing with the command ok to test or add to whitelist.
  • A series of tests will automatically run. You can see the results at the bottom of this page (if there are any problems, it will include a link to see what went wrong).
  • A demo site will be built where anyone can try out a version of CiviCRM that includes your changes.
  • If this process needs to be repeated, an admin will issue the command test this please to rerun tests and build a new demo site.
  • Before this PR can be merged, it needs to be reviewed. Please keep in mind that reviewers are volunteers, and their response time can vary from a few hours to a few weeks depending on their availability and their knowledge of this particular part of CiviCRM.
  • A great way to speed up this process is to "trade reviews" with someone - find an open PR that you feel able to review, and leave a comment like "I'm reviewing this now, could you please review mine?" (include a link to yours). You don't have to wait for a response to get started (and you don't have to stop at one!) the more you review, the faster this process goes for everyone 😄
  • To ensure that you are credited properly in the final release notes, please add yourself to contributor-key.yml
  • For more information about contributing, see CONTRIBUTING.md.
PR commands & links...
  • /rebase <?branch-name> will rebase your branch and change the base of the PR (if <branch-name> is specified).
  • /squash will combine all commits (keeping only the first commit messsage).
  • /port <branch-name> will create a copy of this PR against a different branch.
  • /lint will automatically fix linting errors, amending commits as needed.
  • retest this please will rerun the tests and rebuild the demo site.
  • 📖 Review standards
  • 🗒️ Review template (brief or verbose)

➡️ Online demo of this PR 🔗

@civibot civibot Bot added the master label Nov 7, 2026
@jfilter
jfilter marked this pull request as ready for review November 8, 2026 15:07
@mattwire

Copy link
Copy Markdown
Contributor

@jfilter AI review:

Core reports look consistent, and the tests do reach the count path. Points on extension compatibility:

  • countRowsFound() strips SQL_CALC_FOUND_ROWS from legacy extension SQL and then runs a second COUNT(*), so those reports pay for both. Simpler: if the SQL still contains SQL_CALC_FOUND_ROWS, read FOUND_ROWS() straight after the query as before, and only run the count otherwise.
  • That would also keep SQL that relies on session variables working. reportplus CRM_Reportplus_Form_Contribute_TopDonor extends its own base class, not core TopDonor, so it doesn't get the new SET @rows handling and still filters with (@rows := @rows + 1) <= N. By the time the count runs @rows is already above N, so a full page reports a total of 0.
  • Wrapping the SQL as SELECT COUNT(*) FROM (...) fails with MySQL error 1060 if the select list has duplicate column names, which a top-level SELECT allows. An extension report selecting e.g. contact.id and contribution.id without aliases would only throw once a page is full.
  • Grouped reports now run the aggregation twice. A timing for a multi-page grouped report on MariaDB, where SQL_CALC_FOUND_ROWS isn't deprecated, would help.

Co-authored-by: Claude <noreply@anthropic.com>
@jfilter
jfilter force-pushed the perf-report-found-rows branch from d977445 to b9f327b Compare November 24, 2026 14:54
@jfilter

jfilter commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @mattwire. Rebased onto current master and updated:

  • Legacy SQL_CALC_FOUND_ROWS SQL: done as you suggested. If the query buildRows() runs still contains SQL_CALC_FOUND_ROWS, the total is read from FOUND_ROWS() straight after the query and no count query runs. The test fixture for this case now also repeats a column name, so taking the count path would fail with error 1060. It fails on the previous head and passes now.

  • Session variables (reportplus TopDonor): confirmed. Its limit() only adds SQL_CALC_FOUND_ROWS in html output mode, which is no longer set, so its query reaches the count path with @rows already past the page. Instead of the TopDonor-specific SET @rows:=0 override, buildRows() now saves every user variable the query assigns (@name :=) just before running it and restores those values before the count. That covers core TopDonor, reportplus and any other report using the same pattern, so the core override is gone. A new fixture with a (@rows := @rows + 1) <= 5 filter gets 3 on the previous head and 5 now.

  • Duplicate column names: still open for reports that relied on limit() adding the modifier and then select the same column name twice. Core reports alias every column, and legacy SQL that keeps SQL_CALC_FOUND_ROWS is no longer counted (see above).

  • Grouped reports on MariaDB: measured, and grouped reports with several pages get slower on both databases, because the count query computes the aggregates again. 300k contributions on 100k contacts, page 1 of 50 rows, median of 5 runs through buildQuery()/buildRows()/setPager(), master → this PR:

    Report MySQL 8.4 MariaDB 11.4
    contribute/detail 618 → 241 ms 115 → 145 ms
    contribute/sybunt (grouped) 1476 → 2978 ms 955 → 1569 ms
    contribute/lybunt (grouped) 404 → 695 ms 568 → 1148 ms

    Totals match master in every case. If the grouped case matters more than the deprecation, grouped queries could keep SQL_CALC_FOUND_ROWS and only ungrouped ones go through the count; I've added the numbers to the description.

@colemanw colemanw added the merge ready PR will be merged after a few days if there are no objections label Nov 24, 2026
@jfilter

jfilter commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@civireview

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

CiviReview: 🟡 Questions Only · Confidence: 3/5 ★★★☆☆

Automated AI-assisted review (alpha — experimental tool under active development; may miss issues or report false positives, so please verify findings before acting and open an issue with any feedback).

Summary: Report pagers stop using the deprecated SQL_CALC_FOUND_ROWS. buildRows() counts the rows it fetched, and runs a COUNT(*) only when the page is full. This also fixes wrong totals in Repeat, empty reports and Top Donors paging. A/B testing proved 7 test(s) failed on base, passed on PR. 3 verified finding(s) — top: [MEDIUM] Count query fails with MySQL error 1060 for extension reports that rely on limit() and repeat a column name (+2 more).

Merge Confidence (3/5): 1 confirmed medium finding(s); 2 low-severity or question-only finding(s); unaddressed reviewer feedback (1 open question/request(s) (mattwire) · 3 addressed/answered).

  • PR: civicrm/civicrm-core#37969 · Profile: core · Kind: core-bugfix · Commits: 3574e72 → b9f327b

Action Items (4)

  • [MEDIUM | PROVEN] CRM/Report/Form.php:3342-3354 — Count query fails with MySQL error 1060 for extension reports that rely on limit() and repeat a column name — Catch the DB exception in countRowsFound() and fall back to re-running the query without its LIMIT and with SQL_CALC_FOUND_ROWS, then read FOUND_ROWS(). Or wrap the query in a form that does not need unique column…
  • [LOW | CONFIRMED] CRM/Report/Form.php:3319-3332 — Extra count query now runs for non-paged callers such as the ReportTemplate.getrows API — In buildRows() or setRowsFound(), skip countRowsFound() when !$this->addPaging (set _rowsFound = $offset + $fetched), because no pager is rendered.
  • [LOW | CONFIRMED] CRM/Report/Form/Contribute/History.php:616-626 — Rewritten Contribute History pager/total flow has no pager-total test — Add a PagerTest case: create 3 donors with createDonors(), run CRM_Report_Form_Contribute_History with rowCount=2 on page 1 and page 2, and assert _totalItems is 3 both times.
  • [OPEN REVIEWER FEEDBACK] Address mattwire: COUNT(*) derived-table wrapper fails with error 1060 on duplicate column names — The author says it is still open for reports that relied on limit(). Reproduced live on stack B (nativecode=1060), and there is no fallback in countRowsFound().

Empirical Verification Matrix

Check Status Detail
CI / Jenkins ✅ PASS 1 CI checks: 1 passed, 0 failed, 0 pending.
A/B Proof-of-Fix ✅ PASS 7 test(s) failed on base, passed on PR (+9 regression-guard test(s) passed on both base & PR: testDetailTotalCountsAllPages, testDetailTotalOnLastPage, testLybuntTotalCountsAllContacts, testSybuntTotalCountsAllContacts, testEventSummaryTotalCountsAllEvents, testEventIncomeCountSummaryTotalCountsAllEvents, testPledgeDetailTotalCountsAllPledges, testMemberLapseTotalCountsAllMemberships, testLegacyOwnFoundRowsQueryTotalCountsAllPages)
Base-Test Regression ✅ PASS 40 test(s) passed on A and B (1 pre-existing failure(s) on both)
Live Surface Diff ✅ PASS Live APIv4/APIv3/routes/Afform surface diff captured with 0 risk flags.
Reviewer Thread ⚠️ WARN 1 open question/request(s) (mattwire) · 3 addressed/answered
Reviewer Questions & Thread Resolution (1 open, 3 addressed/answered)
Reviewer Question / Request Status Detail
mattwire Read FOUND_ROWS() directly when legacy SQL still contains SQL_CALC_FOUND_ROWS instead of counting again ✅ Addressed Form.php:3270 reads FOUND_ROWS() right after the query when the SQL contains the modifier and skips countRowsFound().
mattwire Session-variable top-N filters (reportplus TopDonor rows) report a wrong total on the count path ✅ Addressed buildRows() saves every @name := variable before the query and countRowsFound() restores them. testLegacyTopRowsQueryTotalCountsFromSameStart is green on B and red on A.
mattwire COUNT(*) derived-table wrapper fails with error 1060 on duplicate column names ⏳ Open The author says it is still open for reports that relied on limit(). Reproduced live on stack B (nativecode=1060), and there is no fallback in countRowsFound().
mattwire Timing of multi-page grouped reports on MariaDB 💬 Answered The author posted MySQL 8.4 and MariaDB 11.4 timings showing grouped reports getting slower, and offered keeping SQL_CALC_FOUND_ROWS for grouped queries as an option.
Detailed Walkthrough (6 notes)
  • PROVEN (A/B): 7 tests are red on the base and green on the PR: empty-report total 0, Repeat total, Top Donors paging and rank continuation, legacy FOUND_ROWS and @var top-rows queries, the LIMIT syntaxes, and the lybunt API test. There are no regressions. CRM_Logging_SchemaTest::testArchiveEngineConversion fails on both stacks.
  • PROVEN (A/B): 9 added tests also pass on the base. They are regression guards for totals that were already correct, not proof of the fix.
  • CONFIRMED (code): limit() no longer injects SQL_CALC_FOUND_ROWS. buildRows() reads FOUND_ROWS() only when the SQL still contains the modifier. Otherwise setRowsFound() uses offset plus fetched rows for a page that is not full, or a derived-table COUNT(*) for a full page, after restoring user variables.
  • PROVEN (live, stack B): the derived-table count throws error 1060 for unaliased duplicate column names on a full page. The old FOUND_ROWS path on stack A returns the total for the same query. See the duplicate-column finding.
  • CONFIRMED (code): the count also runs for APIv3 ReportTemplate.getrows, which has no pager (low, performance only). Contribute History's rewritten pager flow has no test (low).
  • CONFIRMED (author comment): grouped reports with several pages are slower because the count recomputes the aggregates (sybunt 1.5→3.0 s on MySQL 8.4).
CiviCRM Core Standards (10 checks — 4 ISSUE)
Code Status Note
r-explain PASS The description covers before/after, timings and extension impact.
r-user ISSUE Extension reports that relied on limit() adding the modifier can now crash on a full page (see 'Count query fails with MySQL error 1060'). The page-size-as-total change for own-query extensions is documented in the PR.
r-tech ISSUE limit() no longer adds SQL_CALC_FOUND_ROWS, which changes behaviour for extensions (see the duplicate-column finding). The new protected setRowsFound() and the int return of ReportDetail::getCountOfAllContactChangesForConnection are fine.
r-code ISSUE The count path has no fallback for derived-table errors (duplicate-column finding) and also runs for non-paged API getrows (extra count finding, low).
r-run PASS CI passed. In the A/B run, 7 tests go from red to green with no regressions.
r-maint PASS setRowsFound() is a clear, reusable helper for reports that run their own query.
r-test ISSUE PagerTest covers most rewritten reports and the legacy cases. Contribute History has no pager-total test (low).
r-doc N/A No dev-docs change identified.
rg-hook N/A No hook signature change.
rg-sec PASS The count SQL wraps the query that was already executed. User-variable names are restricted to \w+.
Ecosystem Blast Radius (6 items)
Repo Path Symbol Impact
civicrm-core CRM/Report/Form.php CRM_Report_Form::limit / buildRows / setPager / setRowsFound / countRowsFound Every report that extends CRM_Report_Form now gets its pager total from fetched rows or a derived-table count instead of SQL_CALC_FOUND_ROWS.
civicrm-core api/v3/ReportTemplate.php _civicrm_api3_report_template_getrows A full API page triggers an unused count query (extra count finding).
civicrm-core CRM/Report/Form/Contribute/TopDonor.php limit / alterDisplay Top Donors now pages, and ranks continue across pages.
civicrm-core CRM/Report/Form/Contribute/History.php buildRows The total now comes from setRowsFound() instead of a LIMIT-less query run. No pager test covers it.
civicrm-core CRM/Logging/ReportDetail.php getCountOfAllContactChangesForConnection Returns 0 instead of [] when there is no log_conn_id, which works with the new === NULL check in setPager().
extensions report extensions (e.g. reportplus) own-query / limit()-reliant reports Own-query reports that never call setRowsFound() get the page size as their total. Reports that relied on limit() and have duplicate unaliased columns crash on a full page.
Rejected or below 50% confidence (2)
  • [LOW | REJECTED | 35%] CRM/Report/Form/Contribute/Detail.php:581-585 — Removed soft_credits_only early setPager() in Contribute Detail has no test — verifier: I read Detail.php:525-615 at head. The count is taken over the same temp3 SELECT that is displayed, and in soft_credits_only mode temp3 holds only soft-credit rows, so the total cannot diverge from the displayed rows by mode. The failure mechanism is speculative and the code path is already covered by the Detail pager tests.
  • [LOW | REJECTED | 20%] CRM/Report/Form.php:3335-3351 — Open concern: COUNT(*) wrapper still fails on duplicate column names, with no test pinning the behaviour — verifier: Duplicate of count-derived-table-dup-columns, which was proven live on stack B. I merged it there instead of posting it twice.

Reviewed by civireview · sonnet-opus · 2,306,113 tokens · $1.38

Comment thread CRM/Report/Form.php Resolved
Comment thread CRM/Report/Form.php Resolved
Comment thread CRM/Report/Form/Contribute/History.php Resolved
Co-authored-by: Claude <noreply@anthropic.com>
@jfilter

jfilter commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up in 151ea18, which drops the remaining SQL_CALC_FOUND_ROWS/FOUND_ROWS() dependencies. MySQL 9.7 still warns that both "will be removed in a future release" and recommends two separate queries.

  • Legacy SQL_CALC_FOUND_ROWS SQL: I reverted the FOUND_ROWS() read from my last update. buildRows() now strips the modifier before running the query and counts like every other report, so the query keeps its LIMIT optimisation and nothing is computed twice.
  • Duplicate column names: fixed. When the derived-table count fails with error 1060, the query is counted through a CTE with a column list (checked on MySQL 8.4 and MariaDB 11.4).
  • Grouped reports: they stay on the count path. Keeping the modifier there would only defer the break; the extra aggregation on multi-page grouped reports is the cost.
  • Reports that run their own SQL_CALC_FOUND_ROWS query and never call setRowsFound() still get their total from FOUND_ROWS(), now with a deprecation warning, so that fallback can go after the deprecation period.
  • Reports without a pager (APIv3 getrows) no longer run the count (also noted by civireview).

@jfilter

jfilter commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@civireview

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

CiviReview: 🔴 Needs Changes · Confidence: 2/5 ★★☆☆☆

Automated AI-assisted review (alpha — experimental tool under active development; may miss issues or report false positives, so please verify findings before acting and open an issue with any feedback).

Summary: Report pager totals no longer use SQL_CALC_FOUND_ROWS. buildRows() uses the fetched row count, or a LIMIT-less COUNT(*) when the page is full. This also fixes the totals for Repeat, empty reports and Top Donors. The new CTE fallback breaks CI on MySQL 5.7. A/B testing proved 2 test(s) failed on base, passed on PR. 1 verified finding(s) — top: [MEDIUM] Duplicate-column count fallback uses a CTE, which MySQL 5.7 does not support (Jenkins failing).

Merge Confidence (2/5): CI / Jenkins failed; 1 confirmed medium finding(s); unaddressed reviewer feedback (1 open question/request(s) (mattwire) · 3 addressed/answered).

  • PR: civicrm/civicrm-core#37969 · Profile: core · Kind: core-bugfix · Commits: 3574e72 → 151ea18

Action Items (2)

  • [MEDIUM | PROVEN] CRM/Report/Form.php:3352-3361 — Duplicate-column count fallback uses a CTE, which MySQL 5.7 does not support (Jenkins failing) — Make the 1060 fallback work without a CTE. One option: read the column count from the LIMIT 0 result as you do now, then build a derived table with unique aliases. Another: on servers without CTE support, run the…
  • [CHECK FAILED] Resolve CI / Jenkins: 1 CI checks: 0 passed, 1 failed, 0 pending (1 failed test(s) extracted). — failed tests: CRM_Report_Form_PagerTest::testLegacyFoundRowsQueryTotalCountsAllPages

Empirical Verification Matrix

Check Status Detail
CI / Jenkins ❌ FAIL 1 CI checks: 0 passed, 1 failed, 0 pending (1 failed test(s) extracted). — failed tests: CRM_Report_Form_PagerTest::testLegacyFoundRowsQueryTotalCountsAllPages
A/B Proof-of-Fix ✅ PASS 2 test(s) failed on base, passed on PR (+1 regression-guard test(s) passed on both base & PR: testHistoryTotalCountsAllContacts)
Base-Test Regression ✅ PASS 16 test(s) passed on A and B
Live Surface Diff ✅ PASS Live APIv4/APIv3/routes/Afform surface diff captured with 0 risk flags.
Reviewer Thread ⚠️ WARN 1 open question/request(s) (mattwire) · 3 addressed/answered
Reviewer Questions & Thread Resolution (1 open, 3 addressed/answered)
Reviewer Question / Request Status Detail
mattwire Legacy SQL_CALC_FOUND_ROWS queries paying for both FOUND_ROWS and a second COUNT ✅ Addressed At head, buildRows() strips the modifier before running the query (Form.php:3262), so the work is no longer done twice. The query is counted only when the page is full.
mattwire Session-variable top-N filters (reportplus TopDonor rows) giving a wrong total on the count path ✅ Addressed buildRows() saves every @name := variable before the query (Form.php:3265-3269), and restoreRowsFoundVariables() resets them before each count query.
mattwire COUNT(*) derived-table wrapper failing with error 1060 on duplicate column names ⏳ Open A CTE fallback was added at Form.php:3352-3361, but CTEs are a syntax error on MySQL 5.7, which core still supports, and the Jenkins m57 job fails the duplicate-column test.
mattwire Timing of multi-page grouped reports on MariaDB 💬 Answered The author posted MySQL 8.4 and MariaDB 11.4 timings showing grouped reports getting slower, and decided to keep them on the count path.
Detailed Walkthrough (5 notes)
  • CONFIRMED (Form.php:3257-3331): buildRows() removes SQL_CALC_FOUND_ROWS before running the query. setRowsFound() uses offset+fetched when the page is not full and otherwise counts the SQL without its LIMIT. When addPaging is FALSE it sets _rowsFound to NULL and runs no count.
  • CONFIRMED (Form.php:3342-3375): countRowsFound() wraps the SQL in a derived table and restores the saved @var values before counting. On error 1060 it falls back to a CTE with a column list. That fallback breaks on MySQL 5.7 (see the CTE finding).
  • PROVEN (A/B): testRowsFoundAcceptsLimitSyntaxes and testRowsFoundWithoutPagingRunsNoCount are red on base and green on the PR, with no regressions. testHistoryTotalCountsAllContacts also passes on base, so it only guards against regressions.
  • PROVEN (CI): Jenkins job standalone-clean php85m57 fails CRM_Report_Form_PagerTest::testLegacyFoundRowsQueryTotalCountsAllPages with 'DB Error: syntax error'. Its fixture repeats legacy_column, so it reaches the CTE fallback.
  • NOT VERIFIED: the author's MySQL 8.4/MariaDB timings, where multi-page grouped reports pay a second aggregation, and behaviour in real extensions such as reportplus. The A/B stacks have neither MySQL 5.7 nor those extensions.
CiviCRM Core Standards (8 checks — 3 ISSUE)
Code Status Note
r-explain PASS The description and the follow-up comment explain the before and after, the timings and the impact on extensions.
r-user PASS Legacy SQL_CALC_FOUND_ROWS SQL is still accepted, and reports that run their own query get a deprecation warning. The MySQL 5.7 limitation is covered under r-code.
r-tech PASS limit() no longer adds the modifier, the new protected setRowsFound() is documented, and the PR describes the impact on extensions.
r-code ISSUE See 'Duplicate-column count fallback uses a CTE, which MySQL 5.7 does not support'.
r-run ISSUE Jenkins is red on the MySQL 5.7 job (testLegacyFoundRowsQueryTotalCountsAllPages). A/B passes because the stacks run MariaDB.
r-test ISSUE The legacy duplicate-column test fails in CI on MySQL 5.7 (same CTE finding). testHistoryTotalCountsAllContacts also passes on base, so it only guards against regressions and does not prove the fix.
r-doc N/A No dev-docs change identified.
rg-sec PASS The count wraps the query that was already executed, and user-variable names are restricted to \w+.
Ecosystem Blast Radius (3 items)
Repo Path Symbol Impact
civicrm-core CRM/Report/Form.php buildRows / setRowsFound / countRowsFound All report pager totals now come from these methods. The duplicate-column fallback fails on MySQL 5.7 (CTE finding).
extensions report extensions that rely on limit() and select unaliased duplicate column names countRowsFound fallback On MySQL 5.7 a full page crashes with a syntax error instead of showing a total.
extensions report extensions that run their own query setPager FOUND_ROWS() fallback They still get their total from FOUND_ROWS(), now with a deprecation warning, until they call setRowsFound().
Rejected or below 50% confidence (1)
  • [MEDIUM | REJECTED | 20%] CRM/Report/Form.php:3357-3360 — CTE fallback for duplicate columns is a syntax error on MySQL 5.7; it breaks CI test testLegacyFoundRowsQueryTotalCountsAllPages — verifier: The defect is real, but this is the same root cause and the same lines as cte-fallback-unsupported-mysql57, so I merged it there and it is not posted twice.

Reviewed by civireview · sonnet-opus · 1,134,115 tokens · $0.78

Comment thread CRM/Report/Form.php Resolved
Co-authored-by: Claude <noreply@anthropic.com>
@jfilter

jfilter commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@civireview

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

CiviReview: 🟢 Ready · Confidence: 5/5 ★★★★★

Automated AI-assisted review (alpha — experimental tool under active development; may miss issues or report false positives, so please verify findings before acting and open an issue with any feedback).

Summary: Report pagers no longer use the deprecated SQL_CALC_FOUND_ROWS. Totals come from the fetched rows, or from a LIMIT-less COUNT(*) when the page is full. This also fixes the wrong totals for Repeat, empty reports and Top Donors.

Merge Confidence (5/5): No verified issues; passed CI / Jenkins, Base-Test Regression, Live Surface Diff.

  • PR: civicrm/civicrm-core#37969 · Profile: core · Kind: core-bugfix · Commits: 3574e72 → c7636ea

Findings

No verified high-signal issues found above the confidence gate.

Empirical Verification Matrix

Check Status Detail
CI / Jenkins ✅ PASS 1 CI checks: 1 passed, 0 failed, 0 pending.
Base-Test Regression ✅ PASS 16 test(s) passed on A and B
Live Surface Diff ✅ PASS Live APIv4/APIv3/routes/Afform surface diff captured with 0 risk flags.
Reviewer Thread ✅ PASS All 4 reviewer question/request(s) addressed or answered.

Not Verified:

  • No added/modified PHPUnit tests in PR; Proof-of-Fix A/B test skipped.
Reviewer Questions & Thread Resolution (all 4 addressed/answered)
Reviewer Question / Request Status Detail
mattwire Legacy SQL_CALC_FOUND_ROWS queries paying for both FOUND_ROWS() and a second COUNT ✅ Addressed At head, buildRows() removes the modifier before running the query (Form.php:3262) and runs the count only when a paged page is full, so nothing is computed twice.
mattwire Session-variable top-N filters (reportplus TopDonor @rows) giving a wrong total on the count path ✅ Addressed buildRows() saves every @name := variable (Form.php:3265-3269), and restoreRowsFoundVariables() resets them before both the derived-table count and the streamed fallback.
mattwire COUNT(*) derived-table wrapper failing with error 1060 on duplicate column names ✅ Addressed On error 1060, countRowsFound() now counts rows from an unbuffered run of the query (Form.php:3352-3361). This works without CTEs, a live probe on stack B returned the correct total of 2, and the MySQL 5.7 CI job is green.
mattwire Timing of multi-page grouped reports on MariaDB 💬 Answered The author posted MySQL 8.4 and MariaDB 11.4 timings showing grouped multi-page reports get slower, and explained why grouped reports stay on the count path.
Detailed Walkthrough (6 notes)
  • CONFIRMED (Form.php:3257-3332): buildRows() removes SQL_CALC_FOUND_ROWS and saves any @var := user variables before running the query, then calls setRowsFound(). A page that is not full gives offset + fetched. A full page with paging off sets the total to NULL. A full page with paging on calls countRowsFound() on the SQL without its LIMIT.
  • CONFIRMED (Form.php:3348-3364): this commit replaces the CTE fallback with a streamed count. Any error other than 1060 is rethrown. On 1060, countRowsFound() restores the user variables, runs the LIMIT-less SQL through CRM_Core_DAO::executeUnbufferedQuery() (wrapper confirmed at CRM/Core/DAO.php:1689) and counts rows until fetch() returns false. No MySQL 8.0 syntax is left in this path.
  • PROVEN (live, stack B): setRowsFound('SELECT c.id, e.id … LIMIT 1', 1) with paging on now sets _rowsFound = 2. A direct COUNT(*) of the same join also gives 2, and a later SELECT 1 on the same connection succeeds, so the unbuffered result was fully read. On the previous head this query threw DBQueryException 1060.
  • PROVEN (CI): Jenkins is green (1 passed, 0 failed), including the MySQL 5.7 job that failed CRM_Report_Form_PagerTest::testLegacyFoundRowsQueryTotalCountsAllPages on the previous head. A/B base-test regression: 16 tests pass on A and B.
  • CONFIRMED (not a defect): the streamed fallback sends the full result set to PHP, but it runs only for extension SQL that repeats unaliased column names on a full, paged page. Master already computed the full result for the same query through SQL_CALC_FOUND_ROWS. The failed derived-table attempt is rejected when MySQL resolves the derived table's columns, before any rows are read, so the work is not done twice.
  • NOT VERIFIED: grouped multi-page reports run a second aggregation for the count (author's timings: sybunt 1.5→3.0 s on MySQL 8.4). Behaviour in real extensions such as reportplus was not checked, because the stacks have no large dataset and no third-party report extensions installed.
CiviCRM Core Standards (8 checks — all PASS/N/A)
Code Status Note
r-explain PASS The description and follow-up comments cover the before and after, the timings, and what changes for extensions. The latest commit's @todo explains why the CTE was dropped.
r-user PASS Extension reports with repeated unaliased column names now get a correct total instead of an error. Own-query extensions keep the FOUND_ROWS() fallback with a deprecation warning, as the PR documents.
r-tech PASS The 1060 fallback now uses the existing CRM_Core_DAO::executeUnbufferedQuery() wrapper and needs no MySQL 8.0 syntax, so it works on MySQL 5.7, which core still supports.
r-code PASS countRowsFound() rethrows any error other than 1060, restores user variables before the fallback, and reads every row of the unbuffered result, so the connection is usable again afterwards (checked live).
r-run PASS Jenkins: 1 passed, 0 failed, including the m57 job that failed on the previous head. A/B base-test regression: 16 tests pass on both stacks.
r-test PASS testLegacyFoundRowsQueryTotalCountsAllPages uses the LegacyFoundRowsForm fixture, which repeats a column name, so it covers the new fallback and now passes in CI. This diff adds no new tests.
r-doc N/A No dev-docs change identified.
rg-sec PASS The fallback runs the same SQL that was already executed. No new input reaches the query.
Ecosystem Blast Radius (3 items)
Repo Path Symbol Impact
civicrm-core CRM/Report/Form.php CRM_Report_Form::countRowsFound The fallback for repeated column names now streams and counts rows instead of using a CTE. It works on MySQL 5.7, 8.x and MariaDB.
extensions report extensions that rely on limit() and repeat unaliased column names countRowsFound 1060 fallback They get a correct pager total. The count runs in PHP, so it is slower on very large result sets.
extensions report extensions that run their own query setPager FOUND_ROWS() fallback No change in this commit. They keep the deprecation warning until they call setRowsFound().

Reviewed by civireview · sonnet-opus · 921,203 tokens · $0.66

@jfilter

jfilter commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

@colemanw the PR is now ready.

@colemanw
colemanw merged commit 48a495f into civicrm:master Nov 26, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

master merge ready PR will be merged after a few days if there are no objections

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants