Skip to content

LINQ: Count()/LongCount() after Take()/Skip() count the paged rows (Fixes #5920) - #5925

Merged
jeremydmiller merged 1 commit into
masterfrom
fix/5920-take-skip-count
Nov 15, 2026
Merged

jeremydmiller merged 1 commit into
masterfrom
fix/5920-take-skip-count

Conversation

@jeremydmiller

@jeremydmiller jeremydmiller commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

Fixes #5920.

Root cause

ProcessSingleValueModeIfAny turns a counted statement into select count(*) ... by swapping its select clause for a CountClause, and it left the statement's Limit/Offset in place. The paging was therefore applied to the single row the aggregate returns:

  • Take(n).Count(): select count(*) ... LIMIT n returns the full count
  • Skip(k).Count() and Skip(k).Take(n).Count(): OFFSET k skips the only row, so the count is 0
  • SelectMany(x => x.Children).Take(n).Count(): the same, over the exploded CTE
  • OrderBy(...).Take(n).SelectMany(x => x.Children).Count(): the SUM(jsonb_array_length(...)) shortcut summed every document and then paged the SUM row

Fix

In CollectionUsage.Compilation.cs:

  • tryCountPagedStatement<T>(): when the counted statement has a Limit or Offset, convert it to a CTE, keeping its ORDER BY because that decides which rows are on the page, and count the CTE. This is the same shape the join path already uses. Unpaged statements, Distinct() and GroupBy() are untouched: the last two already counted a CTE that carried the paging.
  • sumCollectionLengths<T>(): the SelectMany SUM shortcut wraps paged parent rows in a CTE and sums over it.
  • Any(): Take(0).Any() kept LIMIT 0 instead of widening it to LIMIT 1. It used to return true.

SQL before / after (executed; CTE names normalized to cte1/cte2)

Shape Before After
Take(3) select count(*) ... from mt_doc_x as d LIMIT $1 WITH cte1 as (select d.data from mt_doc_x as d LIMIT $1) select count(*) as number from cte1 as d
Skip(4) select count(*) ... OFFSET $1 WITH cte1 as (select d.data from mt_doc_x as d OFFSET $1) select count(*) ... from cte1 as d
Skip(4).Take(3) select count(*) ... OFFSET $1 LIMIT $2 WITH cte1 as (select d.data ... OFFSET $1 LIMIT $2) select count(*) ... from cte1 as d
OrderBy(Number).Skip(4).Take(3) select count(*) ... OFFSET $1 LIMIT $2 (ORDER BY dropped) WITH cte1 as (select d.data ... order by CAST(d.data ->> 'Number' as integer) OFFSET $1 LIMIT $2) select count(*) ... from cte1 as d
Where(Number > 3).Take(3) select count(*) ... where ... > $1 LIMIT $2 WITH cte1 as (select d.data ... where ... > $1 LIMIT $2) select count(*) ... from cte1 as d
Select(x => x.Number).Take(3) select count(*) ... LIMIT $1 WITH cte1 as (select CAST(d.data ->> 'Number' as integer) ... LIMIT $1) select count(*) ... from cte1 as d
SelectMany(Children).Take(3) WITH cte1 as (select jsonb_array_elements(...) as data ...) select count(*) from cte1 as d LIMIT $1 WITH cte1 as (select jsonb_array_elements(...) ...), cte2 as (select d.data as data from cte1 as d LIMIT $1) select count(*) from cte2 as d
SelectMany(Children).Where(Value > 1).Take(3) ... select count(*) from cte1 as d where ... > $1 LIMIT $2 ... cte2 as (select d.data as data from cte1 as d where ... > $1 LIMIT $2) select count(*) from cte2 as d
SelectMany(Tags).Take(3) (scalar) ... select count(*) from cte1 as d LIMIT $1 ... cte2 as (select CAST(data as integer) as data from cte1 as d LIMIT $1) select count(*) from cte2 as d
OrderBy(Number).Take(3).SelectMany(Children) select SUM(jsonb_array_length(d.data -> 'Children')) from mt_doc_x as d LIMIT $1 WITH cte1 as (select d.data from mt_doc_x as d order by ... LIMIT $1) select SUM(jsonb_array_length(d.data -> 'Children')) from cte1 as d
Select(Color).Distinct().Take(2) already WITH cte1 as (select DISTINCT(...) ... LIMIT $1) select count(*) ... unchanged (was already correct)
GroupBy(...).Select(...).Take(2) already WITH cte1 as (... GROUP BY ... LIMIT $1) select count(*) ... unchanged (was already correct)
Take(0) with Any() select TRUE ... LIMIT 1 select TRUE ... LIMIT 0

Unpaged counts are byte-identical. unpaged_count_sql_is_unchanged records the SQL each query actually executes and compares it with strings captured from master at 1d13d0f3a. It covers 11 shapes: plain, Where, OrderBy, Where+OrderBy, Select, Distinct, SelectMany, SelectMany+Where, SelectMany scalar, SelectMany+Distinct and GroupBy. All 11 pass on master and with the fix. Skip(k).Any() with k past the end was already correct (OFFSET k LIMIT 1).

Tests

  • LinqTests/Bugs/Bug_5920_count_over_paged_queries.cs, 140 cases. Each shape's CountAsync() and LongCountAsync() are compared against LINQ to Objects over the same 10 seeded documents. The shapes are Take, Skip, Skip+Take, OrderBy(+Descending)+Skip+Take, Where+Take, Where+OrderBy+Skip+Take, Select+Take, Select+Skip+Take, Distinct+Take, Distinct+Skip+Take, SelectMany+Take, SelectMany+Skip, SelectMany+Skip+Take, SelectMany+Where+Take, SelectMany scalar+Take, SelectMany+Distinct+Take, GroupBy+Take, Skip+Take+SelectMany and Skip+SelectMany. They run with n in {0, 1, 3, 10, 25} (25 > total) and k in {0, 1, 4, 10, 15} (past the end). Any() after Skip and after Skip+Take is covered too, as are the executed-SQL assertions above. The document type is declared in ClearedBeforeEachTest.
  • CompiledQueryTests/compiled_count_over_paged_queries.cs, 13 cases. A compiled Where+OrderBy+Skip+Take+Count() and a compiled Take+LongCount(), each with several paging values, against LINQ to Objects. A test also asserts that both are served by the source-generated path.

Red on master (fix reverted, same tests)

  • LinqTests Bug_5920_count_over_paged_queries: 51 of 140 fail. Take, Skip, Skip+Take, OrderBy+Skip+Take, Where+Take, Select+Take, all four SelectMany-then-page shapes, both page-then-SelectMany shapes, Take(0).Any() and the paged-SQL assertion. Distinct+Take and GroupBy+Take pass on master, and so do all 11 unpaged-SQL cases.
  • CompiledQueryTests compiled_count_over_paged_queries: 5 of 13 fail.

Full runs with the fix (Release, database marten_10_m)

Suite TFM Total Failed
LinqTests net10.0 1857 0
LinqTests net11.0 1881 0
CompiledQueryTests net10.0 22 0
DocumentDbTests net10.0 1271 0
EventSourcingTests net10.0 2944 0

The new LinqTests class was re-run after its SQL assertions moved from ToCommand() to executed SQL: 140/140 on net10.0 and on net11.0.

9.x

9.0 has the same bug. On a worktree from origin/9.0 (d824a8dcc), the same test class fails the same 51 behavioural cases. The fix cherry-picks cleanly onto branch fix/5920-take-skip-count-9.0 (0e549e50b). That branch is red without the fix (51/140 LinqTests, 5/13 CompiledQueryTests) and green with it (full LinqTests on net10.0: 1809 run, 0 failed). Its CI run: https://github.com/JasperFx/marten/actions/runs/43732699500

Not fixed here (separate, pre-existing)

OrderBy(...).Take(n).SelectMany(x => x.Children).ToList() (a fetch, not a count) applies the LIMIT to the exploded child rows, so it returns n children rather than the children of the first n documents. After this PR, the count of that shape follows LINQ semantics (the children of the first n documents), so it can differ from the fetch's row count until the fetch is fixed too.

Migration guide: a "LINQ Count() after Take() or Skip() counts the page" note under Key Changes in 10.0.0. markdownlint and cspell are clean.

🤖 Generated with Claude Code

…5920)

Count()/LongCount() over a paged statement put the LIMIT/OFFSET on the
count(*) itself, so Take(n).Count() returned the full count and
Skip(k).Count() / Skip(k).Take(n).Count() returned 0. A paged counted
statement is now wrapped in a CTE (keeping its ORDER BY, which decides the
page) and the CTE is counted. Covers documents, Where, OrderBy, Select
projections, SelectMany(...).Take/Skip, Take/Skip before SelectMany (the
SUM(jsonb_array_length) shortcut now sums the page) and compiled queries.
Take(0).Any() no longer widens LIMIT 0 to LIMIT 1.

Unpaged counts send byte-identical SQL; Distinct()/GroupBy() counts already
counted a CTE that carried the paging and are unchanged.

Fixes #5920

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jeremydmiller
jeremydmiller merged commit 5bbd732 into master Nov 15, 2026
32 checks passed
@jeremydmiller
jeremydmiller deleted the fix/5920-take-skip-count branch November 15, 2026 16:28
jeremydmiller added a commit that referenced this pull request Nov 15, 2026
[9.0] LINQ: Count()/LongCount() after Take()/Skip() count the paged rows (backport of #5925)
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.

LINQ: Take(n).Count() and Skip(k).Take(n).Count() return wrong counts (LIMIT/OFFSET applied to the count(*) itself)

1 participant