Skip to content

B+Tree EntryCount over-counts on an AllowMultiple index whenever keys arrive out of sorted order #783

Closed

Description

@nockawa

Summary

IBTreeIndex.EntryCount reports a value that grows with the ROW count instead of the distinct-key count, for any AllowMultiple index whose keys do not arrive in sorted order. Measured: 2 000 rows over 50 distinct keys reported 1 142; over 250 distinct keys, 1 867.

The tree itself stays structurally correct throughout — the leaf chain holds exactly one entry per distinct key, no key appears twice, and every row is returned by query. Only the counter drifts.

This is a violation of rule IXS-05 (EntryCount equals the number of items materialised by the leaf-chain walk).

Why it matters beyond hygiene

IndexStatistics.EntryCount is documented and consumed as the index's distinct-key count. The selectivity estimators divide by it, and the planner picks both the primary scan stream and the cluster scan path from the result. So every query over an AllowMultiple index built in realistic key order was costed from a number that describes nothing — and the error grows with table size.

The count is also persisted (BTree.WriteToDirectory writes entry.Count = _count) and read back on load, so the drift survives a restart.

Cause

BTree.InsertArguments.Added is set as a side effect of reading the value:

public int GetValue()
{
    Added = true;      // BTree.cs
    return _value;
}

It is meant to mean a new leaf entry was created; it actually means somebody read the value. The duplicate-key branch reads the value in order to append it into the existing key's buffer, so it flips Added, and the general descent's tail

if (args.Added) { IncCount(); }     // BTree.Insert.cs

increments the entry count for a key that was never added.

Why it went unnoticed

Insertion order decides whether the bug is reachable:

duplicate key lands on route counts
rightmost / leftmost leaf, or a single-leaf tree OLC fast path — returns Completed before the counting tail correct
anywhere else general descent → NodeWrapper.InsertLeaf +1 per duplicate row

Keys arriving in ascending order always land on the rightmost-append fast path, and every existing test builds its trees that way. Cyclic keys (i % k) route through the general descent instead.

Both verifiers cited by IXS-05 are [RuleMutant]s: they prove the validator reports an injected violation, not that the tree maintains the invariant. Nothing ran CheckConsistency on an AllowMultiple tree built in non-sorted order, so 5 295 tests walked past this.

Repro

10 000 rows, one [Index(AllowMultiple = true)] int field, EntryCount versus a walk of EnumerateLeaves():

layout distinct keys EntryCount leaf entries
key = i / fanout (sorted) 50 50 50
key = i % 50 (cyclic) 50 1 142 50
key = i % 250 (cyclic) 250 1 867 250

Fix

Give InsertArguments a side-effect-free accessor for the duplicate-append case and use it at all six such sites; GetValue() remains only at the three sites that genuinely create an entry.

Verified that Added drives nothing else: InsertIterative's completed out-parameter is set by control flow, and the unique-constraint check keys on !AllowMultiple.

Acceptance criteria

  • EntryCount equals the distinct-key count for an AllowMultiple index regardless of insertion order
  • A regression test asserts the leaf chain before the counter, so "one entry per row" fails differently from "counter drifted"
  • The test is tagged [VerifiesRule("IXS-05")] and demonstrably fails against unfixed code
  • IXS-05 records the occurrence and gains a non-mutant verifier

Activity

  1. updated Product Engine, Area Indexes, Priority P1-High and Estimate S on Aug 11, 2026
  2. added theissue type on Aug 11, 2026
  3. added a commit that references this issue on Aug 12, 2026
  4. moved this to In Progress in Typhonon Aug 12, 2026
  5. nockawa commented on Aug 12, 2026

    @nockawa
    CollaboratorAuthor

    Fixed in #786 (squashed as e28376af).

    InsertArguments.ValueForExistingKey — a side-effect-free accessor — at all six duplicate-append sites; GetValue() keeps the flag and remains only at the three that genuinely create an entry. Five of the six returned before the counting tail and were already harmless; converted anyway so the invariant holds by construction rather than by which paths happen to read the flag afterwards.

    BTreeEntryCountTests (9 cases, [VerifiesRule("IXS-05")]) asserts the leaf chain before the counter, so a tree that really did hold one entry per row fails differently from one whose counter drifted — different defects, different fixes. Ablating the live site fails exactly the two cyclic cases plus the statistics case, while the four ascending and two degenerate ones stay green: the same partition the mechanism predicts.

    IXS-05 records the occurrence and gains its first verifier that exercises the tree rather than the validator — both it previously cited are mutants, which is the gap this fell through.

  6. moved this from In Progress to Done in Typhonon Aug 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Fields

    Priority

    P1-High

    Estimate

    S

    Area

    Indexes

    Start date

    None yet

    Target date

    None yet

    Bug status

    None yet

    Product

    Engine

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions