Skip to content

[API Proposal]: ability to have stable hash codes #88031

@insouciiance

Description

@insouciiance

Background and motivation

Currently, certain types & methods use Interop.GetRandomBytes (e.g. HashCode or string.GetHashCode) to have a random seed for hash codes, meaning they return different hash for the same value on different program runs.

However it would really nice to have the ability to stabilize all hash codes across multiple runs.
One use case for this feature would be to detect changes in behaviour on CI and verify if those were intended or not. To have deterministic rendering results we would expect deterministic hash codes so that, for example, enumerating a set or a dictionary is stable (of course no ordering is expected at all, but it should be deterministic).

API Proposal

[AttributeUsage(AttributeTargets.Assembly)]
public sealed class AssemblyStabilizedHashCodeAlgorithmAttribute : Attribute
{
    public bool Enabled { get; }

    public AssemblyStabilizedHashCodeAlgorithmAttribute(bool enabled);
}

API Usage

<ItemGroup>
  <AssemblyAttribute Include="System.Runtime.AssemblyStabilizedHashCodeAlgorithm">
    <_Parameter1>true</_Parameter1>
  </AssemblyAttribute>
</ItemGroup>

or

[assembly: System.Runtime.AssemblyStabilizedHashCodeAlgorithm(true)]

Alternative Designs

<PropertyGroup>
    <UseStabilizedHashCodeAlgorithm>true</UseStabilizedHashCodeAlgorithm>
</PropertyGroup>

Risks

Hash code randomization is good for security, prevention against DoS attacks, etc. Having stable hash codes across runs may result in hash flooding, so it needs to be toggled explicitly via the assembly attribute or the .csrpoj property.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.Runtimeneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsideration

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions