The regex your agent wrote hangs on one bad string: a timeout policy, a pumped-input test and a build gate for C#
Agents write validators like ^(\w+\s?)*$ that pass every example and then pin a CPU core on 40 characters of input. Here's how to make that fail in CI, fix it without changing what the pattern accepts, and stop the next one at build time. About 20 minutes.

A pull request from an agent adds two validators to a signup form: one for a slug, one for a display name. The patterns look tidy, the agent wrote five example tests, all green. The reviewer approves. A week later a bot posts a 40-character display name ending in an exclamation mark, and one request thread spins at 100% CPU until the process is restarted.
Nothing in the diff was wrong on the inputs anyone tried. The pattern was ^(\w+\s?)*$, which is a quantifier inside a quantifier over characters that can match in more than one way. On input that almost matches, the engine tries every way of splitting the word into groups before it gives up, and the number of ways doubles with each extra character.
This playbook builds three things around that failure: a timeout policy the whole codebase shares, a test that feeds every validator a “pumped” string and fails on a hang, and a build gate that refuses regexes with no timeout. It also covers how to fix a pattern without silently changing what it accepts. The prompts don’t depend on any one agent. Anything that can edit files and run dotnet test can follow them.
The first draft, as an agent writes it
Here’s the code under test. Two validators, each a static Regex, both patterns of the kind an agent produces when asked for “a slug validator” and “a display name that allows single spaces”:
using System.Text.RegularExpressions;
namespace Rx.Lib;
public static class Validators
{
private static readonly Regex SlugRx =
new(@"^([a-zA-Z0-9]+[-_.]?)+$", RegexOptions.None, RegexPolicy.Timeout);
private static readonly Regex NameRx =
new(@"^(\w+\s?)*$", RegexOptions.None, RegexPolicy.Timeout);
public static bool IsValidSlug(string s) => SlugRx.IsMatch(s);
public static bool IsValidDisplayName(string s) => NameRx.IsMatch(s);
}
Both pass the obvious cases, which is the whole problem. my-post and v1.2.3 match the slug pattern, Ada Lovelace matches the name pattern, and a b! matches neither. The slug pattern allows an optional separator after each run of letters and digits, so trailing- is valid and -leading isn’t. That detail matters later, because a fix has to keep it.
Step 1: one timeout policy, in one place
.NET regexes have no time limit by default. The documentation says the default is Regex.InfiniteMatchTimeout, and it describes an app-wide default you can set through the REGEX_DEFAULT_MATCH_TIMEOUT property. Don’t rely on that one in a test project. Set from a module initialiser in an xUnit test assembly under dotnet test, the value didn’t take: new Regex("a").MatchTimeout still reported an infinite timeout, and the pumped-input tests below hung instead of failing.
An explicit timeout on every regex has none of that fragility, and it’s what you want in production anyway. Put the number in one file:
namespace Rx.Lib;
public static class RegexPolicy
{
public const int TimeoutMs = 250;
public static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(TimeoutMs);
}
It’s a const so the same value can feed the [GeneratedRegex] attribute later, which needs a compile-time constant. 250ms is a choice, not a recommendation: pick the longest a single match can take before the request is already failing its own budget. A validator on a form field has no business taking even 20ms.
A timeout doesn’t fix a bad pattern. It turns an unbounded hang into a RegexMatchTimeoutException after a known delay, which is the difference between one slow request and a dead thread pool. Microsoft’s regex guidance is explicit that timeouts and NonBacktracking protect against accidental performance problems in developer-written patterns and aren’t a boundary against malicious patterns, so patterns built from user input are a separate problem that needs Regex.Escape or no regex at all.
Step 2: the pumped-input test, written before the fix
The test needs an input that makes a vulnerable pattern work as hard as possible: a long run of characters the pattern is happy to consume, followed by one character that makes the final match fail. Repeating the valid character is the “pump”, and the trailing character is the trigger.
using Rx.Lib;
namespace Rx.Tests;
public class ValidatorTests
{
// Valid-looking prefix, then one character that forces the match to fail at the very end.
public static IEnumerable<object[]> Pumped() =>
from n in new[] { 40, 5_000 }
select new object[] { new string('a', n) + "!" };
[Theory, MemberData(nameof(Pumped))]
public void Slug_rejects_pumped_input_within_budget(string input) =>
Assert.False(Validators.IsValidSlug(input));
[Theory, MemberData(nameof(Pumped))]
public void DisplayName_rejects_pumped_input_within_budget(string input) =>
Assert.False(Validators.IsValidDisplayName(input));
[Theory]
[InlineData("my-post", true)]
[InlineData("v1.2.3", true)]
[InlineData("trailing-", true)]
[InlineData("-leading", false)]
[InlineData("a b", false)]
public void Slug_behaviour(string input, bool expected) =>
Assert.Equal(expected, Validators.IsValidSlug(input));
}
There’s no stopwatch and no threshold to tune. The pass condition is “returns false”, and the only way to miss it is for the policy timeout to fire and throw. Two sizes are enough: 40 is where exponential patterns are already hopeless, and 5,000 catches the quadratic ones that look fine at 40.
Create the project and run it:
dotnet new sln -n Rx
dotnet new classlib -n Rx.Lib -f net10.0
dotnet new xunit -n Rx.Tests -f net10.0
dotnet add Rx.Tests reference Rx.Lib
dotnet test Rx.Tests
Run against the draft validators, it prints (trimmed):
Failed Rx.Tests.ValidatorTests.Slug_rejects_pumped_input_within_budget(input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!") [253 ms]
Error Message:
System.Text.RegularExpressions.RegexMatchTimeoutException : The Regex engine has timed out while trying to match a pattern to an input string. [...]
Failed Rx.Tests.ValidatorTests.DisplayName_rejects_pumped_input_within_budget(input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!") [251 ms]
[...]
Failed! - Failed: 4, Passed: 5, Skipped: 0, Total: 9, Duration: 1 s
Four failures, each around 250ms, and the five behaviour tests still pass. That’s the red you want: the example tests an agent would write were green, and the pumped ones aren’t.
Step 3: fix it without changing what it accepts
The agent’s fix prompt matters here. “Fix the catastrophic backtracking” invites a rewrite that is safe and quietly different, such as rejecting the trailing separator the old slug pattern allowed. Ask for equivalence explicitly:
The tests in ValidatorTests fail with RegexMatchTimeoutException on pumped input.
Rewrite SlugRx and NameRx so no quantified group can match the same characters in
more than one way. The set of accepted strings must not change. Use
[GeneratedRegex] with RegexPolicy.TimeoutMs. Do not edit the existing tests.
The usual repair is to make each repetition start with something the previous one can’t end with. For the slug, a separator is now required between runs, and an optional trailing one is added explicitly. For the name, the whitespace moves to the front of each later word:
using System.Text.RegularExpressions;
namespace Rx.Lib;
public static partial class Validators
{
[GeneratedRegex(@"^[a-zA-Z0-9]+(?:[-_.][a-zA-Z0-9]+)*[-_.]?$",
RegexOptions.None, RegexPolicy.TimeoutMs)]
private static partial Regex SlugRx();
[GeneratedRegex(@"^(?:\w+(?:\s\w+)*\s?)?$", RegexOptions.None, RegexPolicy.TimeoutMs)]
private static partial Regex NameRx();
public static bool IsValidSlug(string s) => SlugRx().IsMatch(s);
public static bool IsValidDisplayName(string s) => NameRx().IsMatch(s);
}
[GeneratedRegex] also moves the pattern’s compilation to build time, and the generator caches a singleton instance, so the static field disappears. The third argument is matchTimeoutMilliseconds, which is why the policy exposed a constant.
Run the tests again and all nine pass. But “the tests pass” is the claim that got the first draft approved. The behaviour tests cover five strings. Whether the rewrite accepts exactly the same language as the original is a question for a differential test.
Step 4: prove equivalence with the original on the linear engine
RegexOptions.NonBacktracking guarantees linear-time matching in the length of the input, and it’s available from .NET 7. It can’t be used for everything (the documentation says to avoid it when a pattern needs lookarounds, backreferences or atomic groups), but neither original pattern needs those. That makes the old patterns safe to run as an oracle: compile them with NonBacktracking, throw tens of thousands of short random strings at both versions, and compare.
using System.Text.RegularExpressions;
using Rx.Lib;
namespace Rx.Tests;
public class EquivalenceTests
{
// The agent's original patterns, run on the linear-time engine so they can't hang.
private static readonly Regex OldSlug =
new(@"^([a-zA-Z0-9]+[-_.]?)+$", RegexOptions.NonBacktracking, RegexPolicy.Timeout);
private static readonly Regex OldName =
new(@"^(\w+\s?)*$", RegexOptions.NonBacktracking, RegexPolicy.Timeout);
private static IEnumerable<string> Samples(string alphabet, int count)
{
var rng = new Random(20261118);
for (var i = 0; i < count; i++)
yield return string.Concat(Enumerable.Range(0, rng.Next(0, 14))
.Select(_ => alphabet[rng.Next(alphabet.Length)]));
}
[Fact]
public void Slug_fix_accepts_exactly_what_the_original_accepted()
{
foreach (var s in Samples("ab1-_. !", 50_000))
Assert.True(OldSlug.IsMatch(s) == Validators.IsValidSlug(s), $"differs on \"{s}\"");
}
[Fact]
public void DisplayName_fix_accepts_exactly_what_the_original_accepted()
{
foreach (var s in Samples("ab_ \t!", 50_000))
Assert.True(OldName.IsMatch(s) == Validators.IsValidDisplayName(s), $"differs on \"{s}\"");
}
}
The alphabets are small on purpose. Short strings over six or eight symbols hit the interesting cases (empty input, leading and trailing separators, double spaces, a tab) thousands of times each, and the fixed seed makes a failure reproducible. Run it:
Passed! - Failed: 0, Passed: 11, Skipped: 0, Total: 11, Duration: 193 ms
A differential test that has never failed hasn’t shown it can. Drop the trailing [-_.]? from the slug fix, which is exactly the “tidy” mistake an agent makes, and run it again:
differs on "a-"
Failed! - Failed: 2, Passed: 9, Skipped: 0, Total: 11
Both the equivalence test and the trailing- behaviour test go red, and the counterexample is a two-character string. Restore the ? and it’s green again.
The other fix on offer is to keep the original pattern and add RegexOptions.NonBacktracking. It’s a one-word change and it removes the blow-up. It also gives up lookarounds and backreferences if the pattern ever needs them later, so the rewrite is the better default when the pattern is this simple. Use NonBacktracking when the pattern is long, inherited or somebody else’s.
Step 5: stop the next one at build time
Tests only cover the validators somebody wrote tests for. The next regex arrives in a file nobody thought to cover, with no timeout, in a static call like Regex.IsMatch(input, pattern). A banned-API analyser catches that at compile time, with no tests involved.
Add the package to the project that contains application code:
dotnet add Rx.Lib package Microsoft.CodeAnalysis.BannedApiAnalyzers
Then add this to Rx.Lib.csproj, next to the package reference:
<ItemGroup>
<AdditionalFiles Include="..\BannedSymbols.txt" />
</ItemGroup>
And create BannedSymbols.txt beside the solution. Each line is a documentation-comment ID, a semicolon, and the message the developer sees:
M:System.Text.RegularExpressions.Regex.#ctor(System.String);Pass a timeout: new Regex(pattern, options, RegexPolicy.Timeout)
M:System.Text.RegularExpressions.Regex.#ctor(System.String,System.Text.RegularExpressions.RegexOptions);Pass a timeout: new Regex(pattern, options, RegexPolicy.Timeout)
M:System.Text.RegularExpressions.Regex.IsMatch(System.String,System.String);Use a Regex instance with a timeout
M:System.Text.RegularExpressions.Regex.IsMatch(System.String,System.String,System.Text.RegularExpressions.RegexOptions);Use a Regex instance with a timeout
M:System.Text.RegularExpressions.Regex.Match(System.String,System.String);Use a Regex instance with a timeout
M:System.Text.RegularExpressions.Regex.Replace(System.String,System.String,System.String);Use a Regex instance with a timeout
M:System.Text.RegularExpressions.GeneratedRegexAttribute.#ctor(System.String);Use GeneratedRegex(pattern, options, RegexPolicy.TimeoutMs)
M:System.Text.RegularExpressions.GeneratedRegexAttribute.#ctor(System.String,System.Text.RegularExpressions.RegexOptions);Use GeneratedRegex(pattern, options, RegexPolicy.TimeoutMs)
That list isn’t exhaustive. The Regex class has more static overloads (IsMatch, Match, Matches, Replace, Split, EnumerateMatches), and the file should grow until every overload without a timeout is covered. The shape stays the same.
To see it work, drop in a file with a plain static call:
using System.Text.RegularExpressions;
namespace Rx.Lib;
public static class Sneaky
{
public static bool LooksLikeSku(string s) => Regex.IsMatch(s, @"^(\d+-?)+$");
}
The build prints:
Sneaky.cs(5,50): warning RS0030: The symbol 'Regex.IsMatch(string, string)' is banned in this project: Use a Regex instance with a timeout
A warning won’t stop an agent that doesn’t read warnings. Make the build fail instead, in CI and in whatever command the agent runs to check its own work:
dotnet build -warnaserror
Run that with Sneaky.cs in place and the output ends with error RS0030 and Build FAILED. Delete the file and it builds clean. If you’d rather not fail the build on every warning, set <WarningsAsErrors>RS0030</WarningsAsErrors> in the project file so only this rule is promoted.
The analyser can’t tell a safe pattern from a vulnerable one. What it enforces is the precondition for the policy: every regex has a timeout, so a vulnerable pattern becomes an exception with a stack trace instead of a stuck thread. Finding the vulnerable pattern is the job of the pumped-input test.
Make the agent do the whole loop
Give the agent the policy as a standing instruction, in whatever file your tool reads (AGENTS.md, CLAUDE.md, a Cursor rule, a pasted preamble), and make the check a command:
Regexes in this repo:
- Every regex has a timeout from RegexPolicy. Prefer [GeneratedRegex(..., RegexPolicy.TimeoutMs)].
- Never nest a quantified group whose repetitions can match the same characters.
- Every validator that uses a regex gets a pumped-input test: a long run of valid
characters plus one invalid character, in ValidatorTests.
- Run `dotnet build -warnaserror && dotnet test` before saying you're done.
Nothing in it is specific to one agent. The technique is a policy file, a test and a build flag, and the check that proves it worked is a command that exits non-zero.
Make it yours
For patterns that can’t be rewritten (a vendored or inherited regex with backreferences), skip the equivalence test and keep the timeout and the pumped-input test. They’re the cheap half of the loop and they work on any pattern.
For regexes created inside a framework, such as a validation attribute on a model property, a banned-API rule can’t see the timeout. Put the pumped-input test on the model’s validation instead, and check in the framework’s documentation how to set a match timeout there.
For a TypeScript service the test carries over unchanged to Vitest, with the per-test timeout as the failure signal. JavaScript’s RegExp has no match timeout, so the policy part has to come from a lint rule or from avoiding regexes on untrusted input. Check any such rule against your own patterns before trusting it.
What goes wrong
Pumped input only finds what you pump. The pump above repeats one valid character and ends in a failure, which triggers the common nested-quantifier shape. Patterns with alternation overlap, such as (a|aa)+, need a different pump, and the honest version of the test uses several shapes. Ask the agent to add one pump per distinct token class in the pattern, then check its choices; an agent will happily write pumps that the pattern rejects at the first character, which proves nothing.
The equivalence test is sampled, not proved. Fifty thousand strings from a small alphabet make a counterexample very likely if one exists in short strings, but they don’t cover long inputs or characters outside the alphabet. Add the characters that matter for your pattern (Unicode letters for \w, non-breaking spaces for \s) rather than hoping.
A 250ms timeout fires on slow CI runners for legitimate heavy matches too. If a valid input times out in tests, the right response is usually that the pattern or the input size is wrong, not that the number is. Raise it only after finding out which.
And skip all of this for patterns that are never fed outside input. A regex over a constant string in a build script doesn’t need a pumped-input test. The tests are for anything reachable from a request, a file upload or a log line.
First 20 minutes
Search the repo for Regex and [RegularExpression and list every pattern. Add RegexPolicy and the banned-symbols file, then run dotnet build -warnaserror and read what it flags. For each regex reachable from user input, ask the agent for a pumped-input test first, watch it fail or pass, and only then let it touch the pattern. For the same idea applied to loops instead of patterns, see the scaling test
.