[SortedCollections] _Node.UnsafeHandle.concatenateWith: Fix children buffer corruption in simple-merge path

When two same-depth internal nodes plus a separator fit in a single
node, `concatenateWith` takes the simple-merge branch.  The non-leaf
subbranch was calling `moveInitializeElements` to move children, but
that method operates on the keys/values buffers, not the children
buffer.  The consequences:

- The re-read from `rightHandle.keys[0..<childCount]` hits slots that
  were already moved-out by the preceding `moveInitializeElements`
  call, which is UB.
- Writes land on top of keys just written by that same prior call,
  corrupting them.
- `self.children` is left with its original (too few) children plus
  uninitialized slots; subsequent traversal dereferences garbage.
- `rightHandle.drop()` deallocates the children buffer without
  transferring ownership, leaking the `_Node.Storage` references.

Fix: call `moveInitializeChildren` instead, matching the splinter
branch just above.

Add `test_join_nonLeafSimpleMerge`, which builds two depth-1 internal
nodes whose combined element count fits in capacity 4 and joins them
via `_Node.join`.  Without the fix the resulting tree's children are
undefined, so iteration either crashes or yields garbage.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Karoy LorenteyandClaude Sonnet 4.6 committed 2026-05-01 17:14:21 -07:00
1 parent fb65ce5c6e
commit 8f2e4bba20
2 files changed
+36 -3

No files matched your search

@@ -498,7 +498,7 @@ extension _Node.UnsafeHandle {
)
if !self.isLeaf {
rightHandle.moveInitializeElements(
rightHandle.moveInitializeChildren(
count: rightHandle.childCount,
fromSlot: 0,
toSlot: self.childCount,
@@ -21,16 +21,49 @@ final class BTreeBuilderTests: CollectionTestCase {
func test_append() {
withEvery("size", in: 0..<1000) { size in
var builder = _BTree<Int, Int>.Builder(capacity: 4)
for i in 0..<size {
builder.append((i, -i))
}
let tree = builder.finish()
tree.checkInvariants()
expectEqualElements(tree, (0..<size).map { (key: $0, value: -$0) })
}
}
func test_join_nonLeafSimpleMerge() {
// Two depth-1 internal nodes whose combined element count plus the
// separator fits in a single internal node of capacity 4. This
// exercises the simple-merge branch of
// `_Node.UnsafeHandle.concatenateWith` on non-leaf nodes, which must
// move children via `moveInitializeChildren` rather than
// `moveInitializeElements`.
let capacity = 4
var leftNode = tree {
tree { 0; 1; 2 }
3
tree { 4; 5 }
}.toNode(ofCapacity: capacity)
var rightNode = tree {
tree { 7; 8 }
9
tree { 10; 11; 12 }
}.toNode(ofCapacity: capacity)
let merged = _Node.join(
&leftNode,
with: &rightNode,
separatedBy: (key: 6, value: 12),
capacity: capacity
)
let btree = _BTree(rootedAt: merged, internalCapacity: capacity)
btree.checkInvariants()
expectEqualElements(btree, (0...12).map { (key: $0, value: $0 * 2) })
}
}
#endif