diff --git a/app/AGENTS.md b/app/AGENTS.md index 6be3b61fb..16729ca75 100644 --- a/app/AGENTS.md +++ b/app/AGENTS.md @@ -30,6 +30,7 @@ Key structure: - **Naming conventions** - Constants, enum members, and `static readonly` fields use `UPPER_SNAKE_CASE` such as `MY_CONSTANT`. - **Extension members** - Declare extension methods in an `extension` block of their static class, one block per receiver, never with a `this` parameter: MWAIS0016 refuses the classic form. The `` of the receiver, and of a generic block its ``, belongs on the block, not on its members. A member which only looks something up about its receiver, such as a name, an icon, a flag, a prompt, or an address, is an extension property, named without `Get` or `To`: `format.FileExtension`, `host.IsChatSupported`. It stays a method when it takes parameters, builds something new such as a list or a model profile, parses, scans a collection, or converts into another type, as `GetModelProfile`, `CompactCount`, and `ToSources` do. Check first that the receiver has no instance member of the same name, which would hide the extension. A helper which belongs to the type rather than to one of its values is a static member of the block and is reached through the type: `RID.Current`, `FileExportFormat.TryFromCodeFenceLanguage`. Never name one `Parse` or `TryParse`: C# finds those of `Enum` first. - **Line breaks** - Every text AI Studio builds ends its lines with LF, on every system: use `AppendLineLF` of `SharedTools.Text` instead of `StringBuilder.AppendLine`, and `'\n'` instead of `Environment.NewLine`. Both of them write CR LF on Windows, where no pipeline runs the tests; MWAIS0018 refuses them, and its code fix offers the replacement. Where a format needs CR LF, write it on purpose, as `CsvWriter.ROW_END` does. A raw string literal and a file which comes with the app keep the line endings of the checkout, CR LF on Windows with `core.autocrlf`: a test which compares such a text with what the app built normalizes it first, e.g. with `ReplaceLineEndings("\n")`. +- **Bursts in the log** - Never log one line per item of something which arrives in bursts, such as the changes a file system watcher reports, the files of a run, or the mails of a folder: a build or a sync tool changes thousands of files within seconds. Log the first item and then a summary with counts, as `FileSourceIndexer` does with `WatcherChangeTally`, or one summary per run with a few examples. Every log line of the .NET server travels to the runtime, and `RustLogForwarder` drops lines once its queue is full. - **Message Bus** - Singleton event bus for cross-component communication inside the .NET app - **Prompt injection reports** - The user hears once per action about what the filter removed, as soon as that action ends. Content which belongs to an action carries its scope from `PromptInjectionGuardService.BeginAction` down to where it is read or filtered; whatever is filtered without a scope is reported right away. Pass the scope as a parameter, never through a field or an `AsyncLocal`: the service serves the whole app, and the message bus delivers to other receivers in the execution context of whoever sends. - **Paths in stored data** - A stored path to a file which AI Studio keeps below the data directory, such as a transcript or a tokenizer copy, is relative to that directory, so that a backup or a copy of the data directory works on another computer, under another user name, or on another OS. Mark such a property with `[JsonConverter(typeof(DataDirectoryRelativePathConverter))]`, for a positional record parameter with `[property: ...]`; in memory, the path stays absolute. Better still, derive the path from IDs and store none, as `VisualBriefingStore` does. Paths to files of the user stay absolute. Chats stored before v26.10.1 are migrated by a compatibility shim, see `documentation/compatibility-shims/2026-10-relative-data-paths.md`. diff --git a/app/MindWork AI Studio/Tools/Rust/LogEventsRequest.cs b/app/MindWork AI Studio/Tools/Rust/LogEventsRequest.cs new file mode 100644 index 000000000..1990e1119 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Rust/LogEventsRequest.cs @@ -0,0 +1,7 @@ +namespace AIStudio.Tools.Rust; + +/// +/// A batch of log events which the Rust runtime writes to the log file. +/// +/// The events, in the order they happened. +public readonly record struct LogEventsRequest(IReadOnlyList Events); \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Services/Indexing/FileSourceIndexer.Watchers.cs b/app/MindWork AI Studio/Tools/Services/Indexing/FileSourceIndexer.Watchers.cs index 774ed9fa9..6ba524c93 100644 --- a/app/MindWork AI Studio/Tools/Services/Indexing/FileSourceIndexer.Watchers.cs +++ b/app/MindWork AI Studio/Tools/Services/Indexing/FileSourceIndexer.Watchers.cs @@ -10,6 +10,12 @@ internal sealed partial class FileSourceIndexer { private const int WATCHER_DEBOUNCE_SECONDS = 2; + /// + /// How long the changes of a data source are counted after the one which was logged, before their summary is logged. + /// + private const int WATCHER_SUMMARY_SECONDS = 30; + + private readonly WatcherChangeTally watcherChangeTally = new(); private readonly ConcurrentDictionary watchers = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary watcherDebounceTokens = new(StringComparer.OrdinalIgnoreCase); private readonly Lock watcherDebounceLock = new(); @@ -130,23 +136,52 @@ internal sealed partial class FileSourceIndexer private void OnWatchedDataSourceChanged(string dataSourceId, DataSourceWatcherConfiguration configuration, FileSystemEventArgs args) { - if (!IsRelevantWatcherEvent(configuration, args)) + var isRelevant = IsRelevantWatcherEvent(configuration, args); + + // + // Only the first change of a burst gets a line of its own, and the others are counted, + // cf. WatcherChangeTally: + // + if (this.watcherChangeTally.Count(dataSourceId, args.FullPath, isRelevant)) { - logger.LogDebug( - "Ignoring file system change for data source '{DataSourceId}' at '{Path}' (event={ChangeType}) because the path is not part of the RAG index.", - dataSourceId, - args.FullPath, - args.ChangeType); - return; + if (isRelevant) + logger.LogDebug( + "Detected relevant file system change for data source '{DataSourceId}' at '{Path}' (event={ChangeType}). Scheduling a debounced embedding run. Further changes within {Seconds} s are summarized.", + dataSourceId, + args.FullPath, + args.ChangeType, + WATCHER_SUMMARY_SECONDS); + else + logger.LogDebug( + "Ignoring file system change for data source '{DataSourceId}' at '{Path}' (event={ChangeType}) because the path is not part of the RAG index. Further changes within {Seconds} s are summarized.", + dataSourceId, + args.FullPath, + args.ChangeType, + WATCHER_SUMMARY_SECONDS); + + this.ScheduleWatcherSummary(dataSourceId); } - logger.LogDebug( - "Detected relevant file system change for data source '{DataSourceId}' at '{Path}' (event={ChangeType}). Scheduling a debounced embedding run.", - dataSourceId, - args.FullPath, - args.ChangeType); + if (isRelevant) + this.ScheduleWatchedDataSourceRefresh(dataSourceId); + } - this.ScheduleWatchedDataSourceRefresh(dataSourceId); + private void ScheduleWatcherSummary(string dataSourceId) + { + Task.Run(async () => + { + await Task.Delay(TimeSpan.FromSeconds(WATCHER_SUMMARY_SECONDS)); + var counts = this.watcherChangeTally.Close(dataSourceId); + if (counts.Total > 0) + logger.LogDebug( + "The watcher of data source '{DataSourceId}' reported {FurtherChanges} further file system change(s) within {Seconds} s: {Relevant} concern the RAG index, {Ignored} do not. The last one was at '{Path}'.", + dataSourceId, + counts.Total, + WATCHER_SUMMARY_SECONDS, + counts.Relevant, + counts.Ignored, + counts.LastPath); + }).Observe($"{nameof(FileSourceIndexer)}: summarizing the file system changes of a data source"); } private void ScheduleWatchedDataSourceRefresh(string dataSourceId) diff --git a/app/MindWork AI Studio/Tools/Services/Indexing/WatcherChangeCounts.cs b/app/MindWork AI Studio/Tools/Services/Indexing/WatcherChangeCounts.cs new file mode 100644 index 000000000..5107c0d97 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Services/Indexing/WatcherChangeCounts.cs @@ -0,0 +1,30 @@ +namespace AIStudio.Tools.Services.Indexing; + +/// +/// The file system changes of one data source which WatcherChangeTally counted instead of logging each. +/// +/// How many changes concerned no file of the RAG index. +/// How many changes concerned the RAG index. +/// The path of the last change, or an empty string without any. +internal readonly record struct WatcherChangeCounts(int Ignored, int Relevant, string LastPath) +{ + /// + /// No change counted. + /// + public static readonly WatcherChangeCounts NONE = new(0, 0, string.Empty); + + /// + /// How many changes were counted. + /// + public int Total => this.Ignored + this.Relevant; + + /// + /// Counts one more change. + /// + /// The path of the change. + /// Whether the change concerns the RAG index. + /// The counts including this change. + public WatcherChangeCounts Add(string path, bool isRelevant) => isRelevant + ? this with { Relevant = this.Relevant + 1, LastPath = path } + : this with { Ignored = this.Ignored + 1, LastPath = path }; +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Services/Indexing/WatcherChangeTally.cs b/app/MindWork AI Studio/Tools/Services/Indexing/WatcherChangeTally.cs new file mode 100644 index 000000000..ba89586fc --- /dev/null +++ b/app/MindWork AI Studio/Tools/Services/Indexing/WatcherChangeTally.cs @@ -0,0 +1,49 @@ +namespace AIStudio.Tools.Services.Indexing; + +/// +/// Counts the file system changes which the watchers report, so the log gets a summary instead of one line per change. +/// +/// +/// A build, a checkout, or a sync tool changes thousands of files within seconds. With one log line each, such a +/// burst buried the log, and the log events piled up on their way to the runtime until it closed the connection +/// of the .NET server. Therefore, the first change of a data source opens a window and is logged as it comes; +/// every further change is only counted until the window closes, and its summary takes one line. +/// +internal sealed class WatcherChangeTally +{ + private readonly Lock tallyLock = new(); + private readonly Dictionary openWindows = new(StringComparer.OrdinalIgnoreCase); + + /// + /// Counts a change of a data source. + /// + /// The id of the data source. + /// The path of the change. + /// Whether the change concerns the RAG index. + /// True when the change opened a window: the caller logs it as it comes and closes the window later. + public bool Count(string dataSourceId, string path, bool isRelevant) + { + lock (this.tallyLock) + { + if (this.openWindows.TryGetValue(dataSourceId, out var counts)) + { + this.openWindows[dataSourceId] = counts.Add(path, isRelevant); + return false; + } + + this.openWindows[dataSourceId] = WatcherChangeCounts.NONE; + return true; + } + } + + /// + /// Closes the window of a data source, so its next change opens a new one. + /// + /// The id of the data source. + /// The changes counted after the one which opened the window. + public WatcherChangeCounts Close(string dataSourceId) + { + lock (this.tallyLock) + return this.openWindows.Remove(dataSourceId, out var counts) ? counts : WatcherChangeCounts.NONE; + } +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Services/RuntimeOutageCheck.cs b/app/MindWork AI Studio/Tools/Services/RuntimeOutageCheck.cs new file mode 100644 index 000000000..ac3c9b5d1 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Services/RuntimeOutageCheck.cs @@ -0,0 +1,108 @@ +namespace AIStudio.Tools.Services; + +/// +/// Decides whether the runtime is gone after a call to it failed. +/// +/// +/// A failed call alone proves little. All calls share one HTTP/2 connection, which a flood of requests can +/// congest and which the runtime may close, while the runtime itself keeps running. Therefore, a report +/// starts a round of probes, which ask the runtime over a connection of their own. The first answer ends the +/// round, and the next report starts afresh: failed calls never add up over the lifetime of the server. Only +/// when no probe of a round gets an answer does the runtime count as gone, and the server shuts down. +/// +/// Asks the runtime whether it is alive; true when it answered. +/// Shuts the server down once the runtime counts as gone. +/// How many probes a round makes and how long it waits between them. +/// Ends a running round when the server stops. +/// The logger. +public sealed class RuntimeOutageCheck(Func> isRuntimeAlive, Action shutDown, RuntimeProbeSchedule schedule, CancellationToken stopToken, ILogger logger) +{ + private readonly Lock roundLock = new(); + + private Task runningRound = Task.CompletedTask; + private int reportsInRound; + private int shutDownStarted; + + /// + /// Reports that a call to the runtime failed, and starts a round of probes unless one is running. + /// + /// Why the call failed, for the log. + /// The round this report joined. It ends once the runtime answered or counts as gone, and it never fails. + public Task Report(string reason) + { + if (Volatile.Read(ref this.shutDownStarted) != 0) + return Task.CompletedTask; + + lock (this.roundLock) + { + if (!this.runningRound.IsCompleted) + { + this.reportsInRound++; + logger.LogDebug("Another call to the runtime failed while a round of probes is running. Reason = '{Reason}'.", reason); + return this.runningRound; + } + + this.reportsInRound = 1; + this.runningRound = Task.Run(() => this.RunRoundAsync(reason)); + this.runningRound.Observe($"{nameof(RuntimeOutageCheck)}: checking whether the runtime is alive"); + return this.runningRound; + } + } + + private async Task RunRoundAsync(string reason) + { + logger.LogWarning("A call to the runtime failed. Reason = '{Reason}'. Checking over a connection of its own whether the runtime is still alive.", reason); + try + { + for (var probe = 1; probe <= schedule.Probes; probe++) + { + if (probe > 1) + await Task.Delay(schedule.Interval, stopToken); + + if (await this.ProbeAsync()) + { + logger.LogInformation("The runtime answered probe {Probe} of {Probes} and is still alive. The {Reports} failed call(s) of this round were transient.", probe, schedule.Probes, this.ReportsInRound); + return; + } + + logger.LogWarning("The runtime did not answer probe {Probe} of {Probes}.", probe, schedule.Probes); + } + } + catch (Exception) when (stopToken.IsCancellationRequested) + { + // The server stops anyway, so the outcome of this round no longer matters. + return; + } + + if (Interlocked.Exchange(ref this.shutDownStarted, 1) != 0) + return; + + logger.LogError("The runtime did not answer any of {Probes} probes, {Interval} apart, and counts as gone. Failed calls in this round: {Reports}; the first one failed with reason '{Reason}'. Shutting down the server.", schedule.Probes, schedule.Interval, this.ReportsInRound, reason); + shutDown(); + } + + /// + /// Asks the runtime once whether it is alive. A probe which fails in any way counts as no answer. + /// + private async Task ProbeAsync() + { + try + { + return await isRuntimeAlive(stopToken); + } + catch (Exception e) when (!stopToken.IsCancellationRequested) + { + logger.LogWarning(e, "The probe whether the runtime is alive failed."); + return false; + } + } + + private int ReportsInRound + { + get + { + lock (this.roundLock) + return this.reportsInRound; + } + } +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Services/RuntimeProbeSchedule.cs b/app/MindWork AI Studio/Tools/Services/RuntimeProbeSchedule.cs new file mode 100644 index 000000000..20200bd1e --- /dev/null +++ b/app/MindWork AI Studio/Tools/Services/RuntimeProbeSchedule.cs @@ -0,0 +1,14 @@ +namespace AIStudio.Tools.Services; + +/// +/// How a round of RuntimeOutageCheck probes the runtime. +/// +/// How many probes a round makes at most, before the runtime counts as gone. +/// How long the round waits between two probes. +public readonly record struct RuntimeProbeSchedule(int Probes, TimeSpan Interval) +{ + /// + /// Seven probes, ten seconds apart: the runtime counts as gone once it did not answer for a minute. + /// + public static readonly RuntimeProbeSchedule DEFAULT = new(7, TimeSpan.FromSeconds(10)); +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Services/RustAvailabilityMonitorService.cs b/app/MindWork AI Studio/Tools/Services/RustAvailabilityMonitorService.cs index 14d77d041..17bc59f6e 100644 --- a/app/MindWork AI Studio/Tools/Services/RustAvailabilityMonitorService.cs +++ b/app/MindWork AI Studio/Tools/Services/RustAvailabilityMonitorService.cs @@ -2,31 +2,24 @@ using Microsoft.AspNetCore.Components; namespace AIStudio.Tools.Services; +/// +/// Shuts the server down once the runtime is gone. +/// +/// +/// Services report a failed call to the runtime with the event RUST_SERVICE_UNAVAILABLE. Such a call can fail +/// while the runtime keeps running, so RuntimeOutageCheck probes the runtime before the server shuts down. +/// public sealed class RustAvailabilityMonitorService : BackgroundService, IMessageBusReceiver { - private const int UNAVAILABLE_EVENT_THRESHOLD = 2; - private readonly ILogger logger; private readonly MessageBus messageBus; - private readonly RustService rustService; - private readonly IHostApplicationLifetime appLifetime; + private readonly RuntimeOutageCheck outageCheck; - private int rustUnavailableCount; - private int availabilityCheckTriggered; - - // To prevent multiple shutdown triggers. We use int instead of bool for Interlocked operations. - private int shutdownTriggered; - - public RustAvailabilityMonitorService( - ILogger logger, - MessageBus messageBus, - RustService rustService, - IHostApplicationLifetime appLifetime) + public RustAvailabilityMonitorService(ILogger logger, MessageBus messageBus, RustService rustService, IHostApplicationLifetime appLifetime) { this.logger = logger; this.messageBus = messageBus; - this.rustService = rustService; - this.appLifetime = appLifetime; + this.outageCheck = new(rustService.IsRuntimeAliveAsync, appLifetime.StopApplication, RuntimeProbeSchedule.DEFAULT, appLifetime.ApplicationStopping, logger); this.messageBus.RegisterComponent(this); this.ApplyFilters([], [Event.RUST_SERVICE_UNAVAILABLE]); @@ -54,40 +47,13 @@ public sealed class RustAvailabilityMonitorService : BackgroundService, IMessage string s when !string.IsNullOrWhiteSpace(s) => s, _ => "unknown reason", }; - - // Thread-safe incrementation of the unavailable count and check against the threshold: - var numEvents = Interlocked.Increment(ref this.rustUnavailableCount); - - // On the first event, trigger some Rust availability checks to confirm. - // Just fire and forget - we don't need to await this here. - if (numEvents == 1 && Interlocked.Exchange(ref this.availabilityCheckTriggered, 1) == 0) - { - // - // This is also useful to speed up the detection of Rust availability issues, - // as it triggers two immediate checks instead of waiting for the next scheduled check. - // Scheduled checks are typically every few minutes, which might be too long to wait - // in case of critical Rust service failures. - // - // On the other hand, we cannot kill the .NET server on the first failure, as it might - // be a transient issue. - // - - this.VerifyRustAvailability().Observe($"{nameof(RustAvailabilityMonitorService)}: verifying the Rust availability"); - this.VerifyRustAvailability().Observe($"{nameof(RustAvailabilityMonitorService)}: verifying the Rust availability"); - } - if (numEvents <= UNAVAILABLE_EVENT_THRESHOLD) - { - this.logger.LogWarning("Rust service unavailable (num repeats={NumRepeats}, threshold={Threshold}). Reason = '{Reason}'. Waiting for more occurrences before shutting down the server.", numEvents, UNAVAILABLE_EVENT_THRESHOLD, reason); - return Task.CompletedTask; - } - - // Ensure shutdown is only triggered once: - if (Interlocked.Exchange(ref this.shutdownTriggered, 1) != 0) - return Task.CompletedTask; - - this.logger.LogError("Rust service unavailable (num repeats={NumRepeats}, threshold={Threshold}). Reason = '{Reason}'. Shutting down the server.", numEvents, UNAVAILABLE_EVENT_THRESHOLD, reason); - this.appLifetime.StopApplication(); + // + // The round of probes runs on its own and takes up to a minute. The service which reported + // the failed call goes on meanwhile, e.g., the event stream with its next attempt. The check + // watches the outcome of the round itself. + // + _ = this.outageCheck.Report(reason); return Task.CompletedTask; } @@ -95,17 +61,4 @@ public sealed class RustAvailabilityMonitorService : BackgroundService, IMessage { return Task.FromResult(MessageBusAnswer.NONE); } - - private async Task VerifyRustAvailability() - { - try - { - await this.rustService.ReadUserLanguage(forceRequest: true); - } - catch (Exception e) - { - this.logger.LogWarning(e, "Rust availability check failed."); - await this.messageBus.SendMessage(null, Event.RUST_SERVICE_UNAVAILABLE, "Rust availability check failed"); - } - } } diff --git a/app/MindWork AI Studio/Tools/Services/RustJsonContext.cs b/app/MindWork AI Studio/Tools/Services/RustJsonContext.cs index c0ec6ae74..e700117cd 100644 --- a/app/MindWork AI Studio/Tools/Services/RustJsonContext.cs +++ b/app/MindWork AI Studio/Tools/Services/RustJsonContext.cs @@ -29,7 +29,7 @@ namespace AIStudio.Tools.Services; [JsonSerializable(typeof(ValidateShortcutRequest))] [JsonSerializable(typeof(SetInterfaceSizeRequest))] [JsonSerializable(typeof(CreateMediaJobRequest))] -[JsonSerializable(typeof(LogEventRequest))] +[JsonSerializable(typeof(LogEventsRequest))] [JsonSerializable(typeof(ValidateTokenizerRequest))] [JsonSerializable(typeof(StoreTokenizerRequest))] [JsonSerializable(typeof(DeleteTokenizerRequest))] diff --git a/app/MindWork AI Studio/Tools/Services/RustLogForwarder.cs b/app/MindWork AI Studio/Tools/Services/RustLogForwarder.cs new file mode 100644 index 000000000..e2b13f05c --- /dev/null +++ b/app/MindWork AI Studio/Tools/Services/RustLogForwarder.cs @@ -0,0 +1,136 @@ +using System.Threading.Channels; + +using AIStudio.Tools.Rust; + +namespace AIStudio.Tools.Services; + +/// +/// Forwards the log events of the .NET server to the runtime, in batches and in the order they happened. +/// +/// +/// With one request per event, a burst of events, such as the changes of a build in a watched folder, put +/// thousands of requests on the HTTP/2 connection to the runtime at once. The runtime fell minutes behind, +/// and once the server gave up on more than 20 of them, the runtime closed the connection which all calls +/// of the server share. Therefore, a single sender takes the waiting events off a bounded queue and sends up +/// to MAX_BATCH_SIZE of them per request, one request at a time, over a client of its own. When the runtime +/// cannot keep up, the queue fills up, further events are dropped, and the next batch says how many. +/// +public sealed class RustLogForwarder : IDisposable +{ + /// + /// How many events wait for the runtime at most. + /// + public const int CAPACITY = 10_000; + + /// + /// How many events one request carries at most. + /// + public const int MAX_BATCH_SIZE = 500; + + /// + /// How long the sender waits after a batch failed, so a runtime which is gone is not asked again and again. + /// + public static readonly TimeSpan PAUSE_AFTER_FAILURE = TimeSpan.FromSeconds(1); + + /// + /// How long disposing waits for the waiting events to reach the runtime. + /// + private static readonly TimeSpan DRAIN_TIMEOUT = TimeSpan.FromSeconds(2); + + private readonly Channel queue = Channel.CreateBounded(new BoundedChannelOptions(CAPACITY) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait }); + private readonly HttpClient http; + private readonly TimeSpan pauseAfterFailure; + private readonly Task sender; + + private int lostEvents; + + /// The client which sends the batches. It needs a connection of its own, so the log events never wait in front of other calls. + /// How long the sender waits after a batch failed. + public RustLogForwarder(HttpClient http, TimeSpan pauseAfterFailure) + { + this.http = http; + this.pauseAfterFailure = pauseAfterFailure; + this.sender = Task.Run(this.SendAsync); + } + + /// + /// Queues a log event for the runtime. Never waits: when the queue is full, the event is dropped and counted. + /// + /// The log event. + public void Enqueue(LogEventRequest logEvent) + { + if (!this.queue.Writer.TryWrite(logEvent)) + Interlocked.Increment(ref this.lostEvents); + } + + /// + /// Accepts no further events and sends the waiting ones. + /// + /// A task which ends once every waiting event was sent or lost. + public Task StopAsync() + { + this.queue.Writer.TryComplete(); + return this.sender; + } + + public void Dispose() + { + // Gives the waiting events a moment to reach the runtime before the server ends: + this.StopAsync().Wait(DRAIN_TIMEOUT); + } + + private async Task SendAsync() + { + var reader = this.queue.Reader; + var batch = new List(MAX_BATCH_SIZE + 1); + while (await reader.WaitToReadAsync()) + { + batch.Clear(); + while (batch.Count < MAX_BATCH_SIZE && reader.TryRead(out var logEvent)) + batch.Add(logEvent); + + var eventsInBatch = batch.Count; + var lostBefore = Interlocked.Exchange(ref this.lostEvents, 0); + if (lostBefore > 0) + batch.Add(CreateLostEventsNotice(lostBefore)); + + if (await this.TrySendAsync(batch)) + continue; + + // The events of this batch are lost as well, and the next batch reports them together: + Interlocked.Add(ref this.lostEvents, lostBefore + eventsInBatch); + await Task.Delay(this.pauseAfterFailure); + } + } + + private async Task TrySendAsync(List batch) + { + // + // Nothing here may use a logger: logging means sending another event through this very + // forwarder, and a broken connection to the runtime would feed itself. The console is the + // only way left, which the developer sees while the server runs from the IDE. + // + try + { + using var response = await this.http.PostAsJsonAsync("/log/events", new LogEventsRequest(batch), RustService.JSON_OPTIONS); + if (response.IsSuccessStatusCode) + return true; + + Console.WriteLine($"Failed to send {batch.Count} log events to the runtime: '{response.StatusCode}'."); + return false; + } + catch (Exception e) + { + Console.WriteLine($"Failed to send {batch.Count} log events to the runtime: {TerminalLogger.DescribeException(e)}"); + return false; + } + } + + private static LogEventRequest CreateLostEventsNotice(int lostEvents) => new( + TerminalLogger.FormatTransportTimestamp(DateTimeOffset.UtcNow), + nameof(LogLevel.Warning), + typeof(RustLogForwarder).FullName!, + $"Dropped {lostEvents} log events because the runtime could not take them in time.", + null, + null); +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Services/RustService.App.cs b/app/MindWork AI Studio/Tools/Services/RustService.App.cs index c6c0f64d7..fe61f35fb 100644 --- a/app/MindWork AI Studio/Tools/Services/RustService.App.cs +++ b/app/MindWork AI Studio/Tools/Services/RustService.App.cs @@ -126,6 +126,34 @@ public sealed partial class RustService return response; } + /// + /// Asks the runtime whether it is alive, over a connection of its own. + /// + /// + /// This check tells a runtime which is gone from a connection which failed: all other calls share one + /// HTTP/2 connection, which a flood of requests can congest and which the runtime may close while it + /// keeps running. + /// + /// Ends the check when the server stops. + /// True when the runtime answered. + public async Task IsRuntimeAliveAsync(CancellationToken token) + { + try + { + using var response = await this.aliveHttp.GetAsync("/system/alive", token); + if (response.IsSuccessStatusCode) + return true; + + this.logger?.LogWarning("The runtime refused the check whether it is alive: '{StatusCode}'.", response.StatusCode); + return false; + } + catch (Exception e) when (!token.IsCancellationRequested) + { + this.logger?.LogWarning("The runtime did not answer the check whether it is alive: {Reason}", TerminalLogger.DescribeException(e)); + return false; + } + } + /// /// Requests the Rust runtime to exit the entire desktop application. /// diff --git a/app/MindWork AI Studio/Tools/Services/RustService.Log.cs b/app/MindWork AI Studio/Tools/Services/RustService.Log.cs index cb5e30b28..a0a395113 100644 --- a/app/MindWork AI Studio/Tools/Services/RustService.Log.cs +++ b/app/MindWork AI Studio/Tools/Services/RustService.Log.cs @@ -14,7 +14,7 @@ public sealed partial class RustService } /// - /// Sends a log event to the Rust runtime. + /// Queues a log event for the Rust runtime. /// /// When the log event happened, formatted by TerminalLogger.FormatTransportTimestamp. /// The log level. @@ -22,29 +22,11 @@ public sealed partial class RustService /// The log message. /// Optional exception message. /// Optional exception stack trace. + /// + /// Never waits: the event joins the queue of RustLogForwarder, which sends it in a batch. + /// public void LogEvent(string timestamp, string level, string category, string message, string? exception = null, string? stackTrace = null) { - try - { - // - // Fire-and-forget the log event to avoid blocking. This is the one place which deliberately - // discards its task instead of observing it: observing means logging the failure, and logging - // means sending another log event through this very method. A broken connection to Rust would - // feed itself. The unobserved task exception handler in Program.cs remains the safety net here. - // - var request = new LogEventRequest(timestamp, level, category, message, exception, stackTrace); - _ = this.http.PostAsJsonAsync("/log/event", request, JSON_OPTIONS); - } - catch - { - // - // We don't expect this to ever happen because the HTTP client cannot raise exceptions in fire-and-forget mode. - // This is because we don't await the task, so any exceptions thrown during the HTTP request are not propagated - // back to the caller. - // - - Console.WriteLine("Failed to send log event to Rust service."); - // Ignore errors to avoid log loops - } + this.logForwarder.Enqueue(new LogEventRequest(timestamp, level, category, message, exception, stackTrace)); } } \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Services/RustService.OS.cs b/app/MindWork AI Studio/Tools/Services/RustService.OS.cs index 9fd151e8e..4e72b610c 100644 --- a/app/MindWork AI Studio/Tools/Services/RustService.OS.cs +++ b/app/MindWork AI Studio/Tools/Services/RustService.OS.cs @@ -2,15 +2,15 @@ public sealed partial class RustService { - public async Task ReadUserLanguage(bool forceRequest = false) + public async Task ReadUserLanguage() { - if (!forceRequest && !string.IsNullOrWhiteSpace(this.cachedUserLanguage)) + if (!string.IsNullOrWhiteSpace(this.cachedUserLanguage)) return this.cachedUserLanguage; await this.userLanguageLock.WaitAsync(); try { - if (!forceRequest && !string.IsNullOrWhiteSpace(this.cachedUserLanguage)) + if (!string.IsNullOrWhiteSpace(this.cachedUserLanguage)) return this.cachedUserLanguage; var response = await this.http.GetAsync("/system/language"); @@ -33,15 +33,15 @@ public sealed partial class RustService } } - public async Task ReadUserName(bool forceRequest = false) + public async Task ReadUserName() { - if (!forceRequest && !string.IsNullOrWhiteSpace(this.cachedUserName)) + if (!string.IsNullOrWhiteSpace(this.cachedUserName)) return this.cachedUserName; await this.userNameLock.WaitAsync(); try { - if (!forceRequest && !string.IsNullOrWhiteSpace(this.cachedUserName)) + if (!string.IsNullOrWhiteSpace(this.cachedUserName)) return this.cachedUserName; var response = await this.http.GetAsync("/system/username"); diff --git a/app/MindWork AI Studio/Tools/Services/RustService.cs b/app/MindWork AI Studio/Tools/Services/RustService.cs index 0d004c3b6..2cb8d8142 100644 --- a/app/MindWork AI Studio/Tools/Services/RustService.cs +++ b/app/MindWork AI Studio/Tools/Services/RustService.cs @@ -17,7 +17,18 @@ public sealed partial class RustService : BackgroundService private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(RustService).Namespace, nameof(RustService)); private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(RustService).Namespace, nameof(RustService)); - + + /// + /// How long the runtime may take to answer whether it is alive. Its handler does no work, so + /// anything longer means that the runtime cannot answer at the moment. + /// + private static readonly TimeSpan ALIVE_CHECK_TIMEOUT = TimeSpan.FromSeconds(5); + + /// + /// How long the runtime may take to log one batch of log events. + /// + private static readonly TimeSpan LOG_TIMEOUT = TimeSpan.FromSeconds(30); + private readonly HttpClient http; /// @@ -32,6 +43,23 @@ public sealed partial class RustService : BackgroundService /// private readonly HttpClient extractionHttp; + /// + /// A dedicated client for checking whether the runtime is alive. + /// + /// + /// All other calls share one HTTP/2 connection. A flood of requests can congest it, and the + /// runtime may close it, while the runtime itself keeps running. This client opens a connection + /// of its own, so its check fails only when the runtime cannot accept a connection and answer. + /// + private readonly HttpClient aliveHttp; + + /// + /// A dedicated client for the log events, so a burst of them never waits in front of other calls. + /// + private readonly HttpClient logHttp; + + private readonly RustLogForwarder logForwarder; + private readonly SemaphoreSlim fileDialogLock = new(1, 1); private readonly SemaphoreSlim userLanguageLock = new(1, 1); private readonly SemaphoreSlim userNameLock = new(1, 1); @@ -88,6 +116,9 @@ public sealed partial class RustService : BackgroundService // extraction client below is visible: this.http = CreateHttpClient(apiPort, certificateFingerprint, TimeSpan.FromSeconds(100)); this.extractionHttp = CreateHttpClient(apiPort, certificateFingerprint, Timeout.InfiniteTimeSpan); + this.aliveHttp = CreateHttpClient(apiPort, certificateFingerprint, ALIVE_CHECK_TIMEOUT); + this.logHttp = CreateHttpClient(apiPort, certificateFingerprint, LOG_TIMEOUT); + this.logForwarder = new(this.logHttp, RustLogForwarder.PAUSE_AFTER_FAILURE); } /// @@ -104,6 +135,9 @@ public sealed partial class RustService : BackgroundService this.certificateFingerprint = string.Empty; this.http = new HttpClient(runtime, disposeHandler: false) { BaseAddress = new Uri("https://127.0.0.1"), Timeout = TimeSpan.FromSeconds(100) }; this.extractionHttp = new HttpClient(runtime, disposeHandler: false) { BaseAddress = new Uri("https://127.0.0.1"), Timeout = Timeout.InfiniteTimeSpan }; + this.aliveHttp = new HttpClient(runtime, disposeHandler: false) { BaseAddress = new Uri("https://127.0.0.1"), Timeout = ALIVE_CHECK_TIMEOUT }; + this.logHttp = new HttpClient(runtime, disposeHandler: false) { BaseAddress = new Uri("https://127.0.0.1"), Timeout = LOG_TIMEOUT }; + this.logForwarder = new(this.logHttp, RustLogForwarder.PAUSE_AFTER_FAILURE); } private static HttpClient CreateHttpClient(string apiPort, string certificateFingerprint, TimeSpan timeout) @@ -160,8 +194,13 @@ public sealed partial class RustService : BackgroundService public override void Dispose() { + // First, so the waiting log events still reach the runtime: + this.logForwarder.Dispose(); + this.logHttp.Dispose(); + this.http.Dispose(); this.extractionHttp.Dispose(); + this.aliveHttp.Dispose(); this.userLanguageLock.Dispose(); this.userNameLock.Dispose(); base.Dispose(); diff --git a/app/MindWork AI Studio/Tools/TerminalLogger.cs b/app/MindWork AI Studio/Tools/TerminalLogger.cs index 27a6ce4f8..edda97596 100644 --- a/app/MindWork AI Studio/Tools/TerminalLogger.cs +++ b/app/MindWork AI Studio/Tools/TerminalLogger.cs @@ -86,7 +86,7 @@ public sealed class TerminalLogger() : ConsoleFormatter(FORMATTER_NAME) textWriter.WriteLine(); } - // Send log event to Rust via API (fire-and-forget): + // Queue the log event for Rust, which receives it in a batch: if (RUST_SERVICE is not null) RUST_SERVICE.LogEvent(transportTimestamp, logLevel, category, message, exceptionMessage, stackTrace); diff --git a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md index 49e167a97..14436757c 100644 --- a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md +++ b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md @@ -51,6 +51,7 @@ - Fixed the tiles on the assistants page, which were narrower when their texts were short, so that the tiles did not line up in columns. All tiles now have the same width, and their start buttons sit at the same height. - Fixed the Mathematics prototype, which told the AI that a correct derivative or integral had failed its check when the values of the function were far larger than those of its derivative. - Fixed the Mathematics prototype getting stuck for a long time when it checked a result with a very large factorial or power. Meanwhile, no other calculation could run. +- Fixed AI Studio ceasing to work when many files in a folder of a local data source changed within a short time, e.g., during a software build or while a sync tool updated the folder. - Upgraded several libraries to improve security. - Upgraded Tauri to v2.12.7. - Upgraded MudBlazor to v9.14.0. diff --git a/app/Tests/Serialization/JsonTestRoots.Runtime.cs b/app/Tests/Serialization/JsonTestRoots.Runtime.cs index 8cc355fa5..8725e581b 100644 --- a/app/Tests/Serialization/JsonTestRoots.Runtime.cs +++ b/app/Tests/Serialization/JsonTestRoots.Runtime.cs @@ -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)); diff --git a/app/Tests/Tools/RuntimeOutageCheckTests.cs b/app/Tests/Tools/RuntimeOutageCheckTests.cs new file mode 100644 index 000000000..f39c15f1e --- /dev/null +++ b/app/Tests/Tools/RuntimeOutageCheckTests.cs @@ -0,0 +1,135 @@ +using AIStudio.Tools.Services; + +using Microsoft.Extensions.Logging.Abstractions; + +namespace AIStudio.Tests.Tools; + +/// +/// Checks how the server decides that the runtime is gone after a call to it failed. +/// +/// +/// 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. +/// +[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(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); + } + + /// + /// 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. + /// + [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."); + } + + /// + /// Answers the probes from a script, one answer per probe. + /// + /// Whether the runtime answers the first, second, and later probes. + private sealed class ScriptedRuntime(bool[] answers) + { + private int probes; + + /// + /// How many probes asked the runtime so far. + /// + public int Probes => Volatile.Read(ref this.probes); + + public Task IsAliveAsync(CancellationToken token) + { + var probe = Interlocked.Increment(ref this.probes); + return Task.FromResult(answers[probe - 1]); + } + } +} \ No newline at end of file diff --git a/app/Tests/Tools/RustLogForwarderTests.cs b/app/Tests/Tools/RustLogForwarderTests.cs new file mode 100644 index 000000000..18562d37e --- /dev/null +++ b/app/Tests/Tools/RustLogForwarderTests.cs @@ -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; + +/// +/// Checks how the log events of the .NET server reach the runtime. +/// +/// +/// 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. +/// +[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(); + + /// + /// Plays the runtime: it holds back its first answer until the test lets it go, and records every batch + /// it accepted. + /// + /// How the runtime answers the first batch; every later batch succeeds. + 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 batches = new(); + private int requests; + + /// + /// Ends once the first batch arrived. + /// + public Task FirstRequestArrived => this.firstRequest.Task; + + /// + /// The batches the runtime accepted, in order. + /// + public IReadOnlyList Batches => [..this.batches]; + + /// + /// Lets the runtime answer the first batch, and every later one at once. + /// + public void Answer() => this.answer.TrySetResult(); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri?.AbsolutePath is not "/log/events") + return new HttpResponseMessage(HttpStatusCode.NotFound); + + var batch = await request.Content!.ReadFromJsonAsync(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); + } + } +} \ No newline at end of file diff --git a/app/Tests/Tools/WatcherChangeTallyTests.cs b/app/Tests/Tools/WatcherChangeTallyTests.cs new file mode 100644 index 000000000..8ee61b0f5 --- /dev/null +++ b/app/Tests/Tools/WatcherChangeTallyTests.cs @@ -0,0 +1,76 @@ +using AIStudio.Tools.Services.Indexing; + +namespace AIStudio.Tests.Tools; + +/// +/// Checks how the changes a watcher reports are counted instead of logged one by one. +/// +[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)); + } +} \ No newline at end of file diff --git a/runtime/src/log.rs b/runtime/src/log.rs index c46e0c01f..9acb23795 100644 --- a/runtime/src/log.rs +++ b/runtime/src/log.rs @@ -455,15 +455,32 @@ fn log_with_level( } } -/// Logs an event from the .NET server. -pub async fn log_event(Json(event): Json) -> Json { +/// Logs a batch of events from the .NET server, in the order the server sent them. +/// +/// The server sends its events in batches. With one request per event, a burst of events, such as +/// the changes of a build in a watched folder, flooded the one HTTP/2 connection which all calls of +/// the server share, until the runtime closed it. +pub async fn log_events(Json(request): Json) -> Json { + log_dotnet_events(log::logger(), &request.events); + Json(LogEventResponse { success: true, issue: String::new() }) +} + +/// Logs the given events from the .NET server, one after another. +fn log_dotnet_events(logger: &dyn log::Log, events: &[LogEvent]) { + for event in events { + log_dotnet_event(logger, event); + } +} + +/// Logs one event from the .NET server. +fn log_dotnet_event(logger: &dyn log::Log, event: &LogEvent) { let level = parse_dotnet_log_level(&event.level); let message = event.message.as_str(); let category = event.category.as_str(); let created_at = parse_dotnet_timestamp(&event.timestamp); log_with_level( - log::logger(), + logger, level, category, created_at, @@ -481,8 +498,6 @@ pub async fn log_event(Json(event): Json) -> Json { if created_at.is_none() && !WARNED_ABOUT_UNREADABLE_DOTNET_TIMESTAMP.swap(true, Ordering::Relaxed) { log::warn!(Source = ".NET Server", Comp = category; "Could not read the timestamp '{}' of a log event. Such events show the time they arrived instead. This warning appears only once.", event.timestamp); } - - Json(LogEventResponse { success: true, issue: String::new() }) } /// The response the get log paths request. @@ -505,6 +520,13 @@ pub struct LogEvent { stack_trace: Option, } +/// A batch of log events from the .NET server. +#[derive(Deserialize)] +pub struct LogEventsRequest { + /// The events, in the order they happened. + events: Vec, +} + /// The response to a log event request. #[derive(Serialize)] pub struct LogEventResponse { @@ -685,6 +707,29 @@ mod tests { ]); } + #[test] + fn a_batch_of_dotnet_events_is_logged_in_order() { + log::set_max_level(LevelFilter::Info); + + // The shape in which the .NET server sends its batches: + let request: LogEventsRequest = serde_json::from_str(r#"{"events":[ + {"timestamp":"2026-11-25T18:02:02.2220000+00:00","level":"Information","category":"Tests","message":"First","exception":null,"stack_trace":null}, + {"timestamp":"2026-11-25T18:02:03.2930000+00:00","level":"Error","category":"Tests","message":"Second","exception":"Boom","stack_trace":"at Third()"} + ]}"#).unwrap(); + + let logger = CapturingLogger::default(); + log_dotnet_events(&logger, &request.events); + + let first = parse_dotnet_timestamp("2026-11-25T18:02:02.2220000+00:00"); + let second = parse_dotnet_timestamp("2026-11-25T18:02:03.2930000+00:00"); + assert_eq!(logger.0.into_inner().unwrap(), vec![ + (String::from("First"), first), + (String::from("Second"), second), + (String::from(" Exception: Boom"), second), + (String::from(" at Third()"), second), + ]); + } + #[test] fn flatpak_standard_path_matches_tauri_local_data_path() { let base_directory = PathBuf::from("/var/data"); diff --git a/runtime/src/runtime_api.rs b/runtime/src/runtime_api.rs index f6a77ddd4..cf803d009 100644 --- a/runtime/src/runtime_api.rs +++ b/runtime/src/runtime_api.rs @@ -1,6 +1,7 @@ use log::info; use once_cell::sync::Lazy; use axum::extract::DefaultBodyLimit; +use axum::http::StatusCode; use axum::middleware; use axum::routing::{delete, get, post}; use axum::Router; @@ -19,6 +20,10 @@ static RUSTLS_CRYPTO_PROVIDER_INIT: Once = Once::new(); /// what a tool returns to a model well below this. The limit is headroom, not a working constraint. const PROMPT_INJECTION_BODY_LIMIT_BYTES: usize = 16 * 1024 * 1024; +/// The request body limit for a batch of log events from the .NET server. A batch rarely takes more +/// than a few hundred kilobytes; the limit leaves room for a batch full of stack traces. +const LOG_EVENTS_BODY_LIMIT_BYTES: usize = 16 * 1024 * 1024; + /// The port used for the runtime API server. In the development environment, we use a fixed /// port, in the production environment we use the next available port. This differentiation /// is necessary because we cannot communicate the port to the .NET server in the development @@ -34,6 +39,7 @@ pub static API_SERVER_PORT: Lazy = Lazy::new(|| { /// Creates the router with every route of the runtime API, each of which requires the API token. fn create_router() -> Router { let router = Router::new() + .route("/system/alive", get(is_alive)) .route("/system/dotnet/port", get(crate::dotnet::dotnet_port)) .route("/system/dotnet/ready", get(crate::dotnet::dotnet_ready)) .route("/system/qdrant-edge/info", get(crate::qdrant_edge_database::qdrant_edge_info)) @@ -91,7 +97,13 @@ fn create_router() -> Router { .route("/image/prepare", post(crate::image::prepare_image)) .route("/image/prepare-for-model", post(crate::image::prepare_image_for_model)) .route("/log/paths", get(crate::log::get_log_paths)) - .route("/log/event", post(crate::log::log_event)) + // + // A batch holds up to a few hundred log events of the .NET server, some with a stack trace, + // which can exceed Axum's 2 MB default. The runtime would refuse such a batch with 413, and + // its events would be lost. + // + .route("/log/events", post(crate::log::log_events) + .layer(DefaultBodyLimit::max(LOG_EVENTS_BODY_LIMIT_BYTES))) .route("/tokenizer/count", post(crate::tokenizer::token_count)) .route("/tokenizer/validate", post(crate::tokenizer::validate_tokenizer)) .route("/tokenizer/store", post(crate::tokenizer::store_tokenizer)) @@ -116,6 +128,15 @@ fn require_api_token(router: Router) -> Router { router.route_layer(middleware::from_extractor::()) } +/// Tells the .NET server that the runtime is alive. +/// +/// The .NET server asks this route over a connection of its own whenever a call to the runtime +/// failed. The handler does no work at all, so an answer proves exactly what the server wants to +/// know: the runtime accepts a new connection and runs a handler. Nothing else can make it fail. +async fn is_alive() -> StatusCode { + StatusCode::NO_CONTENT +} + /// Starts the runtime API server. The server is used to communicate with the .NET server and /// to provide additional functionality to the Tauri app. pub fn start_runtime_api() { @@ -294,6 +315,12 @@ mod tests { assert!(unprotected_routes.is_empty(), "These routes answer without the API token: {unprotected_routes:#?}"); } + #[tokio::test] + async fn the_alive_route_answers_only_with_the_token() { + assert_eq!(send(create_router(), request("GET", "/system/alive", None, "")).await, StatusCode::UNAUTHORIZED); + assert_eq!(send(create_router(), request("GET", "/system/alive", Some(API_TOKEN.to_hex_text()), "")).await, StatusCode::NO_CONTENT); + } + #[tokio::test] async fn a_valid_token_gets_through_to_the_handler() { // The handler fails on the incomplete body, before it touches any file.