System.IndexOutOfRangeException in TlsOverPerCoreLockedStacksArrayPool during gen2 gc
Hi !
I noticed that my .Net core app (v2.1.4) is throwing System.IndexOutOfRangeException every gen2 collection.
The stacktrace is :
at System.Buffers.TlsOverPerCoreLockedStacksArrayPool`1.PerCoreLockedStacks.Trim(UInt32 tickCount, Int32 id, MemoryPressure pressure, Int32[] bucketSizes)
at System.Buffers.TlsOverPerCoreLockedStacksArrayPool`1.Trim()
at System.Gen2GcCallback.Finalize()
We call trim on each PerCoreLockedStacks with _bucketArraySizes being an array of int of size 17 https://github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs#L68
TlsOverPerCoreLockedStacksArrayPool
public bool Trim()
{
int milliseconds = Environment.TickCount;
MemoryPressure pressure = GetMemoryPressure();
ArrayPoolEventSource log = ArrayPoolEventSource.Log;
if (log.IsEnabled())
log.BufferTrimPoll(milliseconds, (int)pressure);
foreach (PerCoreLockedStacks bucket in _buckets)
{
bucket?.Trim((uint)milliseconds, Id, pressure, _bucketArraySizes);
}
...
However in PerCoreLockedStacks we set an array of size ProcessorCount to _perCoreStacks
public PerCoreLockedStacks()
{
// Create the stacks. We create as many as there are processors, limited by our max.
var stacks = new LockedStack[Math.Min(Environment.ProcessorCount, MaxPerCorePerArraySizeStacks)];
for (int i = 0; i < stacks.Length; i++)
{
stacks[i] = new LockedStack();
}
_perCoreStacks = stacks;
}
And when we trim those PerCoreLockedStacks, we reach an IndexOutOfRangeException when accessing bucketSizes elements with index >= 17 (My system has 24 logical cores)
PerCoreLockedStacks
public bool Trim(uint tickCount, int id, MemoryPressure pressure, int[] bucketSizes)
{
LockedStack[] stacks = _perCoreStacks;
for (int i = 0; i < stacks.Length; i++)
{
stacks[i].Trim(tickCount, id, pressure, bucketSizes[i]);
}
return true;
}
https://github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs#L373
Please let me know if I missed anything ! Obvious fix could be to replace ProcessorCount by 17, but I'm not sure about the impact of this.
Thanks !
Here are the metrics which helped me identify this issue

Thanks. That logic is definitely incorrect.
I am having an issue that looks suspiciously like this one.
Microsoft.AspNetCore 2.2.0
Microsoft.NetCoreApp.2.2.4
Kestrel/Stateless/ServiceFabric
2* E5-2630v2 12 Cores 24 Threads
Yes, that looks like the same issue. It was fixed for 3.0.
@stephentoub Thanks, any idea when 3.0 will be released?
https://github.com/dotnet/core/blob/master/roadmap.md