Fixed the .NET server shutting down while the runtime still runs (#1237)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-26 12:01:08 +01:00
1 parent 9ebfce3855
commit 902e406e1d
22 files changed
+923 -115

No files matched your search

@@ -29,7 +29,7 @@ public static partial class JsonTestRoots
yield return Case(new(typeof(ValidateShortcutRequest), options));
yield return Case(new(typeof(SetInterfaceSizeRequest), options));
yield return Case(new(typeof(CreateMediaJobRequest), options));
yield return Case(new(typeof(LogEventRequest), options));
yield return Case(new(typeof(LogEventsRequest), options));
yield return Case(new(typeof(ValidateTokenizerRequest), options));
yield return Case(new(typeof(StoreTokenizerRequest), options));
yield return Case(new(typeof(DeleteTokenizerRequest), options));
+135
View File
@@ -0,0 +1,135 @@
using AIStudio.Tools.Services;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.Tools;
/// <summary>
/// Checks how the server decides that the runtime is gone after a call to it failed.
/// </summary>
/// <remarks>
/// The probes answer from a script here, without waiting between them. The rounds have three probes, so
/// two unanswered probes in a row are not enough for a shutdown.
/// </remarks>
[TestFixture]
public sealed class RuntimeOutageCheckTests
{
private static readonly RuntimeProbeSchedule THREE_PROBES = new(3, TimeSpan.Zero);
[Test]
public async Task AnAnswerEndsTheRoundWithoutShuttingDown()
{
var runtime = new ScriptedRuntime([false, true]);
var shutDowns = 0;
var check = new RuntimeOutageCheck(runtime.IsAliveAsync, () => Interlocked.Increment(ref shutDowns), THREE_PROBES, CancellationToken.None, NullLogger.Instance);
await check.Report("Tauri event stream error");
Assert.That(shutDowns, Is.Zero, "The server shut down although the runtime answered.");
Assert.That(runtime.Probes, Is.EqualTo(2), "The round went on after the runtime answered.");
}
[Test]
public async Task NoAnswerShutsTheServerDownOnce()
{
var runtime = new ScriptedRuntime([false, false, false, false, false, false]);
var shutDowns = 0;
var check = new RuntimeOutageCheck(runtime.IsAliveAsync, () => Interlocked.Increment(ref shutDowns), THREE_PROBES, CancellationToken.None, NullLogger.Instance);
await check.Report("Tauri event stream error");
await check.Report("EnterpriseEnvConfigs failed");
Assert.That(shutDowns, Is.EqualTo(1));
Assert.That(runtime.Probes, Is.EqualTo(3), "A report after the shutdown started another round.");
}
[Test]
public async Task ReportsDuringARoundJoinIt()
{
var answer = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var probes = 0;
var shutDowns = 0;
var check = new RuntimeOutageCheck(_ =>
{
Interlocked.Increment(ref probes);
return answer.Task;
}, () => Interlocked.Increment(ref shutDowns), THREE_PROBES, CancellationToken.None, NullLogger.Instance);
var rounds = Enumerable.Range(0, 20).Select(_ => check.Report("Tauri event stream error")).ToList();
answer.SetResult(true);
await Task.WhenAll(rounds);
Assert.That(probes, Is.EqualTo(1), "Every report started a round of its own.");
Assert.That(rounds.Distinct().Count(), Is.EqualTo(1), "The reports did not join the running round.");
Assert.That(shutDowns, Is.Zero);
}
/// <summary>
/// Each round needs two of its three probes. Counted over the lifetime of the server, as before,
/// these failed calls would have added up to a shutdown while the runtime kept running.
/// </summary>
[Test]
public async Task FailedCallsDoNotAddUpAcrossRounds()
{
var runtime = new ScriptedRuntime([false, true, false, true, false, true]);
var shutDowns = 0;
var check = new RuntimeOutageCheck(runtime.IsAliveAsync, () => Interlocked.Increment(ref shutDowns), THREE_PROBES, CancellationToken.None, NullLogger.Instance);
for (var round = 0; round < 3; round++)
await check.Report("Tauri event stream error");
Assert.That(shutDowns, Is.Zero);
Assert.That(runtime.Probes, Is.EqualTo(6));
}
[Test]
public async Task AProbeWhichFailsCountsAsNoAnswer()
{
var shutDowns = 0;
var check = new RuntimeOutageCheck(_ => throw new HttpRequestException("Connection refused"), () => Interlocked.Increment(ref shutDowns), THREE_PROBES, CancellationToken.None, NullLogger.Instance);
await check.Report("Tauri event stream error");
Assert.That(shutDowns, Is.EqualTo(1));
}
[Test]
public async Task StoppingTheServerEndsTheRoundQuietly()
{
using var stop = new CancellationTokenSource();
var shutDowns = 0;
var check = new RuntimeOutageCheck(_ =>
{
// The round awaits the check before the test leaves the scope of the source:
// ReSharper disable once AccessToDisposedClosure
stop.Cancel();
return Task.FromResult(false);
}, () => Interlocked.Increment(ref shutDowns), new RuntimeProbeSchedule(3, TimeSpan.FromHours(1)), stop.Token, NullLogger.Instance);
var round = check.Report("Tauri event stream error");
await round;
Assert.That(round.IsCompletedSuccessfully, Is.True, "The round failed instead of ending quietly.");
Assert.That(shutDowns, Is.Zero, "The server shut down although it was stopping anyway.");
}
/// <summary>
/// Answers the probes from a script, one answer per probe.
/// </summary>
/// <param name="answers">Whether the runtime answers the first, second, and later probes.</param>
private sealed class ScriptedRuntime(bool[] answers)
{
private int probes;
/// <summary>
/// How many probes asked the runtime so far.
/// </summary>
public int Probes => Volatile.Read(ref this.probes);
public Task<bool> IsAliveAsync(CancellationToken token)
{
var probe = Interlocked.Increment(ref this.probes);
return Task.FromResult(answers[probe - 1]);
}
}
}
+142
View File
@@ -0,0 +1,142 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http.Json;
using System.Text.RegularExpressions;
using AIStudio.Tools;
using AIStudio.Tools.Rust;
using AIStudio.Tools.Services;
namespace AIStudio.Tests.Tools;
/// <summary>
/// Checks how the log events of the .NET server reach the runtime.
/// </summary>
/// <remarks>
/// The runtime holds back its first answer here until the test lets it go, so the events pile up behind the
/// first batch, as they do during a burst.
/// </remarks>
[TestFixture]
public sealed partial class RustLogForwarderTests
{
[Test]
public async Task EventsArriveInBatchesAndInOrder()
{
const int EVENTS = 1_234;
var runtime = new LogRuntime();
var forwarder = CreateForwarder(runtime);
forwarder.Enqueue(CreateEvent(0));
await runtime.FirstRequestArrived;
for (var number = 1; number < EVENTS; number++)
forwarder.Enqueue(CreateEvent(number));
runtime.Answer();
await forwarder.StopAsync();
var messages = runtime.Batches.SelectMany(batch => batch.Events).Select(logEvent => logEvent.Message).ToList();
Assert.That(messages, Is.EqualTo(Enumerable.Range(0, EVENTS).Select(number => $"Event {number}")), "Events were lost or arrived out of order.");
Assert.That(runtime.Batches.Max(batch => batch.Events.Count), Is.LessThanOrEqualTo(RustLogForwarder.MAX_BATCH_SIZE));
Assert.That(runtime.Batches, Has.Count.EqualTo(1 + (EVENTS - 1 + RustLogForwarder.MAX_BATCH_SIZE - 1) / RustLogForwarder.MAX_BATCH_SIZE), "The waiting events were not sent in full batches.");
}
[Test]
public async Task EventsBeyondTheCapacityAreDroppedAndReported()
{
const int EXTRA_EVENTS = 42;
var runtime = new LogRuntime();
var forwarder = CreateForwarder(runtime);
forwarder.Enqueue(CreateEvent(0));
await runtime.FirstRequestArrived;
for (var number = 1; number <= RustLogForwarder.CAPACITY + EXTRA_EVENTS; number++)
forwarder.Enqueue(CreateEvent(number));
runtime.Answer();
await forwarder.StopAsync();
var events = runtime.Batches.SelectMany(batch => batch.Events).ToList();
var notices = events.Where(logEvent => logEvent.Category == typeof(RustLogForwarder).FullName).ToList();
Assert.That(notices, Has.Count.EqualTo(1), "The dropped events were not reported.");
Assert.That(notices[0].Level, Is.EqualTo("Warning"));
Assert.That(LostEvents(notices[0]), Is.EqualTo(EXTRA_EVENTS));
Assert.That(events, Has.Count.EqualTo(1 + RustLogForwarder.CAPACITY + 1), "More or fewer events than the queue holds arrived.");
}
[Test]
public async Task TheEventsOfAFailedBatchAreReportedAsLost()
{
var runtime = new LogRuntime(HttpStatusCode.InternalServerError);
var forwarder = CreateForwarder(runtime);
forwarder.Enqueue(CreateEvent(0));
await runtime.FirstRequestArrived;
forwarder.Enqueue(CreateEvent(1));
runtime.Answer();
await forwarder.StopAsync();
var events = runtime.Batches.Single().Events;
Assert.That(events[0].Message, Is.EqualTo("Event 1"));
Assert.That(LostEvents(events[1]), Is.EqualTo(1), "The event of the failed batch was not reported as lost.");
}
private static RustLogForwarder CreateForwarder(LogRuntime runtime) => new(new HttpClient(runtime) { BaseAddress = new Uri("https://127.0.0.1") }, TimeSpan.Zero);
private static LogEventRequest CreateEvent(int number) => new(TerminalLogger.FormatTransportTimestamp(DateTimeOffset.UtcNow), "Information", "Tests", $"Event {number}", null, null);
private static int LostEvents(LogEventRequest notice)
{
var match = LostEventsPattern().Match(notice.Message);
Assert.That(match.Success, Is.True, $"'{notice.Message}' is no notice about dropped events.");
return int.Parse(match.Groups[1].Value);
}
[GeneratedRegex(@"^Dropped (\d+) log events ")]
private static partial Regex LostEventsPattern();
/// <summary>
/// Plays the runtime: it holds back its first answer until the test lets it go, and records every batch
/// it accepted.
/// </summary>
/// <param name="firstAnswer">How the runtime answers the first batch; every later batch succeeds.</param>
private sealed class LogRuntime(HttpStatusCode firstAnswer = HttpStatusCode.OK) : HttpMessageHandler
{
private readonly TaskCompletionSource firstRequest = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource answer = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly ConcurrentQueue<LogEventsRequest> batches = new();
private int requests;
/// <summary>
/// Ends once the first batch arrived.
/// </summary>
public Task FirstRequestArrived => this.firstRequest.Task;
/// <summary>
/// The batches the runtime accepted, in order.
/// </summary>
public IReadOnlyList<LogEventsRequest> Batches => [..this.batches];
/// <summary>
/// Lets the runtime answer the first batch, and every later one at once.
/// </summary>
public void Answer() => this.answer.TrySetResult();
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.RequestUri?.AbsolutePath is not "/log/events")
return new HttpResponseMessage(HttpStatusCode.NotFound);
var batch = await request.Content!.ReadFromJsonAsync<LogEventsRequest>(RustService.JSON_OPTIONS, cancellationToken);
var isFirst = Interlocked.Increment(ref this.requests) == 1;
this.firstRequest.TrySetResult();
await this.answer.Task;
var status = isFirst ? firstAnswer : HttpStatusCode.OK;
if (status is HttpStatusCode.OK)
this.batches.Enqueue(batch);
return new HttpResponseMessage(status);
}
}
}
@@ -0,0 +1,76 @@
using AIStudio.Tools.Services.Indexing;
namespace AIStudio.Tests.Tools;
/// <summary>
/// Checks how the changes a watcher reports are counted instead of logged one by one.
/// </summary>
[TestFixture]
public sealed class WatcherChangeTallyTests
{
private const string DATA_SOURCE = "72022e84-a70c-45dd-b717-78377d07cc45";
private const string OTHER_DATA_SOURCE = "4f2a6c1e-8b3d-4e5f-9a7c-1d2e3f4a5b6c";
[Test]
public void OnlyTheFirstChangeOfABurstOpensAWindow()
{
var tally = new WatcherChangeTally();
Assert.That(tally.Count(DATA_SOURCE, "/repo/target/a.rlib", isRelevant: false), Is.True);
Assert.That(tally.Count(DATA_SOURCE, "/repo/target/b.rlib", isRelevant: false), Is.False);
Assert.That(tally.Count(DATA_SOURCE, "/repo/README.md", isRelevant: true), Is.False);
}
[Test]
public void ClosingTheWindowReturnsTheFurtherChanges()
{
var tally = new WatcherChangeTally();
tally.Count(DATA_SOURCE, "/repo/target/first.rlib", isRelevant: false);
for (var file = 0; file < 5; file++)
tally.Count(DATA_SOURCE, $"/repo/target/{file}.rlib", isRelevant: false);
tally.Count(DATA_SOURCE, "/repo/README.md", isRelevant: true);
tally.Count(DATA_SOURCE, "/repo/Überblick ä ß 日本.md", isRelevant: true);
var counts = tally.Close(DATA_SOURCE);
Assert.That(counts.Ignored, Is.EqualTo(5), "The change which opened the window was counted as well.");
Assert.That(counts.Relevant, Is.EqualTo(2));
Assert.That(counts.Total, Is.EqualTo(7));
Assert.That(counts.LastPath, Is.EqualTo("/repo/Überblick ä ß 日本.md"));
}
[Test]
public void AfterClosingTheNextChangeOpensANewWindow()
{
var tally = new WatcherChangeTally();
tally.Count(DATA_SOURCE, "/repo/a.md", isRelevant: true);
tally.Count(DATA_SOURCE, "/repo/b.md", isRelevant: true);
tally.Close(DATA_SOURCE);
Assert.That(tally.Count(DATA_SOURCE, "/repo/c.md", isRelevant: true), Is.True);
Assert.That(tally.Close(DATA_SOURCE), Is.EqualTo(WatcherChangeCounts.NONE), "The counts of the closed window were carried over.");
}
[Test]
public void EveryDataSourceHasAWindowOfItsOwn()
{
var tally = new WatcherChangeTally();
tally.Count(DATA_SOURCE, "/repo/a.md", isRelevant: true);
Assert.That(tally.Count(OTHER_DATA_SOURCE, "/mail/b.md", isRelevant: true), Is.True, "A change of one data source joined the window of another.");
tally.Count(OTHER_DATA_SOURCE, "/mail/c.md", isRelevant: false);
Assert.That(tally.Close(DATA_SOURCE).Total, Is.Zero);
Assert.That(tally.Close(OTHER_DATA_SOURCE).Total, Is.EqualTo(1));
}
[Test]
public void ClosingAWindowWhichIsNotOpenCountsNothing()
{
var tally = new WatcherChangeTally();
Assert.That(tally.Close(DATA_SOURCE), Is.EqualTo(WatcherChangeCounts.NONE));
}
}