From 5053bfb951f812da9bd66ce634590725b8c1cef9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 13 Aug 2026 14:58:34 +0700 Subject: [PATCH] P0: integrate realtime FAT and clean evidence retest on 1.6.26 Transplant the validated P0 FAT changes onto the current 1.6.26 main baseline while preserving the timestamp rounding, full-resolution evidence tooltip, and release evidence changes already merged by parallel work. --- IoListTestingWindow.SupplementalEvidence.cs | 65 ++++++++++- MainWindow.IoTesting.AutoConnect.cs | 92 ++++++--------- MainWindow.IoTesting.cs | 16 ++- Services/Iec61850ReportPlanner.cs | 18 ++- .../IoTesting/IoFatCleanSessionService.cs | 110 ++++++++++++++++++ Services/IoTesting/IoTestEvidenceJournal.cs | 63 ++++++++-- Services/IoTesting/IoTestSessionController.cs | 67 ++++++++++- .../IoFatReportPreviewServiceTests.cs | 9 +- .../ARSAS.Tests/IoTestEvidenceJournalTests.cs | 33 ++++++ .../ARSAS.Tests/IoTestFatP0RegressionTests.cs | 82 +++++++++++++ tests/ARSAS.Tests/IoTestingUiContractTests.cs | 12 +- 11 files changed, 486 insertions(+), 81 deletions(-) create mode 100644 Services/IoTesting/IoFatCleanSessionService.cs create mode 100644 tests/ARSAS.Tests/IoTestFatP0RegressionTests.cs diff --git a/IoListTestingWindow.SupplementalEvidence.cs b/IoListTestingWindow.SupplementalEvidence.cs index 689b3adee..0874287b5 100644 --- a/IoListTestingWindow.SupplementalEvidence.cs +++ b/IoListTestingWindow.SupplementalEvidence.cs @@ -10,6 +10,7 @@ public partial class IoListTestingWindow { private Button? _comtradeEvidenceButton; private Button? _timeSyncEvidenceButton; + private Button? _cleanSessionButton; public int SelectedSupplementalEvidenceCount { @@ -41,9 +42,13 @@ private void InstallSupplementalEvidenceControls() _comtradeEvidenceButton = CreateEvidenceButton("COMTRADE · —", OpenComtradeEvidence_Click); _comtradeEvidenceButton.ToolTip = "Browse relay fault records. A remote COMTRADE listing is sufficient File Service FAT evidence; download is optional."; + _cleanSessionButton = CreateEvidenceButton("New Clean FAT", NewCleanFatSession_Click); + _cleanSessionButton.ToolTip = "Archive all current FAT evidence and reset the project to a zero-evidence retest session"; + var insertionIndex = actionPanel.Children.IndexOf(WorkspacePreviewToggle) + 1; actionPanel.Children.Insert(insertionIndex, _timeSyncEvidenceButton); actionPanel.Children.Insert(insertionIndex + 1, _comtradeEvidenceButton); + actionPanel.Children.Insert(insertionIndex + 2, _cleanSessionButton); RefreshSupplementalEvidenceControls(); } @@ -156,6 +161,64 @@ private async void RefreshTimeSyncEvidence_Click(object sender, RoutedEventArgs await CaptureTimeSyncEvidenceAfterPreparationAsync(engineeringWindow, SelectedIed); } + private void NewCleanFatSession_Click(object sender, RoutedEventArgs e) + { + var answer = MessageBox.Show( + this, + "Create a NEW CLEAN FAT session for this project?\n\n" + + "• All current ON/OFF evidence and relay timestamps will be cleared from the active workspace.\n" + + "• Time Sync and COMTRADE evidence will be cleared from the active report.\n" + + "• Existing hash-chained evidence files will NOT be deleted or rewritten; they will be verified and archived outside the new export scope.\n" + + "• All import-ready IO points will be enabled again for retest.\n\n" + + "Use this after correcting relay time synchronization or whenever the customer requires a completely fresh FAT run.", + "New Clean FAT Session", + MessageBoxButton.YesNo, + MessageBoxImage.Warning, + MessageBoxResult.No); + if (answer != MessageBoxResult.Yes) + return; + + try + { + if (Session.IsSessionActive) + { + var stopped = Session.Stop("Sealed before New Clean FAT retest reset."); + if (!stopped.Succeeded) + { + ShowActionResult(stopped, "Could not seal the active FAT session"); + return; + } + } + + var storage = Storage ?? throw new InvalidOperationException("FAT workspace persistence is not available."); + var result = IoFatCleanSessionService.ResetForRetest(storage, Project); + var sessionReset = Session.ResetForCleanRetest(); + if (!sessionReset.Succeeded) + { + ShowActionResult(sessionReset, "Clean FAT session state could not be reset"); + return; + } + + PreparationStatusText = result.ArchivedJournalCount > 0 + ? $"NEW CLEAN FAT ready · {result.ResetPointCount} point(s) reset · {result.ArchivedJournalCount} prior journal(s) archived" + : $"NEW CLEAN FAT ready · {result.ResetPointCount} point(s) reset · active evidence is empty"; + RefreshSupplementalEvidenceControls(); + Raise(nameof(SelectedSupplementalEvidenceCount)); + Raise(nameof(SelectedEvidenceCount)); + RaiseStatusProperties(); + RaiseSelectedIedContextProperties(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException) + { + MessageBox.Show( + this, + ex.Message, + "New Clean FAT Session failed", + MessageBoxButton.OK, + MessageBoxImage.Error); + } + } + private void OpenComtradeEvidence_Click(object sender, RoutedEventArgs e) { var ied = SelectedIed; @@ -225,4 +288,4 @@ private static bool HasLiveValue(string? value) !text.Equals("Unknown", StringComparison.OrdinalIgnoreCase) && !text.Contains("not probed", StringComparison.OrdinalIgnoreCase); } -} \ No newline at end of file +} diff --git a/MainWindow.IoTesting.AutoConnect.cs b/MainWindow.IoTesting.AutoConnect.cs index 5e3233a19..c6aab0b1c 100644 --- a/MainWindow.IoTesting.AutoConnect.cs +++ b/MainWindow.IoTesting.AutoConnect.cs @@ -84,11 +84,9 @@ void ReportProgress(string message) if (string.IsNullOrWhiteSpace(device.SclIedName)) device.SclIedName = ied.IedName; - // Monitoring-only toward the process: no control commands are executed. Use - // configured RCB/DataSet coverage first, then an association-scoped temporary - // dynamic DataSet/URCB when exact coverage is missing, with bounded MMS - // verification/fallback last. Temporary report resources are released when the - // native monitoring session stops. + // Monitoring-only toward the process: no control commands are executed. FAT uses + // deterministic fast MMS acquisition for digital commissioning points while the + // normal engineering workspace keeps report-first behavior for ordinary intervals. device.AllowDynamicDataSetWrites = true; try @@ -242,16 +240,18 @@ void ReportProgress(string message) _ioTestLiveBindingService.BindIed(ied, Devices); var allRequestedPointsLive = requestedPoints.All(point => point.LiveBindingState == IoTestLiveBindingState.LivePointReady); + var fatPollingNotActive = device.IsMonitoring && + device.Points.Any(point => point.PollingIntervalMs > 500); - if (device.IsMonitoring && (selectionChanged || !allRequestedPointsLive)) + if (device.IsMonitoring && (selectionChanged || !allRequestedPointsLive || fatPollingNotActive)) { - ReportProgress("Refreshing report acquisition for the workbook scope"); + ReportProgress("Refreshing FAT acquisition · deterministic fast digital polling"); await StopDeviceMonitorAsync(device); } if (!device.IsMonitoring) { - ReportProgress("Arming static RCB first · dynamic DataSet/URCB for uncovered points"); + ReportProgress("Starting FAT live acquisition · fast MMS verification"); if (!await StartDeviceMonitorAsync(device, navigateToExplorer: false)) { _ioTestLiveBindingService.BindIed(ied, Devices); @@ -260,12 +260,14 @@ void ReportProgress(string message) } } + // Do not hold the operator behind an 8–18 second report-settling phase. FAT + // readiness is the first usable live image; report planning for non-fast points + // can continue in the monitor loop after the card is already responsive. var acquisition = await SettleIoFatReportPriorityAsync( ied, requestedPoints, device, - ReportProgress, - allowSingleRestart: true); + ReportProgress); var binding = _ioTestLiveBindingService.BindIed(ied, Devices); var liveCount = requestedPoints.Count(point => @@ -284,16 +286,16 @@ void ReportProgress(string message) var modelText = usedSavedModel ? "saved model" : "live model"; var acquisitionText = acquisition.PollingCount == 0 ? $"report-backed {acquisition.ReportCount}/{requestedPoints.Count}" - : $"report-backed {acquisition.ReportCount}/{requestedPoints.Count} · MMS fallback {acquisition.PollingCount}"; + : $"fast MMS {acquisition.PollingCount} · report-backed {acquisition.ReportCount}"; var timeSyncText = IoFatSupplementalEvidenceService.FindTimeSyncSignal(device) == null ? " · time-sync fallback ready" : " · time-sync status armed"; var message = $"{ied.IedName} · {liveCount}/{requestedPoints.Count} live · {acquisitionText}{timeSyncText}"; SetStatus(message); AddLog( - acquisition.PollingCount == 0 ? "INFO" : "WARN", + acquisition.PollingCount == 0 ? "INFO" : "INFO", "IO Testing", - $"{message}. Acquisition policy: configured RCB → temporary dynamic DataSet/URCB → bounded MMS verification/fallback. No process control commands are enabled. IED live-bound={binding.LivePointCount}; model={modelText}; mode={device.AcquisitionMode}."); + $"{message}. FAT acquisition prioritizes deterministic fast MMS for digital commissioning points; normal engineering monitoring retains report-first behavior. No process control commands are enabled. IED live-bound={binding.LivePointCount}; model={modelText}; mode={device.AcquisitionMode}."); ReportProgress(message); return IoTestSessionActionResult.Success(message); } @@ -322,36 +324,14 @@ private async Task SettleIoFatReportPriorityAsync( IoTestIedPlan ied, IReadOnlyCollection requestedPoints, Iec61850MonitorDevice device, - Action reportProgress, - bool allowSingleRestart) + Action reportProgress) { - var first = await ObserveIoFatAcquisitionAsync( - ied, - requestedPoints, - device, - reportProgress, - TimeSpan.FromSeconds(8)); - - if (!allowSingleRestart || - first.PollingCount == 0 || - !device.AllowDynamicDataSetWrites || - !device.IsMonitoring) - { - return first; - } - - reportProgress($"{first.PollingCount} point(s) still on MMS fallback · rebuilding the report plan once"); - await StopDeviceMonitorAsync(device); - await Task.Delay(180); - if (!await StartDeviceMonitorAsync(device, navigateToExplorer: false)) - return first; - return await ObserveIoFatAcquisitionAsync( ied, requestedPoints, device, reportProgress, - TimeSpan.FromSeconds(10)); + TimeSpan.FromMilliseconds(2500)); } private async Task ObserveIoFatAcquisitionAsync( @@ -364,30 +344,40 @@ private async Task ObserveIoFatAcquisitionAsync( var deadline = DateTime.UtcNow + timeout; var last = ReadIoFatAcquisitionSummary(requestedPoints, device); var announced = false; + var nextBindingRefreshUtc = DateTime.MinValue; while (DateTime.UtcNow < deadline && device.IsMonitoring) { - await Task.Delay(120); - _ioTestLiveBindingService.BindIed(ied, Devices); + await Task.Delay(100); + var nowUtc = DateTime.UtcNow; + if (nowUtc >= nextBindingRefreshUtc) + { + _ioTestLiveBindingService.BindIed(ied, Devices); + nextBindingRefreshUtc = nowUtc.AddMilliseconds(250); + } last = ReadIoFatAcquisitionSummary(requestedPoints, device); if (!announced) { - reportProgress("Validating static/dynamic report coverage · MMS is fallback only"); + reportProgress("Waiting for first live FAT image · report optimization continues in background"); announced = true; } - var plannerSettled = !ContainsPlannerStage(device.AcquisitionMode); - if (last.LiveCount == requestedPoints.Count && - plannerSettled && - last.UnknownCount == 0 && - (last.PollingCount == 0 || DateTime.UtcNow >= deadline - TimeSpan.FromSeconds(2))) - { + var liveImageReady = requestedPoints.All(HasUsableFatLiveValue); + if (last.LiveCount == requestedPoints.Count && liveImageReady && last.UnknownCount == 0) break; - } } - return last; + _ioTestLiveBindingService.BindIed(ied, Devices); + return ReadIoFatAcquisitionSummary(requestedPoints, device); + } + + private static bool HasUsableFatLiveValue(IoTestPointPlan point) + { + var value = (point.Runtime.CurrentValue ?? string.Empty).Trim(); + return value.Length > 0 && value != "-" && value != "—" && + !value.Equals("Unknown", StringComparison.OrdinalIgnoreCase) && + !value.Contains("pending", StringComparison.OrdinalIgnoreCase); } private static IoFatAcquisitionSummary ReadIoFatAcquisitionSummary( @@ -422,12 +412,6 @@ private static bool IsReportSource(string source) source.Contains("URCB", StringComparison.OrdinalIgnoreCase) || source.Contains("report", StringComparison.OrdinalIgnoreCase); - private static bool ContainsPlannerStage(string? mode) - => (mode ?? string.Empty).Contains("arming", StringComparison.OrdinalIgnoreCase) || - (mode ?? string.Empty).Contains("live start", StringComparison.OrdinalIgnoreCase) || - (mode ?? string.Empty).Contains("preparing", StringComparison.OrdinalIgnoreCase) || - (mode ?? string.Empty).Contains("settling", StringComparison.OrdinalIgnoreCase); - private sealed record IoFatAcquisitionSummary( int LiveCount, int ReportCount, diff --git a/MainWindow.IoTesting.cs b/MainWindow.IoTesting.cs index c81c9d51b..142c521a9 100644 --- a/MainWindow.IoTesting.cs +++ b/MainWindow.IoTesting.cs @@ -14,11 +14,13 @@ namespace ArIED61850Tester; public partial class MainWindow { + private const int IoFatPollingIntervalMs = 250; private readonly IoListExcelImportService _ioListExcelImportService = new(); private readonly IoTestLiveBindingService _ioTestLiveBindingService = new(); private FrameworkElement? _ioListTestingLauncherCard; private IoTestSessionController? _activeIoTestSessionController; private long _ioTestObservationSequence; + private int? _pollingIntervalBeforeIoFat; protected override void OnInitialized(EventArgs e) { @@ -351,6 +353,12 @@ private Task ShowIoTestingWorkspaceAsync(IoTestWorkspaceLaunchResult launch, int MessageBoxImage.Information); } + // FAT is a commissioning workflow: discrete IO must feel immediate even when + // report configuration is incomplete. The previous engineering poll interval is + // restored when the FAT window closes so normal Live Monitor behavior is unchanged. + _pollingIntervalBeforeIoFat ??= PollingIntervalMs; + PollingIntervalMs = Math.Min(PollingIntervalMs, IoFatPollingIntervalMs); + var controller = launch.Session; var persistence = launch.Workspace; var window = new IoListTestingWindow(launch.Project, controller, persistence) { Owner = this }; @@ -368,6 +376,12 @@ void WindowClosed(object? sender, EventArgs args) controller.Dispose(); persistence.Dispose(); + if (_pollingIntervalBeforeIoFat.HasValue) + { + PollingIntervalMs = _pollingIntervalBeforeIoFat.Value; + _pollingIntervalBeforeIoFat = null; + } + if (!IsLoaded) return; IsEnabled = true; @@ -387,7 +401,7 @@ private IoTestSessionController CreateIoTestSession(IoTestProject project, strin => new( project, ResolveIoTestDevice, - action => Dispatcher.BeginInvoke(action, DispatcherPriority.DataBind), + action => Dispatcher.BeginInvoke(action, DispatcherPriority.Background), evidenceRoot); private static string IoTestingProjectsRoot() => Path.Combine( diff --git a/Services/Iec61850ReportPlanner.cs b/Services/Iec61850ReportPlanner.cs index bb573df09..6a1dead13 100644 --- a/Services/Iec61850ReportPlanner.cs +++ b/Services/Iec61850ReportPlanner.cs @@ -5,6 +5,7 @@ namespace ArIED61850Tester.Services; public static class Iec61850ReportPlanner { private const int DynamicDataSetChunkSize = 96; + private const int FastCommissioningPollingThresholdMs = 500; public static IReadOnlyList BuildPlans( Iec61850MonitorDevice device, @@ -19,9 +20,18 @@ public static IReadOnlyList BuildPlans( var plans = new List(); var assigned = new HashSet(StringComparer.OrdinalIgnoreCase); + // FAT/commissioning digital points intentionally use deterministic fast MMS reads. + // At <= 500 ms the point is explicitly asking for commissioning latency rather than + // low-rate report verification. Leaving it out of the report plan also prevents the + // runtime from stretching its verification interval into multi-second territory. + // Normal Live Monitor points keep the existing report-first policy. + var reportCandidates = all + .Where(point => !IsFastCommissioningPoint(point)) + .ToList(); + // Static discovery hints are candidates only. Exact coverage is confirmed later // from the DataSet members returned by the native report subscription planner. - var staticGroups = all + var staticGroups = reportCandidates .Where(point => !string.IsNullOrWhiteSpace(point.ReportControlReference) || !string.IsNullOrWhiteSpace(point.DataSetReference)) .GroupBy(BuildStaticKey, StringComparer.OrdinalIgnoreCase); @@ -48,7 +58,7 @@ public static IReadOnlyList BuildPlans( // monitoring stops; polling remains the final fallback. if (dynamicWritesAllowed) { - var dynamicMembers = all + var dynamicMembers = reportCandidates .Where(point => !assigned.Contains(point.PointKey)) .ToList(); @@ -74,6 +84,7 @@ public static IReadOnlyList BuildDynamicFallbackPlans( IEnumerable points) { var members = points + .Where(point => !IsFastCommissioningPoint(point)) .GroupBy(point => point.PointKey, StringComparer.OrdinalIgnoreCase) .Select(group => group.First()) .ToList(); @@ -128,6 +139,9 @@ private static bool LooksBuffered(string? reference) text.Contains("buffer", StringComparison.OrdinalIgnoreCase); } + private static bool IsFastCommissioningPoint(Iec61850MonitorPoint point) + => point.PollingIntervalMs <= FastCommissioningPollingThresholdMs && IsFastPoint(point); + private static bool IsFastPoint(Iec61850MonitorPoint point) { var reference = Normalize(point.IecReference); diff --git a/Services/IoTesting/IoFatCleanSessionService.cs b/Services/IoTesting/IoFatCleanSessionService.cs new file mode 100644 index 000000000..5cf436ceb --- /dev/null +++ b/Services/IoTesting/IoFatCleanSessionService.cs @@ -0,0 +1,110 @@ +using ArIED61850Tester.Models.IoTesting; + +namespace ArIED61850Tester.Services.IoTesting; + +public sealed record IoFatCleanSessionResult( + int ResetPointCount, + int ArchivedJournalCount, + string ArchiveDirectory); + +/// +/// Creates a clean FAT evidence boundary without rewriting or deleting historical proof. +/// Existing hash-chained journals are verified, then moved below an archive subdirectory; +/// the active top-level evidence directory becomes empty so a new export cannot pick up +/// timestamps from the previous test run. +/// +public static class IoFatCleanSessionService +{ + public static IoFatCleanSessionResult ResetForRetest( + IoTestWorkspacePersistence storage, + IoTestProject project) + { + ArgumentNullException.ThrowIfNull(storage); + ArgumentNullException.ThrowIfNull(project); + + var evidenceDirectory = storage.EvidenceProjectDirectory; + var journals = Directory.Exists(evidenceDirectory) + ? Directory.EnumerateFiles(evidenceDirectory, "*.evidence.jsonl", SearchOption.TopDirectoryOnly) + .OrderBy(path => path, StringComparer.OrdinalIgnoreCase) + .ToArray() + : Array.Empty(); + + // Verify every old journal before moving anything. A clean retest must never hide + // already-damaged evidence behind an archive operation. + foreach (var path in journals) + { + var verification = IoTestEvidenceJournal.Verify(path); + if (!verification.IsValid) + { + throw new InvalidDataException( + $"Cannot create a clean FAT session because evidence '{Path.GetFileName(path)}' failed integrity verification: {verification.Error}"); + } + } + + var archiveDirectory = string.Empty; + if (journals.Length > 0) + { + archiveDirectory = CreateArchiveDirectory(evidenceDirectory); + Directory.CreateDirectory(archiveDirectory); + foreach (var path in journals) + { + var destination = Path.Combine(archiveDirectory, Path.GetFileName(path)); + File.Move(path, destination, overwrite: false); + } + } + + var resetPointCount = 0; + foreach (var ied in project.Ieds) + { + ClearIedEvidence(ied); + foreach (var point in ied.TestPoints) + { + var runtime = point.Runtime; + runtime.State = IoTestPointState.NotStarted; + runtime.LastObservedState = null; + runtime.LastSequence = -1; + runtime.ConnectionGeneration = -1; + runtime.OnEvidence = null; + runtime.OffEvidence = null; + runtime.StatusReason = "Clean retest · no evidence captured"; + runtime.Attempt = 0; + runtime.CurrentValue = "-"; + runtime.CurrentQuality = "Unknown"; + runtime.CurrentSource = "Clean retest · awaiting live baseline"; + runtime.CurrentIedTimestamp = "—"; + + // Completed rows restored from a previous snapshot are automatically + // disabled by the continuation workflow. A deliberate project-wide clean + // retest re-enables every import-ready FAT row. + point.TestEnabled = point.ImportReady; + resetPointCount++; + } + } + + storage.SaveNow(); + return new IoFatCleanSessionResult(resetPointCount, journals.Length, archiveDirectory); + } + + private static string CreateArchiveDirectory(string evidenceDirectory) + { + var archiveRoot = Path.Combine(evidenceDirectory, "archive"); + var baseName = DateTime.UtcNow.ToString("yyyyMMddTHHmmssfffZ"); + var candidate = Path.Combine(archiveRoot, baseName + "_pre_retest"); + var suffix = 1; + while (Directory.Exists(candidate)) + candidate = Path.Combine(archiveRoot, $"{baseName}_pre_retest_{suffix++}"); + return candidate; + } + + private static void ClearIedEvidence(IoTestIedPlan ied) + { + ied.LatestComtradeFiles = string.Empty; + ied.LatestComtradeRemotePath = string.Empty; + ied.LatestComtradeCompleteness = string.Empty; + ied.LatestComtradeAcquisitionSource = string.Empty; + ied.LatestComtradeModifiedAtUtc = null; + ied.LatestComtradeCapturedAtUtc = null; + ied.LatestComtradeFileCount = 0; + ied.LatestComtradeKnownSizeBytes = 0L; + } +} diff --git a/Services/IoTesting/IoTestEvidenceJournal.cs b/Services/IoTesting/IoTestEvidenceJournal.cs index ee96cc502..1baec20cc 100644 --- a/Services/IoTesting/IoTestEvidenceJournal.cs +++ b/Services/IoTesting/IoTestEvidenceJournal.cs @@ -11,6 +11,15 @@ public interface IIoTestEvidenceJournal : IDisposable long RecordCount { get; } string LastHash { get; } IoTestJournalEnvelope Append(IoTestJournalEntry entry); + + // Existing test doubles and alternate journals keep working through this default + // implementation. The production journal overrides it so a baseline batch performs + // one durable disk flush instead of one fsync per FAT point. + IReadOnlyList AppendBatch(IEnumerable entries) + { + ArgumentNullException.ThrowIfNull(entries); + return entries.Select(Append).ToList(); + } } public sealed class IoTestEvidenceJournal : IIoTestEvidenceJournal @@ -68,22 +77,52 @@ public IoTestJournalEnvelope Append(IoTestJournalEntry entry) lock (_sync) { ObjectDisposedException.ThrowIf(_disposed, this); - var sequence = checked(_recordCount + 1); - var previousHash = _lastHash; - var hashInput = JsonSerializer.SerializeToUtf8Bytes( - new JournalHashInput(sequence, previousHash, entry), - JsonOptions); - var hash = Convert.ToHexString(SHA256.HashData(hashInput)).ToLowerInvariant(); - var envelope = new IoTestJournalEnvelope(sequence, previousHash, hash, entry); - _writer.WriteLine(JsonSerializer.Serialize(envelope, JsonOptions)); - _writer.Flush(); - _stream.Flush(flushToDisk: true); - _recordCount = sequence; - _lastHash = hash; + var envelope = AppendCore(entry); + FlushDurable(); return envelope; } } + public IReadOnlyList AppendBatch(IEnumerable entries) + { + ArgumentNullException.ThrowIfNull(entries); + lock (_sync) + { + ObjectDisposedException.ThrowIf(_disposed, this); + var envelopes = new List(); + foreach (var entry in entries) + { + ArgumentNullException.ThrowIfNull(entry); + envelopes.Add(AppendCore(entry)); + } + + if (envelopes.Count > 0) + FlushDurable(); + return envelopes; + } + } + + private IoTestJournalEnvelope AppendCore(IoTestJournalEntry entry) + { + var sequence = checked(_recordCount + 1); + var previousHash = _lastHash; + var hashInput = JsonSerializer.SerializeToUtf8Bytes( + new JournalHashInput(sequence, previousHash, entry), + JsonOptions); + var hash = Convert.ToHexString(SHA256.HashData(hashInput)).ToLowerInvariant(); + var envelope = new IoTestJournalEnvelope(sequence, previousHash, hash, entry); + _writer.WriteLine(JsonSerializer.Serialize(envelope, JsonOptions)); + _recordCount = sequence; + _lastHash = hash; + return envelope; + } + + private void FlushDurable() + { + _writer.Flush(); + _stream.Flush(flushToDisk: true); + } + public static IoTestJournalVerificationResult Verify(string filePath) { if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath)) diff --git a/Services/IoTesting/IoTestSessionController.cs b/Services/IoTesting/IoTestSessionController.cs index 1285a4c37..962c22b02 100644 --- a/Services/IoTesting/IoTestSessionController.cs +++ b/Services/IoTesting/IoTestSessionController.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using System.ComponentModel; +using System.Diagnostics; using System.Reflection; using ArIED61850Tester.Models; using ArIED61850Tester.Models.IoTesting; @@ -8,6 +9,8 @@ namespace ArIED61850Tester.Services.IoTesting; public sealed class IoTestSessionController : ObservableObject, IDisposable { + private const int MaxSnapshotsPerDrain = 64; + private const int DrainBudgetMilliseconds = 4; private static readonly string CurrentApplicationVersion = typeof(IoTestSessionController).Assembly .GetCustomAttribute()?.InformationalVersion @@ -157,14 +160,21 @@ public IoTestSessionActionResult Start(IoTestIedPlan? ied) EvidenceRecordCount = 0; LastJournalHash = string.Empty; JournalIntegrityText = "Evidence journal open · hash chain initialized"; - AppendRequired(SessionEvent("session_started", "FAT session started with a live baseline for every enabled bound point.")); + // Establish all baselines first, then persist the startup records with one + // durable flush. Hash chaining is unchanged, but a 100-point FAT no longer + // performs 101 synchronous fsync operations on the UI thread. + var startupEntries = new List(bindings.Count + 1) + { + SessionEvent("session_started", "FAT session started with a live baseline for every enabled bound point.") + }; foreach (var binding in bindings) { var observation = CreateObservation(binding.Point, binding.LivePoint, _connectionGeneration, DateTimeOffset.UtcNow); _evaluator.StartAttempt(binding.Point, observation); - AppendRequired(PointEvent("baseline", binding.Point, observation, null, binding.Point.Runtime.StatusReason)); + startupEntries.Add(PointEvent("baseline", binding.Point, observation, null, binding.Point.Runtime.StatusReason)); } + AppendBatchRequired(startupEntries); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) { @@ -257,6 +267,26 @@ public IoTestSessionActionResult Stop(string reason = "Stopped by operator") return IoTestSessionActionResult.Success(reason); } + public IoTestSessionActionResult ResetForCleanRetest() + { + ThrowIfDisposed(); + if (IsSessionActive) + return IoTestSessionActionResult.Failure("Stop the active FAT session before creating a clean retest session."); + + CleanupSessionResources(disposeJournal: true); + SessionId = Guid.Empty; + StartedAtUtc = null; + CompletedAtUtc = null; + JournalPath = string.Empty; + EvidenceRecordCount = 0; + LastJournalHash = string.Empty; + JournalIntegrityText = "No evidence journal open"; + State = IoTestSessionState.Idle; + StatusText = "Clean FAT retest ready. No evidence has been captured in the new session yet."; + RaiseProgress(); + return IoTestSessionActionResult.Success(StatusText); + } + public void Enqueue(Iec61850EventEntry entry) { if (entry == null || _disposed || State != IoTestSessionState.Running) @@ -309,10 +339,19 @@ private void ScheduleDrain() private void DrainPendingSnapshots() { + var stopwatch = Stopwatch.StartNew(); + var processed = 0; try { - while (_pendingSnapshots.TryDequeue(out var snapshot)) + while (processed < MaxSnapshotsPerDrain && + stopwatch.ElapsedMilliseconds < DrainBudgetMilliseconds && + _pendingSnapshots.TryDequeue(out var snapshot)) + { ProcessSnapshot(snapshot); + processed++; + if (State != IoTestSessionState.Running) + break; + } } finally { @@ -550,6 +589,28 @@ private void AppendRequired(IoTestJournalEntry entry) throw new InvalidOperationException(StatusText); } + private void AppendBatchRequired(IReadOnlyCollection entries) + { + try + { + var journal = _journal ?? throw new InvalidOperationException("No evidence journal is open for the active FAT session."); + var envelopes = journal.AppendBatch(entries); + if (envelopes.Count == 0) + throw new InvalidOperationException("Evidence journal startup batch produced no records."); + var envelope = envelopes[^1]; + EvidenceRecordCount = envelope.JournalSequence; + LastJournalHash = envelope.Hash; + JournalIntegrityText = $"Evidence journal open · {EvidenceRecordCount} record(s) · SHA-256 {ShortHash(LastJournalHash)}"; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ObjectDisposedException or InvalidOperationException) + { + State = IoTestSessionState.Faulted; + StatusText = $"Evidence journal write failed; FAT capture stopped: {ex.Message}"; + CleanupSessionResources(disposeJournal: true, keepActiveIed: true); + throw new InvalidOperationException(StatusText, ex); + } + } + private bool AppendOrFault(IoTestJournalEntry entry) { try diff --git a/tests/ARSAS.Tests/IoFatReportPreviewServiceTests.cs b/tests/ARSAS.Tests/IoFatReportPreviewServiceTests.cs index 9cd08fdfb..d50239453 100644 --- a/tests/ARSAS.Tests/IoFatReportPreviewServiceTests.cs +++ b/tests/ARSAS.Tests/IoFatReportPreviewServiceTests.cs @@ -160,16 +160,19 @@ public void PreviewKeepsProgressOnIedCardOnly() } [Fact] - public void IoFatPreparation_UsesCachedReconnect_AndRetriesReportPlanBeforePollingFallback() + public void IoFatPreparation_UsesCachedReconnect_AndReturnsOnFirstUsableLiveImage() { var source = File.ReadAllText(FindRepoFile("MainWindow.IoTesting.AutoConnect.cs")); Assert.Contains("Fast reconnect", source, StringComparison.Ordinal); Assert.Contains("ConnectUsingSavedModelAsync", source, StringComparison.Ordinal); Assert.Contains("SettleIoFatReportPriorityAsync", source, StringComparison.Ordinal); - Assert.Contains("rebuilding the report plan once", source, StringComparison.Ordinal); - Assert.Contains("configured RCB → temporary dynamic DataSet/URCB", source, StringComparison.Ordinal); + Assert.Contains("Waiting for first live FAT image", source, StringComparison.Ordinal); + Assert.Contains("TimeSpan.FromMilliseconds(2500)", source, StringComparison.Ordinal); Assert.Contains("IsReportSource", source, StringComparison.Ordinal); + Assert.DoesNotContain("rebuilding the report plan once", source, StringComparison.Ordinal); + Assert.DoesNotContain("TimeSpan.FromSeconds(8)", source, StringComparison.Ordinal); + Assert.DoesNotContain("TimeSpan.FromSeconds(10)", source, StringComparison.Ordinal); Assert.DoesNotContain("ExecuteControlAsync", source, StringComparison.Ordinal); } diff --git a/tests/ARSAS.Tests/IoTestEvidenceJournalTests.cs b/tests/ARSAS.Tests/IoTestEvidenceJournalTests.cs index 4f9f32e1c..3818c20da 100644 --- a/tests/ARSAS.Tests/IoTestEvidenceJournalTests.cs +++ b/tests/ARSAS.Tests/IoTestEvidenceJournalTests.cs @@ -29,6 +29,39 @@ public void Append_CreatesVerifiableHashChain() Assert.Equal(64, verification.LastHash.Length); } + [Fact] + public void AppendBatch_CreatesSameVerifiableOrderedHashChain() + { + var root = TempDirectory(); + var project = Project(); + var ied = project.Ieds[0]; + var sessionId = Guid.NewGuid(); + string path; + + using (var journal = IoTestEvidenceJournal.Create(root, project, ied, sessionId, DateTimeOffset.UtcNow)) + { + path = journal.FilePath; + var envelopes = journal.AppendBatch(new[] + { + Entry(project, ied, sessionId, "session_started"), + Entry(project, ied, sessionId, "baseline"), + Entry(project, ied, sessionId, "baseline") + }); + + Assert.Equal(3, envelopes.Count); + Assert.Equal(3, journal.RecordCount); + Assert.Equal(1, envelopes[0].JournalSequence); + Assert.Equal(2, envelopes[1].JournalSequence); + Assert.Equal(3, envelopes[2].JournalSequence); + Assert.Equal(envelopes[0].Hash, envelopes[1].PreviousHash); + Assert.Equal(envelopes[1].Hash, envelopes[2].PreviousHash); + } + + var verification = IoTestEvidenceJournal.Verify(path); + Assert.True(verification.IsValid, verification.Error); + Assert.Equal(3, verification.RecordCount); + } + [Fact] public void Verify_RejectsTamperedEvidenceLine() { diff --git a/tests/ARSAS.Tests/IoTestFatP0RegressionTests.cs b/tests/ARSAS.Tests/IoTestFatP0RegressionTests.cs new file mode 100644 index 000000000..791f498fe --- /dev/null +++ b/tests/ARSAS.Tests/IoTestFatP0RegressionTests.cs @@ -0,0 +1,82 @@ +namespace ARSAS.Tests; + +public sealed class IoTestFatP0RegressionTests +{ + [Fact] + public void FatWorkspace_UsesFastCommissioningPollingWithoutChangingNormalDefault() + { + var main = Read("MainWindow.IoTesting.cs"); + var planner = Read("Services/Iec61850ReportPlanner.cs"); + + Assert.Contains("private const int IoFatPollingIntervalMs = 250;", main, StringComparison.Ordinal); + Assert.Contains("_pollingIntervalBeforeIoFat", main, StringComparison.Ordinal); + Assert.Contains("PollingIntervalMs = Math.Min(PollingIntervalMs, IoFatPollingIntervalMs);", main, StringComparison.Ordinal); + Assert.Contains("FastCommissioningPollingThresholdMs = 500", planner, StringComparison.Ordinal); + Assert.Contains("!IsFastCommissioningPoint(point)", planner, StringComparison.Ordinal); + } + + [Fact] + public void FatConnect_ReadinessDoesNotBlockOnLegacyEightToEighteenSecondReportSettle() + { + var source = Read("MainWindow.IoTesting.AutoConnect.cs"); + + Assert.Contains("TimeSpan.FromMilliseconds(2500)", source, StringComparison.Ordinal); + Assert.Contains("Waiting for first live FAT image", source, StringComparison.Ordinal); + Assert.Contains("fast MMS verification", source, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("TimeSpan.FromSeconds(8)", source, StringComparison.Ordinal); + Assert.DoesNotContain("TimeSpan.FromSeconds(10)", source, StringComparison.Ordinal); + Assert.DoesNotContain("rebuilding the report plan once", source, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public void FatEvidenceDrain_YieldsUiAndStartupJournalUsesOneDurableBatch() + { + var controller = Read("Services/IoTesting/IoTestSessionController.cs"); + var journal = Read("Services/IoTesting/IoTestEvidenceJournal.cs"); + var main = Read("MainWindow.IoTesting.cs"); + + Assert.Contains("MaxSnapshotsPerDrain = 64", controller, StringComparison.Ordinal); + Assert.Contains("DrainBudgetMilliseconds = 4", controller, StringComparison.Ordinal); + Assert.Contains("stopwatch.ElapsedMilliseconds < DrainBudgetMilliseconds", controller, StringComparison.Ordinal); + Assert.Contains("AppendBatchRequired(startupEntries)", controller, StringComparison.Ordinal); + Assert.Contains("AppendBatch(IEnumerable entries)", journal, StringComparison.Ordinal); + Assert.Contains("FlushDurable();", journal, StringComparison.Ordinal); + Assert.Contains("DispatcherPriority.Background", main, StringComparison.Ordinal); + Assert.DoesNotContain("DispatcherPriority.DataBind", main, StringComparison.Ordinal); + } + + [Fact] + public void NewCleanFatSession_ArchivesOldJournalsAndClearsEveryActiveTimestampSource() + { + var service = Read("Services/IoTesting/IoFatCleanSessionService.cs"); + var ui = Read("IoListTestingWindow.SupplementalEvidence.cs"); + + Assert.Contains("SearchOption.TopDirectoryOnly", service, StringComparison.Ordinal); + Assert.Contains("IoTestEvidenceJournal.Verify(path)", service, StringComparison.Ordinal); + Assert.Contains("Path.Combine(evidenceDirectory, \"archive\")", service, StringComparison.Ordinal); + Assert.Contains("runtime.OnEvidence = null", service, StringComparison.Ordinal); + Assert.Contains("runtime.OffEvidence = null", service, StringComparison.Ordinal); + Assert.Contains("runtime.CurrentIedTimestamp = \"—\"", service, StringComparison.Ordinal); + Assert.Contains("point.TestEnabled = point.ImportReady", service, StringComparison.Ordinal); + Assert.Contains("storage.SaveNow()", service, StringComparison.Ordinal); + Assert.Contains("New Clean FAT", ui, StringComparison.Ordinal); + Assert.Contains("Session.ResetForCleanRetest()", ui, StringComparison.Ordinal); + } + + private static string Read(string relativePath) + => File.ReadAllText(FindRepoFile(relativePath)).Replace("\r\n", "\n", StringComparison.Ordinal); + + private static string FindRepoFile(string relativePath) + { + DirectoryInfo? directory = new(AppContext.BaseDirectory); + while (directory != null) + { + var candidate = Path.Combine(directory.FullName, relativePath); + if (File.Exists(candidate)) + return candidate; + directory = directory.Parent; + } + + throw new FileNotFoundException(relativePath); + } +} diff --git a/tests/ARSAS.Tests/IoTestingUiContractTests.cs b/tests/ARSAS.Tests/IoTestingUiContractTests.cs index 7e2d7619e..70146bb42 100644 --- a/tests/ARSAS.Tests/IoTestingUiContractTests.cs +++ b/tests/ARSAS.Tests/IoTestingUiContractTests.cs @@ -125,18 +125,20 @@ public void IoTestingWindow_UsesSelectedIedContextAndWorkspacePreviewToggle() } [Fact] - public void IoFatAutomaticPreparation_UsesSmartReportingWithoutProcessControls() + public void IoFatAutomaticPreparation_UsesFastCommissioningAcquisitionWithoutProcessControls() { var source = File.ReadAllText(FindRepoFile("MainWindow.IoTesting.AutoConnect.cs")); Assert.Contains("AllowDynamicDataSetWrites = true", source, StringComparison.Ordinal); Assert.Contains("ConnectAndConfigureDeviceAsync", source, StringComparison.Ordinal); Assert.Contains("StartDeviceMonitorAsync", source, StringComparison.Ordinal); - Assert.Contains("configured RCB", source, StringComparison.Ordinal); - Assert.Contains("dynamic DataSet/URCB", source, StringComparison.Ordinal); - Assert.Contains("bounded MMS verification/fallback", source, StringComparison.Ordinal); + Assert.Contains("deterministic fast MMS", source, StringComparison.OrdinalIgnoreCase); + Assert.Contains("first live FAT image", source, StringComparison.OrdinalIgnoreCase); Assert.Contains("SettleIoFatReportPriorityAsync", source, StringComparison.Ordinal); - Assert.Contains("rebuilding the report plan once", source, StringComparison.Ordinal); + Assert.Contains("TimeSpan.FromMilliseconds(2500)", source, StringComparison.Ordinal); + Assert.DoesNotContain("rebuilding the report plan once", source, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("TimeSpan.FromSeconds(8)", source, StringComparison.Ordinal); + Assert.DoesNotContain("TimeSpan.FromSeconds(10)", source, StringComparison.Ordinal); Assert.DoesNotContain("ExecuteControlAsync", source, StringComparison.Ordinal); Assert.DoesNotContain("InspectControlAsync", source, StringComparison.Ordinal); }