Repository navigation
CBEF-132: Count through the index when a query needs consistency - #195
Merged
Merged
Conversation
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.
Contributor
There was a problem hiding this comment.
🟡 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 MISSINGwhen 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
NotBoundedbehavior.
| 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
approved these changes
Nov 24, 2026
emilienbev
left a comment
There was a problem hiding this comment.
Nice fix. A few non-blocking nits below.
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
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.
This was referenced Nov 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


The issue in brief:
Count()with no predicate can be wrong even when the context usesRequestPlus. The query service answers a bareCOUNT(*)from the collection's document count (aCountScan), 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
RequestPlus(the context default orWithScanConsistency) or a non-nullConsistentWith, an unfilteredCount()/LongCount()is sent withWHERE META(d).id IS NOT MISSING, which counts through the primary index and honours the scan consistency. ANotBoundedcount keeps the fasterCountScan.CouchbaseParameterBasedSqlProcessordecides each mark from the query's final options and whether theConsistentWithvalue is null; the SQL generator then adds the predicate to a markedCOUNTthat 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 nullMutationStatedoes 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.EnsureCreatedAsynccreates one unlessAutoCreateIndexesisfalse. CHANGELOG (Fixed) anddocs/concurrency.mdsay so.Tests
ConsistentWithon 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.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 inEnsureCreatedSeedingTests, which passed on two reruns.TransactionCouchbaseTestfails 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.main's baseline: 83 tests now pass, including all 68 overlapping GraphUpdates variants and 6TransactionCouchbaseTesttests. 2 new failures,Select_Union_different_fields_in_anonymous_with_subquery(async: True)andCan_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'sflaky.txt. The JsonQuery/JsonUpdate aborts are also onmain; 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.UpdatesCouchbaseTesttests 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'sflaky.txt(a union result, no count involved). No class aborted.Ticket: CBEF-132
🤖 Generated with Claude Code