Skip to content

Instantly share code, notes, and snippets.

@BradBarnich
Created July 5, 2026 01:59
Show Gist options
  • Select an option

  • Save BradBarnich/4e6368d7e3ae5a32896852c146e0eb3f to your computer and use it in GitHub Desktop.

Select an option

Save BradBarnich/4e6368d7e3ae5a32896852c146e0eb3f to your computer and use it in GitHub Desktop.
Rare Regex NRE on arm64, most reliable on graviton4
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
var options = Options.Parse(args);
const string Pattern = @"EDW-\d{3}";
const string Replacement = "badamespace";
const string NonSimplePattern = @"(?<match>EDW-\d{3})(?<empty>)";
const string NonSimpleReplacement = "badnamespace${empty}";
const string Input = "EDW-987 null-code dependence";
LogEnvironment(options);
var replacements = Enumerable
.Range(0, options.Regexes)
.Select(_ => new SharedReplacement(
new Regex(
options.Mode == ReplacementMode.NonSimple ? NonSimplePattern : Pattern,
RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.ExplicitCapture,
TimeSpan.FromSeconds(10)),
options.Mode == ReplacementMode.NonSimple ? NonSimpleReplacement : Replacement,
options.Mode))
.ToArray();
var failures = new ConcurrentQueue<Exception>();
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(options.Seconds));
var iterations = 0L;
var sw = Stopwatch.StartNew();
Console.WriteLine(
"Starting: workers={0}, regexes={1}, seconds={2}, mode={3}, pattern={4}, replacement={5}, input={6}",
options.Workers,
replacements.Length,
options.Seconds,
options.Mode,
options.Mode == ReplacementMode.NonSimple ? NonSimplePattern : Pattern,
options.Mode == ReplacementMode.NonSimple ? NonSimpleReplacement : Replacement,
Input);
var reporter = Task.Run(async () =>
{
while (!cts.IsCancellationRequested && failures.IsEmpty)
{
await Task.Delay(TimeSpan.FromSeconds(10), cts.Token).ContinueWith(_ => { });
Console.WriteLine(
"progress elapsed={0:n1}s iterations={1:n0} rate={2:n0}/s",
sw.Elapsed.TotalSeconds,
iterations,
iterations / Math.Max(1, sw.Elapsed.TotalSeconds));
}
});
try
{
Parallel.For(
0,
options.Workers,
new ParallelOptions { MaxDegreeOfParallelism = options.Workers, CancellationToken = cts.Token },
worker =>
{
var localIterations = 0L;
var index = worker % replacements.Length;
while (!cts.IsCancellationRequested && failures.IsEmpty)
{
try
{
var output = replacements[index].Transform(Input);
if (output is null)
{
throw new InvalidOperationException("Regex.Replace returned null.");
}
}
catch (Exception ex)
{
var failure = new ReproFailureException(worker, localIterations, index, ex);
if (options.FailFast)
{
Environment.FailFast("Regex replacement repro failed.", failure);
Process.GetCurrentProcess().Kill(entireProcessTree: true);
}
failures.Enqueue(failure);
cts.Cancel();
break;
}
localIterations++;
Interlocked.Increment(ref iterations);
index = (index + 1) % replacements.Length;
}
});
}
catch (OperationCanceledException)
{
// Expected after timeout or after a worker captures the interesting exception.
}
cts.Cancel();
await reporter;
sw.Stop();
Console.WriteLine("finished elapsed={0:n1}s iterations={1:n0}", sw.Elapsed.TotalSeconds, iterations);
if (failures.TryDequeue(out var failure))
{
Console.Error.WriteLine(failure);
return 1;
}
return 0;
static void LogEnvironment(Options options)
{
Console.WriteLine("Runtime={0}", RuntimeInformation.RuntimeIdentifier);
Console.WriteLine("Framework={0}", RuntimeInformation.FrameworkDescription);
Console.WriteLine("OS={0}", RuntimeInformation.OSDescription);
Console.WriteLine("ProcessArchitecture={0}", RuntimeInformation.ProcessArchitecture);
Console.WriteLine("OSArchitecture={0}", RuntimeInformation.OSArchitecture);
Console.WriteLine("COMPlus_ReadyToRun={0}", GetRuntimeSetting("ReadyToRun"));
Console.WriteLine("COMPlus_TieredCompilation={0}", GetRuntimeSetting("TieredCompilation"));
Console.WriteLine("COMPlus_JitNoInline={0}", GetRuntimeSetting("JitNoInline"));
Console.WriteLine("COMPlus_EnableHWIntrinsic={0}", GetRuntimeSetting("EnableHWIntrinsic"));
Console.WriteLine("Options={0}", options);
if (!File.Exists("/proc/cpuinfo"))
{
return;
}
Console.WriteLine("CPU info:");
foreach (var line in File.ReadLines("/proc/cpuinfo").Where(IsInterestingCpuInfoLine).Take(32))
{
Console.WriteLine(line);
}
}
static string GetRuntimeSetting(string name) =>
Environment.GetEnvironmentVariable($"DOTNET_{name}")
?? Environment.GetEnvironmentVariable($"COMPlus_{name}")
?? "(unset)";
static bool IsInterestingCpuInfoLine(string line) =>
line.StartsWith("processor", StringComparison.OrdinalIgnoreCase)
|| line.StartsWith("Features", StringComparison.OrdinalIgnoreCase)
|| line.StartsWith("CPU implementer", StringComparison.OrdinalIgnoreCase)
|| line.StartsWith("CPU architecture", StringComparison.OrdinalIgnoreCase)
|| line.StartsWith("CPU variant", StringComparison.OrdinalIgnoreCase)
|| line.StartsWith("CPU part", StringComparison.OrdinalIgnoreCase)
|| line.StartsWith("CPU revision", StringComparison.OrdinalIgnoreCase);
sealed record SharedReplacement(Regex Pattern, string Replacement, ReplacementMode Mode)
{
public string Transform(string input) =>
Mode == ReplacementMode.Evaluator
? Pattern.Replace(input, _ => Replacement)
: Pattern.Replace(input, Replacement);
}
enum ReplacementMode
{
Simple,
Evaluator,
NonSimple,
}
sealed record Options(int Workers, int Regexes, int Seconds, bool FailFast, ReplacementMode Mode)
{
public static Options Parse(string[] args)
{
var workers = 8;
var regexes = 16;
var seconds = 600;
var failFast = false;
var mode = ReplacementMode.Simple;
for (var i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "--workers":
workers = int.Parse(args[++i]);
break;
case "--regexes":
regexes = int.Parse(args[++i]);
break;
case "--seconds":
seconds = int.Parse(args[++i]);
break;
case "--fail-fast":
failFast = true;
break;
case "--mode":
mode = args[++i] switch
{
"simple" => ReplacementMode.Simple,
"evaluator" => ReplacementMode.Evaluator,
"non-simple" => ReplacementMode.NonSimple,
var value => throw new ArgumentException($"Unknown mode '{value}'"),
};
break;
default:
throw new ArgumentException($"Unknown argument '{args[i]}'");
}
}
if (workers < 1)
{
throw new ArgumentOutOfRangeException(nameof(workers), workers, "Must be positive.");
}
if (regexes < 1)
{
throw new ArgumentOutOfRangeException(nameof(regexes), regexes, "Must be positive.");
}
if (seconds < 1)
{
throw new ArgumentOutOfRangeException(nameof(seconds), seconds, "Must be positive.");
}
return new Options(workers, regexes, seconds, failFast, mode);
}
}
sealed class ReproFailureException(int worker, long iterations, int regexIndex, Exception innerException)
: Exception($"Worker={worker}, Iterations={iterations}, RegexIndex={regexIndex}", innerException);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment