Skip to content

Conversation

@brianchang928
Copy link
Contributor

@brianchang928 brianchang928 commented Aug 13, 2025

This PR fixes an issue where findAnyIndex(forKey:) could return an Index with an incorrect global offset when the matching key was found in an internal B-tree node. While the key lookup itself was correct, the reported offset undercounted the number of elements before the match.

The root cause was that the offset calculation only added the number of preceding keys in the node but did not include the sizes of the preceding child subtrees, including the child at keySlot, which in in-order traversal all come before the matching key.

This PR ensures the calculation to also include the sizes of all child subtrees up to and including handle[childAt: keySlot] when the match is found in an internal node. This ensures Index.offset always matches the true in-order position, keeping index-based operations consistent.

Resolves #138, resolves #366

Checklist

  • I've read the Contribution Guidelines
  • My contributions are licensed under the Swift license.
  • I've followed the coding style of the rest of the project.
  • I've added tests covering all new code paths my change adds to the project (if appropriate).
  • I've added benchmarks covering new functionality (if appropriate).
  • I've verified that my change does not break any existing tests or introduce unexplained benchmark regressions.
  • I've updated the documentation if necessary.

`findAnyIndex(forKey:)` miscomputed the global offset when a key was found in an internal B-tree node, due to missing child subtree counts in the calculation.
Copy link
Member

@lorentey lorentey left a comment

Choose a reason for hiding this comment

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

Thank you!

@lorentey
Copy link
Member

@swift-ci test

1 similar comment
@lorentey
Copy link
Member

@swift-ci test

@lorentey lorentey merged commit b115390 into apple:main Aug 18, 2025
25 checks passed
@lorentey lorentey added this to the 1.3.0 milestone Sep 27, 2025
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.

Incorrect calculating offset for _BTree.findAnyIndex(forKey: Key) SortedSet returns different results for equal indexes.

2 participants