Skip to content

CBEF-132: Count through the index when a query needs consistency - #195

Merged
davidkelly merged 3 commits into
mainfrom
count-request-plus
Nov 24, 2026
Merged

davidkelly merged 3 commits into
mainfrom
count-request-plus

Conversation

@davidkelly

@davidkelly davidkelly commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

The issue in brief: Count() with no predicate can be wrong even when the context uses RequestPlus. The query service answers a bare COUNT(*) from the collection's document count (a CountScan), which ignores the scan consistency and is stale just after documents are deleted and inserted. On a local 3-node 8.0.1 cluster, a count taken at once after delete and insert was wrong in 29 of 40 rounds; the same count with a predicate was right every time. This is also the cause of the flaky GraphUpdates "one-to-many overlapping" and Transaction spec tests, because the harness reseeds before each test.

Change

  • When a query uses RequestPlus (the context default or WithScanConsistency) or a non-null ConsistentWith, an unfiltered Count()/LongCount() is sent with WHERE META(d).id IS NOT MISSING, which counts through the primary index and honours the scan consistency. A NotBounded count keeps the faster CountScan.
  • The translator marks the table of every count over one collection. When the query runs, CouchbaseParameterBasedSqlProcessor decides each mark from the query's final options and whether the ConsistentWith value is null; the SQL generator then adds the predicate to a marked COUNT that has no predicate of its own. So a hint anywhere in the query (later in the chain, or in a sibling subquery) applies, Count(x => true) is covered (EF drops that predicate), and a null MutationState does not force the index. Parameter nullness is part of EF's SQL cache key, so a cached query gets the right SQL for both values.
  • Behaviour change: such a count now needs a primary index. EnsureCreatedAsync creates one unless AutoCreateIndexes is false. CHANGELOG (Fixed) and docs/concurrency.md say so.

Tests

  • Unit: 17 new tests (each consistency source, a late hint, a hint in a sibling subquery, constant-true predicates, null and non-null ConsistentWith on the same query, filtered counts left alone). Mutation checks: marking only predicate-free counts, ignoring the parameter's nullness, or deciding at translation each fail the matching tests. All 1,231 unit tests pass.
  • Integration: a new test deletes, inserts 4 and counts, 20 rounds, under RequestPlus; it fails without the fix (Expected 4, Actual 2) and passes with it. Full suite 408/409; the one failure is the known "Keyspace not found" race in EnsureCreatedSeedingTests, which passed on two reruns.
  • Spec, local cluster: the 68 overlapping GraphUpdates variants pass 3 runs of 3 (33 to 40 failed before). TransactionCouchbaseTest fails the same 36 tests in every run, and none of its 10 flaky tests. UpdatesCouchbaseTest (no primary index in that scope) has no new failures.
  • Full spec run on the first commit, before the review fixes (45306660214), compared with main's baseline: 83 tests now pass, including all 68 overlapping GraphUpdates variants and 6 TransactionCouchbaseTest tests. 2 new failures, Select_Union_different_fields_in_anonymous_with_subquery(async: True) and Can_Attach_or_Update_a_many_to_many_with_mixed_set_and_unset_keys(useUpdate: True, async: False). Both are known flakes and are in CBEF-123: Keep flaky spec tests in their own list #194's flaky.txt. The JsonQuery/JsonUpdate aborts are also on main; CBEF-130: Do not follow an owned type's navigation back to its owner #192 handles them. The baseline is not changed here: the flaky list and the stack (CBEF-123: Keep flaky spec tests in their own list #194, CBEF-130: Do not follow an owned type's navigation back to its owner #192, CBEF-131: Fix legacy keys with non-public parts; default to V2 keys #193) take the effect of this fix in.
  • Filtered spec run on the review fixes (45425994911: NorthwindAggregateOperators, NorthwindSetOperations, GraphUpdates, Transaction, Updates, GearsOfWar incl. TPC/TPT): 80 now pass, the same overlapping GraphUpdates, Transaction and UpdatesCouchbaseTest tests as the full run. 1 new failure, Select_Union_different_fields_in_anonymous_with_subquery(async: True), the known flake in CBEF-123: Keep flaky spec tests in their own list #194's flaky.txt (a union result, no count involved). No class aborted.

Ticket: CBEF-132

🤖 Generated with Claude Code

Motivation
==========
The query service answers a bare COUNT(*) from the collection's
document count (a CountScan), which ignores the scan consistency and
is stale just after documents are deleted and inserted. So Count()
could be wrong under RequestPlus. On a 3-node 8.0.1 cluster, a count
taken at once after delete and insert was wrong in 29 of 40 rounds.
This is also why the GraphUpdates overlapping and Transaction spec
tests flake: the harness reseeds before each test.

Modification
============
- The translator marks the table of an unfiltered Count()/LongCount()
  when the query uses RequestPlus (context default or
  WithScanConsistency) or ConsistentWith. A later hint in the chain
  updates the marks, since hints apply to the whole query.
- The SQL generator gives a marked COUNT the predicate
  WHERE META(alias).id IS NOT MISSING, which counts through the
  primary index. A NotBounded count keeps the CountScan.
- CHANGELOG and docs/concurrency.md describe it, including that such a
  count needs a primary index.

Results
=======
- Unit tests for each consistency source, a late hint, and filtered
  counts; the five that expect the predicate fail without the fix.
- New integration test (delete, insert 4, count, 20 rounds) fails
  without the fix and passes with it.
- Locally, the 68 overlapping GraphUpdates variants pass 3 runs of 3
  (33 to 40 failed before), and the Transaction class fails the same
  36 tests every run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved consistency handling can leave counts stale with late sibling hints or constant-true predicates, while null ConsistentWith parameters can unnecessarily require a primary index and break valid queries.

3 open issues
What changed in this PR

This PR addresses stale unfiltered counts in the Couchbase EF Core provider by routing consistency-sensitive Count() and LongCount() queries through an index rather than the collection’s document count.

Changes:

  • Marks eligible counts and generates WHERE META(d).id IS NOT MISSING when consistency is required.
  • Adds unit coverage for consistency options and an integration regression for counts immediately after deletes and inserts.
  • Documents the primary-index requirement and unchanged NotBounded behavior.
File Description
tests/​Couchbase.EntityFrameworkCore.UnitTests/​Couchbase/​EntityFrameworkCore/​Query/​CouchbaseConsistentCountTests.cs Tests count translation across consistency options and query shapes.
tests/​Couchbase.EntityFrameworkCore.IntegrationTests/​Tests/​CouchbaseWithScanConsistencyTests.cs Tests exact counts after repeated deletes and inserts.
src/​Couchbase.EntityFrameworkCore/​Query/​Internal/​CouchbaseQuerySqlGenerator.cs Adds the index-forcing predicate to marked counts.
src/​Couchbase.EntityFrameworkCore/​Query/​Internal/​CouchbaseQueryHintAnnotationNames.cs Defines the consistent-count annotation.
src/​Couchbase.EntityFrameworkCore/​Query/​Internal/​CouchbaseQueryableMethodTranslatingExpressionVisitor.cs Marks counts and updates markers for consistency hints.
docs/​concurrency.md Explains count behavior and the primary-index requirement.
CHANGELOG.md Records the count-consistency fix and compatibility implications.

Review effort: Balanced

Motivation
==========
Review found three gaps in deciding at translation time:
Count(x => true) bypassed marking, a WithScanConsistency hint in a
later sibling subquery did not update earlier counts, and a null
ConsistentWith value still forced the index predicate.

Modification
============
- Mark every count over a bare keyspace, with or without a predicate.
- Store a ConsistentCountMarker that reads the query's final options.
- Resolve it in CouchbaseParameterBasedSqlProcessor when the query
  runs, using the nullness of the ConsistentWith parameter.

Results
=======
All three cases are covered by new unit tests; 1,231 unit tests pass.

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

Nice fix. A few non-blocking nits below.

Comment thread CHANGELOG.md Resolved
Motivation
==========
Review nits: the CountScan explanation was repeated, the annotate and
swap steps were copied three times, the scan-consistency precedence
was duplicated, and the CHANGELOG did not list the new index
requirement as a change.

Modification
============
- Move SetHintAnnotation and the table swap into TableHintAnnotations.
- Share the precedence through EffectiveScanConsistency.
- Rename IsNeeded to RequiresIndexCount; keep one full explanation on
  the ConsistentCount annotation.
- CHANGELOG: add a Changed entry; say "non-null ConsistentWith".

Results
=======
No behaviour change. 1,231 unit tests and the 13 hint and consistency
integration tests pass.
@davidkelly
davidkelly merged commit e4d51c1 into main Nov 24, 2026
5 checks passed
davidkelly added a commit that referenced this pull request Nov 24, 2026
Motivation
==========
CBEF-132 (#195) made Count() exact under RequestPlus. That was the
cause of the flaky overlapping GraphUpdates and Transaction tests.

Modification
============
Remove the 22 overlapping GraphUpdates and 10 TransactionCouchbaseTest
entries from flaky.txt.

Results
=======
All 32 passed in both spec runs with the fix (45306660214 and
45425994911). The full run has no failures outside the baseline.
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.

3 participants