fix(scripting): #999 K-7 a script-thrown TimeoutException propagates as itself, not as a disposed-CTS fault or a guard timeout

This commit is contained in:
Joseph Doherty
2026-12-03 10:40:44 -05:00
parent 626d0b33c5
commit ef782c29ae
4 changed files with 62 additions and 3 deletions
@@ -301,11 +301,17 @@ public sealed class ScriptRunGuard
{
result = await runTask.WaitAsync(timeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
catch (TimeoutException tex) when (!ScriptTimeouts.IsScriptOwn(runTask, tex))
{
// WaitAsync's synthesized timeout only (#999 / review K-7): a TimeoutException the SCRIPT threw (incl.
// RegexMatchTimeoutException) faulted runTask with that very instance and falls through to the generic
// handler below — it is the script's failure, not a guard timeout, and must never count as a strike.
// The caller's cancel wins even when it lands a few µs after the timeout fired.
if (ct.IsCancellationRequested) throw new OperationCanceledException(ct);
runCts.Cancel();
// The run may have finished in the instant the timeout fired; its continuation then already disposed
// runCts. Cancelling a finished run is moot, so the dispose race must not replace the timeout.
try { runCts.Cancel(); }
catch (ObjectDisposedException) { }
if (NoteTimeout(key, state, timeout))
throw new ScriptQuarantinedException(key, state.QuarantineReason!);
throw new ScriptTimeoutException(timeout);
@@ -461,3 +467,16 @@ public sealed class ScriptQuarantinedException : Exception
Key = key;
}
}
/// <summary>Shared timeout classification for the script run wrappers (#999 / review K-7).</summary>
internal static class ScriptTimeouts
{
/// <summary>
/// True when <paramref name="caught"/> is the exception the script itself threw (it faulted
/// <paramref name="runTask"/>), false when it is <c>Task.WaitAsync</c>'s synthesized timeout. Both are
/// <see cref="TimeoutException"/>s (a script may throw one directly, or hit a <c>Regex</c> match timeout), so the
/// type alone cannot tell a guard timeout from the script's own failure.
/// </summary>
internal static bool IsScriptOwn(Task runTask, Exception caught)
=> runTask.IsFaulted && runTask.Exception!.InnerExceptions.Contains(caught);
}
@@ -82,8 +82,9 @@ public sealed class TimedScriptEvaluator<TContext, TResult>
{
return await runTask.WaitAsync(Timeout, ct).ConfigureAwait(false);
}
catch (TimeoutException)
catch (TimeoutException tex) when (!ScriptTimeouts.IsScriptOwn(runTask, tex))
{
// #999 / review K-7: a TimeoutException the script threw itself faulted runTask and propagates unchanged.
// WaitAsync's synthesized timeout — the inner task may still be running
// on its thread-pool thread (known leak documented in the class summary).
// Wrap so callers can distinguish from user-written timeout logic.
@@ -541,6 +541,33 @@ public sealed class ScriptRunGuardTests
guard.QuarantinedCount.ShouldBe(1);
}
/// <summary>
/// #999 / review K-7: a <see cref="TimeoutException"/> the SCRIPT threw (directly, or a
/// <c>RegexMatchTimeoutException</c>) is the script's own failure — it propagates unchanged, is not a guard
/// timeout, and never quarantines. Before the fix the guard's <c>catch (TimeoutException)</c> took it for
/// <c>WaitAsync</c>'s timeout and called <c>Cancel()</c> on the already-disposed run CTS, surfacing
/// <see cref="ObjectDisposedException"/>.
/// </summary>
[Theory]
[InlineData("throw new System.TimeoutException(\"mine\");", typeof(TimeoutException))]
[InlineData(
"return System.Text.RegularExpressions.Regex.IsMatch(new string('a', 40000) + \"!\", \"^(a+)+$\", System.Text.RegularExpressions.RegexOptions.None, System.TimeSpan.FromMilliseconds(20)) ? 1 : 0;",
typeof(System.Text.RegularExpressions.RegexMatchTimeoutException))]
public async Task A_script_thrown_TimeoutException_propagates_and_is_not_a_guard_timeout(string source, Type expected)
{
var guard = new ScriptRunGuard(new ScriptingOptions { QuarantineAfterConsecutiveTimeouts = 2 });
using var evaluator = Compile(source);
for (var i = 0; i < 4; i++)
{
var ex = await Should.ThrowAsync<Exception>(() =>
Run(guard, "own-timeout", source, evaluator, TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken));
ex.GetType().ShouldBe(expected, $"run {i}: {ex}");
}
guard.IsQuarantined("own-timeout", out _).ShouldBeFalse("a script's own exception is not a timeout strike");
guard.QuarantinedCount.ShouldBe(0);
}
/// <summary>Releases the held script (signal), waits for the orphan to drain, and re-arms the gate for the next attempt.</summary>
private static async Task ReleaseAndDrain(ScriptRunGuard guard, FakeScriptContext held)
{
@@ -47,6 +47,18 @@ public sealed class TimedScriptEvaluatorTests
result.ShouldBe(42.0);
}
/// <summary>#999 / review K-7: a TimeoutException the script threw itself is not the wrapper's timeout.</summary>
[Fact]
public async Task A_script_thrown_TimeoutException_is_not_reported_as_a_script_timeout()
{
var inner = ScriptEvaluator<FakeScriptContext, double>.Compile("""throw new System.TimeoutException("mine");""");
var timed = new TimedScriptEvaluator<FakeScriptContext, double>(inner, TimeSpan.FromSeconds(5));
var ex = await Should.ThrowAsync<Exception>(() => timed.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken));
ex.GetType().ShouldBe(typeof(TimeoutException));
ex.Message.ShouldBe("mine");
}
/// <summary>Verifies that scripts longer than timeout throw ScriptTimeoutException.</summary>
[Fact]
public async Task Script_longer_than_timeout_throws_ScriptTimeoutException()