Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Volatile instead of Interlocked where appropriate #6051

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/OpenTelemetry.Api/Trace/TracerProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ protected override void Dispose(bool disposing)
{
if (disposing)
{
var tracers = Interlocked.CompareExchange(ref this.Tracers, null, this.Tracers);
var tracers = Interlocked.Exchange(ref this.Tracers, null);
if (tracers != null)
{
lock (tracers)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ public DirectorySizeTracker(long maxSizeInBytes, string path)
/// <returns>True if space is available else false.</returns>
public bool IsSpaceAvailable(out long currentSizeInBytes)
{
currentSizeInBytes = Interlocked.Read(ref this.directoryCurrentSizeInBytes);
currentSizeInBytes = Volatile.Read(ref this.directoryCurrentSizeInBytes);
return currentSizeInBytes < this.maxSizeInBytes;
}

public void RecountCurrentSize()
{
var size = CalculateFolderSize(this.path);
Interlocked.Exchange(ref this.directoryCurrentSizeInBytes, size);
Volatile.Write(ref this.directoryCurrentSizeInBytes, size);
}

internal static long CalculateFolderSize(string path)
Expand Down
21 changes: 0 additions & 21 deletions src/OpenTelemetry/Internal/InterlockedHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,9 @@ internal static class InterlockedHelper
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Add(ref double location, double value)
{
// Note: Not calling InterlockedHelper.Read here on purpose because it
// is too expensive for fast/happy-path. If the first attempt fails
// we'll end up in an Interlocked.CompareExchange loop anyway.
double currentValue = Volatile.Read(ref location);

var returnedValue = Interlocked.CompareExchange(ref location, currentValue + value, currentValue);
if (returnedValue != currentValue)
{
AddRare(ref location, value, returnedValue);
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Read(ref double location)
=> Interlocked.CompareExchange(ref location, double.NaN, double.NaN);

[MethodImpl(MethodImplOptions.NoInlining)]
private static void AddRare(ref double location, double value, double currentValue)
{
var sw = default(SpinWait);
while (true)
{
sw.SpinOnce();

var returnedValue = Interlocked.CompareExchange(ref location, currentValue + value, currentValue);
if (returnedValue == currentValue)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ private void UpdateMemoryMappedFileFromConfiguration()

private void CloseLogFile()
{
MemoryMappedFile? mmf = Interlocked.CompareExchange(ref this.memoryMappedFile, null, this.memoryMappedFile);
MemoryMappedFile? mmf = Interlocked.Exchange(ref this.memoryMappedFile, null);
if (mmf != null)
{
// Each thread has its own MemoryMappedViewStream created from the only one MemoryMappedFile.
Expand All @@ -181,10 +181,7 @@ private void CloseLogFile()
mmf.Dispose();
}

FileStream? fs = Interlocked.CompareExchange(
ref this.underlyingFileStreamForMemoryMappedFile,
null,
this.underlyingFileStreamForMemoryMappedFile);
FileStream? fs = Interlocked.Exchange(ref this.underlyingFileStreamForMemoryMappedFile, null);
fs?.Dispose();
}

Expand Down
2 changes: 1 addition & 1 deletion src/OpenTelemetry/Logs/LogRecord.cs
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ internal ref LogRecordData GetDataRef()
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void ResetReferenceCount()
{
this.PoolReferenceCount = 1;
Volatile.Write(ref this.PoolReferenceCount, 1);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand Down
5 changes: 0 additions & 5 deletions src/OpenTelemetry/Metrics/AggregationType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,6 @@ namespace OpenTelemetry.Metrics;

internal enum AggregationType
{
/// <summary>
/// Invalid.
/// </summary>
Invalid = -1,

/// <summary>
/// Calculate SUM from incoming delta measurements.
/// </summary>
Expand Down
4 changes: 2 additions & 2 deletions src/OpenTelemetry/Metrics/Exemplar/Exemplar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ internal void Update<T>(in ExemplarMeasurement<T> measurement)
this.StoreRawTags(measurement.Tags);
}

Interlocked.Exchange(ref this.isCriticalSectionOccupied, 0);
Volatile.Write(ref this.isCriticalSectionOccupied, 0);
Copy link
Contributor

@utpilla utpilla Jan 10, 2025

Choose a reason for hiding this comment

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

We need to consider the memory ordering guarantees of Volatile.Write. With Interlocked methods, the read/writes would not be moved before or after a given Interlocked method.

With volatile writes, read/writes that happen after a given Volatile.Write method can be moved before that Volatile.Write method. We need to evaluate if that affects the correctness of our code. There are some write operations that we do after releasing the locks (for exemplar and MetricPoint updates):

  • Call OnCollected for Exemplars which resets the internal measurement state
  • Update MetricStatus to CollectPending when updating MetricPoints

Copy link
Author

Choose a reason for hiding this comment

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

I went over all uses of Interlocked and also checked the code flow after these lock releases. I now found a few places where the current code incorrectly relies on the preceding interlocked operation for memory ordering, for example in case of MetricPoint.UpdateWithExemplar the order of operations is currently:

Interlocked.Exchange(ref this.runningValue.AsLong, number); // full fence
this.UpdateExemplar(number, tags, offerExemplar); // could run arbitrary lock-free code, though in practice uses locks
this.MetricPointStatus = MetricPointStatus.CollectPending; // no memory ordering guarantees, could become observable before exemplar updates

With this PR:

Volatile.Write(ref this.runningValue.AsLong, number); // release
this.UpdateExemplar(number, tags, offerExemplar);
Volatile.Write(ref this.status, (byte)MetricPointStatus.CollectPending); // release, guarantees all exemplar updates become observable before

}

internal void Reset()
Expand Down Expand Up @@ -168,7 +168,7 @@ internal void Collect(ref Exemplar destination, bool reset)
destination.Reset();
}

Interlocked.Exchange(ref this.isCriticalSectionOccupied, 0);
Volatile.Write(ref this.isCriticalSectionOccupied, 0);
}

internal readonly void Copy(ref Exemplar destination)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ protected override void OnCollected()
// Reset internal state irrespective of temporality.
// This ensures incoming measurements have fair chance
// of making it to the reservoir.
this.measurementState = DefaultMeasurementState;
Volatile.Write(ref this.measurementState, DefaultMeasurementState);
}

private void Offer<T>(in ExemplarMeasurement<T> measurement)
Expand Down
63 changes: 27 additions & 36 deletions src/OpenTelemetry/Metrics/MetricPoint/MetricPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using OpenTelemetry.Internal;

namespace OpenTelemetry.Metrics;

/// <summary>
/// Represents a metric data point.
/// </summary>
[StructLayout(LayoutKind.Auto)]
Copy link
Author

Choose a reason for hiding this comment

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

Using auto-layout together with the field type change for the two enums below reduces the struct size from 72 bytes to 64 bytes.

public struct MetricPoint
{
// Represents the number of update threads using this MetricPoint at any given point of time.
Expand All @@ -22,8 +24,9 @@ public struct MetricPoint
private const int DefaultSimpleReservoirPoolSize = 1;

private readonly AggregatorStore aggregatorStore;
private readonly byte type;

private readonly AggregationType aggType;
private byte status;

private MetricPointOptionalComponents? mpComponents;

Expand All @@ -48,7 +51,7 @@ internal MetricPoint(
Debug.Assert(histogramExplicitBounds != null, "Histogram explicit Bounds was null.");
Debug.Assert(!aggregatorStore!.OutputDelta || lookupData != null, "LookupData was null.");

this.aggType = aggType;
this.type = (byte)aggType;
this.Tags = new ReadOnlyTagCollection(tagKeysAndValues);
this.runningValue = default;
this.snapshotValue = default;
Expand Down Expand Up @@ -145,11 +148,8 @@ public readonly ReadOnlyTagCollection Tags

internal MetricPointStatus MetricPointStatus
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get;

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private set;
readonly get => (MetricPointStatus)this.status;
private set => this.status = (byte)value;
}

// When the AggregatorStore is reclaiming MetricPoints, this serves the purpose of validating the a given thread is using the right
Expand All @@ -160,6 +160,10 @@ internal MetricPointStatus MetricPointStatus

internal readonly bool IsInitialized => this.aggregatorStore != null;

#pragma warning disable SA1300 // TEMP naming supression (will rename to Type)
private readonly AggregationType aggType => (AggregationType)this.type;
#pragma warning restore SA1300

/// <summary>
/// Gets the sum long value associated with the metric point.
/// </summary>
Expand Down Expand Up @@ -394,7 +398,7 @@ internal void Update(long number)
case AggregationType.LongSumIncomingCumulative:
case AggregationType.LongGauge:
{
Interlocked.Exchange(ref this.runningValue.AsLong, number);
Volatile.Write(ref this.runningValue.AsLong, number);
Copy link
Member

Choose a reason for hiding this comment

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

curious, if this shows improvement in the metric stress tests?

break;
}

Expand Down Expand Up @@ -451,7 +455,7 @@ internal void UpdateWithExemplar(long number, ReadOnlySpan<KeyValuePair<string,
case AggregationType.LongSumIncomingCumulative:
case AggregationType.LongGauge:
{
Interlocked.Exchange(ref this.runningValue.AsLong, number);
Volatile.Write(ref this.runningValue.AsLong, number);
break;
}

Expand Down Expand Up @@ -510,7 +514,7 @@ internal void Update(double number)
case AggregationType.DoubleSumIncomingCumulative:
case AggregationType.DoubleGauge:
{
Interlocked.Exchange(ref this.runningValue.AsDouble, number);
Volatile.Write(ref this.runningValue.AsDouble, number);
break;
}

Expand Down Expand Up @@ -567,7 +571,7 @@ internal void UpdateWithExemplar(double number, ReadOnlySpan<KeyValuePair<string
case AggregationType.DoubleSumIncomingCumulative:
case AggregationType.DoubleGauge:
{
Interlocked.Exchange(ref this.runningValue.AsDouble, number);
Volatile.Write(ref this.runningValue.AsDouble, number);
break;
}

Expand Down Expand Up @@ -622,7 +626,7 @@ internal void TakeSnapshot(bool outputDelta)
{
if (outputDelta)
{
long initValue = Interlocked.Read(ref this.runningValue.AsLong);
long initValue = Volatile.Read(ref this.runningValue.AsLong);
this.snapshotValue.AsLong = initValue - this.deltaLastValue.AsLong;
this.deltaLastValue.AsLong = initValue;
this.MetricPointStatus = MetricPointStatus.NoCollectPending;
Expand All @@ -631,12 +635,12 @@ internal void TakeSnapshot(bool outputDelta)
// This ensures no Updates get Lost.
if (initValue != Interlocked.Read(ref this.runningValue.AsLong))
{
this.MetricPointStatus = MetricPointStatus.CollectPending;
Volatile.Write(ref this.status, (byte)MetricPointStatus.CollectPending);
}
}
else
{
this.snapshotValue.AsLong = Interlocked.Read(ref this.runningValue.AsLong);
this.snapshotValue.AsLong = Volatile.Read(ref this.runningValue.AsLong);
}

break;
Expand All @@ -647,51 +651,38 @@ internal void TakeSnapshot(bool outputDelta)
{
if (outputDelta)
{
double initValue = InterlockedHelper.Read(ref this.runningValue.AsDouble);
double initValue = Volatile.Read(ref this.runningValue.AsDouble);
this.snapshotValue.AsDouble = initValue - this.deltaLastValue.AsDouble;
this.deltaLastValue.AsDouble = initValue;
this.MetricPointStatus = MetricPointStatus.NoCollectPending;

// Check again if value got updated, if yes reset status.
// This ensures no Updates get Lost.
if (initValue != InterlockedHelper.Read(ref this.runningValue.AsDouble))
long initValueLong = BitConverter.DoubleToInt64Bits(initValue);
if (initValueLong != Interlocked.Read(ref this.runningValue.AsLong))
{
this.MetricPointStatus = MetricPointStatus.CollectPending;
Volatile.Write(ref this.status, (byte)MetricPointStatus.CollectPending);
}
}
else
{
this.snapshotValue.AsDouble = InterlockedHelper.Read(ref this.runningValue.AsDouble);
this.snapshotValue.AsLong = Volatile.Read(ref this.runningValue.AsLong);
}

break;
}

case AggregationType.LongGauge:
{
this.snapshotValue.AsLong = Interlocked.Read(ref this.runningValue.AsLong);
this.MetricPointStatus = MetricPointStatus.NoCollectPending;

// Check again if value got updated, if yes reset status.
// This ensures no Updates get Lost.
if (this.snapshotValue.AsLong != Interlocked.Read(ref this.runningValue.AsLong))
{
this.MetricPointStatus = MetricPointStatus.CollectPending;
}

break;
}

case AggregationType.DoubleGauge:
{
this.snapshotValue.AsDouble = InterlockedHelper.Read(ref this.runningValue.AsDouble);
this.snapshotValue.AsLong = Volatile.Read(ref this.runningValue.AsLong);
this.MetricPointStatus = MetricPointStatus.NoCollectPending;

// Check again if value got updated, if yes reset status.
// This ensures no Updates get Lost.
if (this.snapshotValue.AsDouble != InterlockedHelper.Read(ref this.runningValue.AsDouble))
if (this.snapshotValue.AsLong != Interlocked.Read(ref this.runningValue.AsLong))
{
this.MetricPointStatus = MetricPointStatus.CollectPending;
Volatile.Write(ref this.status, (byte)MetricPointStatus.CollectPending);
}

break;
Expand Down Expand Up @@ -1078,7 +1069,7 @@ private void CompleteUpdate()
// it had no update.
// TODO: For Delta, this can be mitigated
// by ignoring Zero points
this.MetricPointStatus = MetricPointStatus.CollectPending;
Volatile.Write(ref this.status, (byte)MetricPointStatus.CollectPending);

this.CompleteUpdateWithoutMeasurement();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public void AcquireLock()
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReleaseLock()
{
Interlocked.Exchange(ref this.isCriticalSectionOccupied, 0);
Volatile.Write(ref this.isCriticalSectionOccupied, 0);
}

// Note: This method is marked as NoInlining because the whole point of it
Expand Down