5 Commits
Author SHA1 Message Date
Nikhil Gupta ab29aa793d [HashTreeCollections] Fix union misplacing items pushed into a new child
`copyNodeAndPushItemIntoNewChild` takes an existing item out of `self` and
pushes it into `newChild`, which is then installed as a child of `self` at
`bucket`. `newChild` therefore sits one level below `self`, but the item was
inserted into it using `self`'s level:

    let r = newChild.inserting(level, item, hash)

Navigating with the parent's level picks the wrong hash digit, so the item —
and the subtree it is merged with — end up filed under a path that doesn't
match their hash.

`TreeSet.union` reaches this when it merges an incoming collision node against
an item already occupying that bucket. The result is a set that still reports
the right `count` and still yields every element when iterated, but whose
misplaced members cannot be found by `contains`, since lookup navigates by
hash:

    let a1 = RawCollider(1, "A")
    let a2 = RawCollider(2, "B")
    let c1 = RawCollider(5, "ACAD")
    let c2 = RawCollider(6, "ACAD")

    let u = TreeSet([a1, a2]).union(TreeSet([c1, c2]))
    u.count          // 4
    Array(u)         // [2#B, 1#A, 5#ACAD, 6#ACAD]
    u.contains(c1)   // false
    u.contains(a1)   // false

Building the same set directly with `TreeSet([a1, a2, c1, c2])` is unaffected;
only the structural merge paths are.

Insert at `level.descend()` instead.

Enumerating every pair of subsets of the shared `testItems` fixture, 171 of
4096 unions contained at least one member that `contains` could not find.
With this change all 4096 are clean.

Also fix the full invariant check, which could not run on any tree containing
a collision node. Collision nodes store their item count in `itemMap` and
`childMap` rather than a set of occupied buckets, so treating those bitmaps as
buckets walks items that aren't there — a node holding 5 items has
`itemMap._value == 5`, whose bits nominate buckets 0 and 2. The bucket loop now
only runs for regular nodes. Before this, `swift test
-Xswiftc -DCOLLECTIONS_INTERNAL_CHECKS` trapped immediately in
HashTreeCollections; that trap was also what kept the invariant check from
reporting the misplaced nodes above.

Add a regression test alongside the existing `test_union_collision_node_ordering`.
2026-09-25 14:11:23 +05:30
Karoy Lorentey 1c69635852 Add SPDX-License-Identifier tags 2026-03-05 19:39:24 -08:00
Karoy Lorentey d9b09ecde8 Update copyright dates 2026-03-05 19:39:20 -08:00
Karoy Lorentey c33444df6f [HashTreeCollections] Update copyright notices 2024-02-02 16:20:20 -08:00
Karoy Lorentey 424c8ece98 HashTreeCollections: Qualify internal type names with “Hash”
This makes them unique throughout the package, allowing this code to be built as a single, huge module.
2023-03-21 16:37:22 -07:00