runtime icon indicating copy to clipboard operation
runtime copied to clipboard

ImmutableList<T>.LastIndexOf(...) appears to be missing a guard clause

Open Saborion opened this issue 4 years ago • 18 comments

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:

  1. ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) should throw if index equals the size of the collection, the same way startIndex does for ImmutableArray<T>.LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer ).
  2. ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) should return the correct index of the last item found when the index argument 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.

Saborion avatar Jun 19 '22 05:06 Saborion

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:

  1. ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) should throw if index equals the size of the collection, the same way startIndex does for ImmutableArray<T>.LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer ).
  2. ImmutableList<T>.LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer) should return the correct index of the last item found when the index argument 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:

area-System.Collections

Milestone: -

ghost avatar Jun 19 '22 05:06 ghost

@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 avatar Jul 07 '22 15:07 krwq

@krwq Uh oh. A PR for something this important. Scary.

I'll make an attempt, sure.

Saborion avatar Jul 07 '22 18:07 Saborion

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?

stephentoub avatar Jul 10 '22 18:07 stephentoub

Can you share repro?

Sorry, my bad, it seems I've been executing the wrong test. I've deleted my comment above.

quixoticaxis avatar Jul 10 '22 18:07 quixoticaxis

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.

quixoticaxis avatar Jul 10 '22 19:07 quixoticaxis

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.

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.

Saborion avatar Jul 12 '22 23:07 Saborion

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?

Saborion avatar Jul 12 '22 23:07 Saborion

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 LastIndexOf and FindLastIndex
  • Add a guard clause for the upper bound of the index parameter to throw an exception when index is greater than or equal to Count (consistent with ImmutableArray<T>)

prozolic avatar Jan 14 '26 23:01 prozolic

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 LastIndexOf with index == Count and verify it throws ArgumentOutOfRangeException.
  • Add a test with index == Count - 1 confirming correct behavior.
  • Add tests for edge cases: empty list, single-element list, multiple matches.
  • Verify that ImmutableList and ImmutableArray have 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}");

jeffhandley avatar Feb 08 '26 10:02 jeffhandley

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 avatar Feb 09 '26 02:02 prozolic

@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 avatar Feb 11 '26 02:02 ViveliDuCh

@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

prozolic avatar Feb 11 '26 10:02 prozolic

@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?

prozolic avatar Feb 11 '26 23:02 prozolic

Would that be acceptable?

@prozolic Yes, it would. Thanks for addressing it!

ViveliDuCh avatar Feb 12 '26 20:02 ViveliDuCh

I have created a follow-up PR at #124560, so please continue reviewing it.

prozolic avatar Feb 18 '26 16:02 prozolic

@ViveliDuCh @jeffhandley Thank you for reviewing the PR!

prozolic avatar Feb 24 '26 13:02 prozolic

This has been resolved by #124161 and #124560. Can this be closed?

prozolic avatar Mar 25 '26 13:03 prozolic