ImmutableList<T>.LastIndexOf(...) appears to be missing a guard clause
Description
Searching for the last index of an item in an instance of ImmutableList<T> that holds at least one matching item can return the wrong index. This happens when the index argument passed in to ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) equals the collection size, at which point the returned index will be off by one (+1), e.g. if the actual index is 2 the returned index will be 3.
Reproduction Steps
A .NET 6 console application with the following top level statements:
using System.Collections.Immutable;
var lastIndexOf = new[] { "NonMatch", "Match", "Match", "NonMatch" }
.ToImmutableList()
.LastIndexOf("Match", index: 3, count: 4, equalityComparer: null); // Returns 2 (correct)
var lastIndexOf2 = new[] { "NonMatch", "Match", "Match", "NonMatch" }
.ToImmutableList()
.LastIndexOf("Match", index: 4, count: 4, equalityComparer: null); // Returns 3 (incorrect, should throw?)
Console.WriteLine($"Last index when 'index' argument equals count - 1: {lastIndexOf}");
Console.WriteLine($"Last index when 'index' argument equals count : {lastIndexOf2}");
Expected behavior
One of the two below:
ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer)should throw ifindexequals the size of the collection, the same waystartIndexdoes forImmutableArray<T>.LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer ).ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer)should return the correct index of the last item found when theindexargument equals the size of the collection.
Actual behavior
The returned index is bigger (+1) than the correct index.
Regression?
No response
Known Workarounds
No response
Configuration
- .NET 6
- Windows 10, 64-bit
- x64
- Don't know if it is specific to this version
Other information
I suspect that the culprit is a missing guard clause for the upper boundary for the index parameter in the internal int LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) method (line 786 as of this writing) in ImmutableList_1.Node.cs. This method is called from ImmutableList_1.cs.
Contrast the guard clause in the above mentiond method with the one from ImmutableArray_1.Builder.cs
ImmutableList<T> - Requires.Range(index >= 0, nameof(index));
vs
ImmutableArray<T> - Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex));
where the latter makes more sense.
Tagging subscribers to this area: @dotnet/area-system-collections See info in area-owners.md if you want to be subscribed.
Issue Details
Description
Searching for the last index of an item in an instance of ImmutableList<T> that holds at least one matching item can return the wrong index. This happens when the index argument passed in to ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) equals the collection size, at which point the returned index will be off by one (+1), e.g. if the actual index is 2 the returned index will be 3.
Reproduction Steps
A .NET 6 console application with the following top level statements:
using System.Collections.Immutable;
var lastIndexOf = new[] { "NonMatch", "Match", "Match", "NonMatch" }
.ToImmutableList()
.LastIndexOf("Match", index: 3, count: 4, equalityComparer: null); // Returns 2 (correct)
var lastIndexOf2 = new[] { "NonMatch", "Match", "Match", "NonMatch" }
.ToImmutableList()
.LastIndexOf("Match", index: 4, count: 4, equalityComparer: null); // Returns 3 (incorrect, should throw?)
Console.WriteLine($"Last index when 'index' argument equals count - 1: {lastIndexOf}");
Console.WriteLine($"Last index when 'index' argument equals count : {lastIndexOf2}");
Expected behavior
One of the two below:
ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer)should throw ifindexequals the size of the collection, the same waystartIndexdoes forImmutableArray<T>.LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer ).ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer)should return the correct index of the last item found when theindexargument equals the size of the collection.
Actual behavior
The returned index is bigger (+1) than the correct index.
Regression?
No response
Known Workarounds
No response
Configuration
- .NET 6
- Windows 10, 64-bit
- x64
- Don't know if it is specific to this version
Other information
I suspect that the culprit is a missing guard clause for the upper boundary for the index parameter in the internal int LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) method (line 786 as of this writing) in ImmutableList_1.Node.cs. This method is called from ImmutableList_1.cs.
Contrast the guard clause in the above mentiond method with the one from ImmutableArray_1.Builder.cs
ImmutableList<T> - Requires.Range(index >= 0, nameof(index));
vs
ImmutableArray<T> - Requires.Range(startIndex >= 0 && startIndex < this.Count, nameof(startIndex));
where the latter makes more sense.
| Author: | Saborion |
|---|---|
| Assignees: | - |
| Labels: |
|
| Milestone: | - |
@Saborion this looks like a bug to me. We should match behavior with whatever other collections are doing. Are you perhaps interested in making PR?
@krwq Uh oh. A PR for something this important. Scary.
I'll make an attempt, sure.
By the way, ImmutableArray has the same behavior, it also returns an index in a range that may go out of array's bounds.
Can you share repro?
Can you share repro?
Sorry, my bad, it seems I've been executing the wrong test. I've deleted my comment above.
I've found that FindLastIndex is also bugged for ImmutableList<T> though.
To reproduce:
[Fact] // the test should fail, but passes
public void Index_can_be_calculated_from_beyond_the_boundary()
{
var array = ImmutableList.Create(1, 2, 3, 4);
var index = array.FindLastIndex(55, 4, (element) => element is 3);
Assert.Equal(54, index);
}
Both overrides in the code of Node that take index miss the check on index being less than the length.
I've found that
FindLastIndexis also bugged forImmutableList<T>though.To reproduce:
[Fact] // the test should fail, but passes public void Index_can_be_calculated_from_beyond_the_boundary() { var array = ImmutableList.Create(1, 2, 3, 4); var index = array.FindLastIndex(55, 4, (element) => element is 3); Assert.Equal(54, index); }Both overrides in the code of
Nodethat take index miss the check on index being less than the length.
Yes, good catch. I noticed that as well since I discovered the original bug when writing a wrapper. Chances are I would have missed it though.
I have been busy but was just about to give this a go. Before doing so, however, I am curious. This will be a change of behavior which may have impact on existing applications, since the above mentioned methods (and potentially more) will now start to throw exceptions for previously "accepted" values.
Based on the information in breaking changes I guess the changes to the 2+ mentioned methods would fall into bucket 2, "decreasing the range of accepted values within a given parameter" and would "require talking to the repo owners first".
I am now sure how to get the repo owners input on this? Based on the bot action earlier it seems this fix is for the System.Collections area, and based on area owners the owners are @dotnet/area-system-collections?
I noticed this issue has been open for a while. I'd like to work on a fix if no one is currently assigned to it. Since this would be a breaking change, I'd like to confirm the preferred approach before starting work:
- The APIs to fix are
LastIndexOfandFindLastIndex - Add a guard clause for the upper bound of the
indexparameter to throw an exception when index is greater than or equal toCount(consistent withImmutableArray<T>)
That's great, @prozolic; thanks! I will assign it to you and @ViveliDuCh for her to be prepared to review your PR when it's ready.
Summary
ImmutableList<T>.LastIndexOf returns an incorrect (off-by-one) index when the index parameter equals the collection's Count. Instead of throwing ArgumentOutOfRangeException (as ImmutableArray does), it silently returns a wrong result. A team member confirmed this is a bug and invited a PR.
Expected Fix
Add a missing upper-bound guard clause in ImmutableList_1.Node.cs's LastIndexOf method. The current check is only Requires.Range(index >= 0, nameof(index)), but it should also enforce index < Count (matching ImmutableArray's behavior). The fix is a one-line change to the Requires.Range call, plus potentially adjusting the search logic to avoid the off-by-one.
Test Coverage
- Add a test calling
LastIndexOfwithindex == Countand verify it throwsArgumentOutOfRangeException. - Add a test with
index == Count - 1confirming correct behavior. - Add tests for edge cases: empty list, single-element list, multiple matches.
- Verify that
ImmutableListandImmutableArrayhave consistent behavior for this parameter.
Repro
using System.Collections.Immutable;
var list = new[] { "NonMatch", "Match", "Match", "NonMatch" }.ToImmutableList();
// Returns 2 (correct)
var correct = list.LastIndexOf("Match", index: 3, count: 4, equalityComparer: null);
// Returns 3 (WRONG — should throw ArgumentOutOfRangeException)
var wrong = list.LastIndexOf("Match", index: 4, count: 4, equalityComparer: null);
Console.WriteLine($"Correct: {correct}, Wrong: {wrong}");
Thank you!, @jeffhandley.
I have also fixed the FindLastIndex which has the same bug as LastIndexOf, and submitted a PR for review.
Please let me know if you would like me to exclude FindLastIndex from the PR #124161.
Also, I noticed during PR adjustment that the exceptions thrown for the case of index - count + 1 >= 0 are different between LastIndexOf and FindLastIndex.
If you think it would be better to unify them, please let me know and I will make the correction in a separate PR.
@prozolic great question about the exception inconsistency — I do think unifying them is worth exploring further. I also noticed that, currently, there aren't tests that exercise that specific check.
@ViveliDuCh In my opinion, since ImmutableArray.LastIndexOf and Array.LastIndexOf uses Requires.Range(ArgumentOutOfRangeException) for similar conditional checks, I think it would be better to align with Requires.Range for consistency.
https://github.com/dotnet/runtime/blob/main/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray_1.cs#L261-L263 https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Array.cs#L2153-L2156
@ViveliDuCh @jeffhandley Thank you for checking.
Regarding the Requires.Argument usage in LastIndexOf and FindLastIndex, I plan to change them to Requires.Range for consistency. I would like to create a separate PR to make this change after #124161 is merged. Would that be acceptable?
Would that be acceptable?
@prozolic Yes, it would. Thanks for addressing it!
I have created a follow-up PR at #124560, so please continue reviewing it.
@ViveliDuCh @jeffhandley Thank you for reviewing the PR!
This has been resolved by #124161 and #124560. Can this be closed?