perf(central-ui): save only changed overrides in one transaction; authorise once per action; split Test Run deadline (UI-6, UI-12, UI-13, WP6 task 6.8)

UI-6: Save overrides diffs the working values against the stored rows
(OverrideSaveDiff) and applies only the changed ones inside ONE
ExecuteInstanceAsync transaction; any row failure throws inside it so nothing
commits (no partial apply). InstanceService.SetAttributeOverrideAsync skips
the write and the UpdateOverride audit row when the value is unchanged.
  ~260 overrides, one edited: 260 transactions / ~1,300 round trips / 260
  audit rows -> 1 transaction / 1 SetAttributeOverride / 1 audit row.

UI-12: ParkedMessages bulk retry/discard authorise once per action (role +
site scope + site list) instead of per message (bunit: 5 messages -> 1 site
read, was 5; each also saved two forced session revalidations).
Deployments.LoadDataAsync resolves the scope once (new
SiteScopeService.ResolveScopeAsync) instead of IsSystemWide + PermittedSiteIds
(2 -> 1 revalidation per 500 ms reload). SecuredWrites loads connections with
one GetAllDataConnectionsAsync instead of one query per site.
Not changed: ConnectionHealthQueryService's per-tick site/connection reads.

UI-13 (decided: split deadline): the script deadline is armed when the worker
sends a new 'running' frame (RunInWorkerAsync's userCodeStarting hook, after
compile + trust check + gate); admission, process start-up and compile are
bounded by a separate StartupCeiling (30 s + the script budget) with its own
message.
  Test QueuedAndColdStartTime_IsNotChargedToTheScriptBudget (TimeoutSeconds=1,
  queued ~2 s behind four busy workers + a cold worker start):
  before: 'Script execution exceeded the 1-second sandbox timeout'
  after:  succeeds, returns 7.
This commit is contained in:
Joseph Doherty
2026-12-03 10:20:13 -05:00
parent 8966c54508
commit c5cd280739
14 changed files with 327 additions and 31 deletions
@@ -70,6 +70,46 @@ public class ParkedMessagesMutationRegressionTests : BunitContext
await system.Terminate();
}
/// <summary>
/// UI-12 (WP6 6.8): a bulk retry authorises once — one site-list read for the whole batch,
/// not one per message — and still relays every selected message.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task BulkRetry_AuthorisesOncePerAction_NotPerMessage()
{
using var system = ActorSystem.Create("parked-bulk-" + Guid.NewGuid().ToString("N"));
var dispatched = new ConcurrentQueue<SiteEnvelope>();
var comms = new CommunicationService(Options.Create(new CommunicationOptions()), NullLogger<CommunicationService>.Instance);
comms.SetCommunicationActor(system.ActorOf(Props.Create(() => new ReplyActor(dispatched, 5))));
Services.AddSingleton(comms);
var sites = Substitute.For<ISiteRepository>();
sites.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site> { new("Plant A", "plant-a") { Id = 42 } });
Services.AddSingleton(sites);
Services.AddSingleton<AuthenticationStateProvider>(new MutableAuth("42"));
Services.AddScoped<SiteScopeService>();
Services.AddAuthorizationCore();
Services.AddLogging();
var dialog = Substitute.For<IDialogService>();
dialog.ConfirmAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<string?>()).Returns(true);
Services.AddSingleton(dialog);
JSInterop.Mode = JSRuntimeMode.Loose;
var page = Render<ParkedMessages>();
await page.Find("select").ChangeAsync(new() { Value = "plant-a" });
page.WaitForAssertion(() => Assert.Equal(5, page.FindAll("tr.parked-row").Count));
await page.Find("input[aria-label='Select all']").ChangeAsync(new() { Value = true });
page.WaitForAssertion(() => Assert.Contains("Retry selected", page.Markup));
sites.ClearReceivedCalls();
await page.FindAll("button").Single(b => b.TextContent.Trim() == "Retry selected").ClickAsync(new());
page.WaitForAssertion(() => Assert.Equal(5, dispatched.Count(e => e.Message is ParkedMessageRetryRequest)));
// One read for the bulk authorisation (the page refresh afterwards adds none of its own here).
await sites.Received(1).GetAllSitesAsync(Arg.Any<CancellationToken>());
await system.Terminate();
}
private sealed class MutableAuth(string siteId) : AuthenticationStateProvider
{
/// <summary>Gets or sets the site identifier carried in the user's site-scope claim.</summary>
@@ -87,14 +127,15 @@ public class ParkedMessagesMutationRegressionTests : BunitContext
{
/// <summary>Initializes the actor with the queue that records relayed retry requests.</summary>
/// <param name="dispatched">The queue that receives each relayed retry envelope.</param>
public ReplyActor(ConcurrentQueue<SiteEnvelope> dispatched)
/// <param name="rows">How many parked rows the query reply carries.</param>
public ReplyActor(ConcurrentQueue<SiteEnvelope> dispatched, int rows = 1)
{
Receive<SiteEnvelope>(envelope =>
{
if (envelope.Message is ParkedMessageQueryRequest query)
Sender.Tell(new ParkedMessageQueryResponse(query.CorrelationId, envelope.SiteId,
new[] { new ParkedMessageEntry("parked-message-1", "ERP", "Send", "Offline", 2, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow) },
1, 1, 25, true, null, DateTimeOffset.UtcNow));
Enumerable.Range(1, rows).Select(i => new ParkedMessageEntry($"parked-message-{i}", "ERP", "Send", "Offline", 2, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow)).ToArray(),
rows, 1, 25, true, null, DateTimeOffset.UtcNow));
else if (envelope.Message is ParkedMessageRetryRequest retry)
{
dispatched.Enqueue(envelope);
@@ -0,0 +1,24 @@
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Deployment;
/// <summary>UI-6 (WP6 6.8): Save overrides sends only the values that changed.</summary>
public class OverrideSaveDiffTests
{
/// <summary>Only new or changed values are saved; an unchanged override (of ~260) is not.</summary>
[Fact]
public void Changed_ReturnsOnlyNewOrDifferentValues()
{
var existing = Enumerable.Range(0, 260).ToDictionary(
i => $"A{i}", i => new InstanceAttributeOverride($"A{i}") { OverrideValue = i.ToString() });
var working = existing.ToDictionary(kv => kv.Key, kv => kv.Value.OverrideValue);
working["A7"] = "changed";
working["New"] = "1";
var changed = OverrideSaveDiff.Changed(working, existing);
Assert.Equal(new[] { ("A7", (string?)"changed"), ("New", (string?)"1") },
changed.OrderBy(c => c.Name).ToArray());
}
}
@@ -29,15 +29,54 @@ public class SandboxWorkerIsolationTests
{
await allEntered.Task.WaitAsync(TimeSpan.FromSeconds(8));
var fifthStarted = false;
// UI-13: the queue wait is charged to the start-up ceiling; shrink it so the
// queued fifth run still gives up quickly here.
SandboxWorkerProtocol.StartupCeiling = TimeSpan.Zero;
var fifth = await SandboxWorkerProtocol.RunCoreAsync(new SandboxRunRequest("return 1;", null, 1),
services, catalog, CancellationToken.None, _ => fifthStarted = true);
Assert.Equal(SandboxErrorKind.Timeout, fifth.ErrorKind);
Assert.False(fifthStarted);
}
finally { release.TrySetResult(new ExternalCallResult(true, "null", null)); }
finally
{
SandboxWorkerProtocol.StartupCeiling = TimeSpan.FromSeconds(30);
release.TrySetResult(new ExternalCallResult(true, "null", null));
}
foreach (var result in await Task.WhenAll(workers)) Assert.True(result.Success, result.Error);
}
/// <summary>
/// UI-13 (WP6 6.8): the script deadline starts when the worker reports user code is about to
/// run. A 1-second run queued behind four busy Test Runs for ~2 s (plus a cold worker start)
/// used to report "exceeded the 1-second sandbox timeout"; it now succeeds.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task QueuedAndColdStartTime_IsNotChargedToTheScriptBudget()
{
var allEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource<ExternalCallResult>(TaskCreationOptions.RunContinuationsAsynchronously);
var count = 0;
var external = Substitute.For<IExternalSystemClient>();
external.CallAsync("probe", "blocked", Arg.Any<IReadOnlyDictionary<string, object?>?>(), Arg.Any<CancellationToken>())
.Returns(_ => { if (Interlocked.Increment(ref count) == 4) allEntered.TrySetResult(); return release.Task; });
using var services = new ServiceCollection().AddSingleton(external).BuildServiceProvider();
var catalog = Substitute.For<ISharedScriptCatalog>();
var busy = Enumerable.Range(0, 4).Select(_ => SandboxWorkerProtocol.RunAsync(new SandboxRunRequest(
"await ExternalSystem.Call(\"probe\", \"blocked\"); return 42;", null, 10), services, catalog, CancellationToken.None)).ToArray();
await allEntered.Task.WaitAsync(TimeSpan.FromSeconds(10));
var queued = SandboxWorkerProtocol.RunAsync(new SandboxRunRequest("return 7;", null, 1),
services, catalog, CancellationToken.None);
await Task.Delay(TimeSpan.FromSeconds(2)); // queued longer than its whole 1 s script budget
release.TrySetResult(new ExternalCallResult(true, "null", null));
var result = await queued.WaitAsync(TimeSpan.FromSeconds(30));
Assert.True(result.Success, result.Error);
Assert.Equal("7", result.ReturnValueJson);
foreach (var r in await Task.WhenAll(busy)) Assert.True(r.Success, r.Error);
}
/// <summary>Verifies that an uncooperative broker still has its child killed at the deadline and keeps the lifetime until the broker completes.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -109,6 +109,32 @@ public class InstanceServiceTests
Assert.Contains("does not exist", result.Error);
}
/// <summary>
/// UI-6 (WP6 6.8): re-saving an override with its current value writes nothing and adds no
/// UpdateOverride audit row.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task SetAttributeOverride_UnchangedValue_SkipsTheWriteAndTheAuditRow()
{
var instance = new Instance("Inst1") { Id = 1, TemplateId = 1 };
var existing = new InstanceAttributeOverride("Threshold") { Id = 5, InstanceId = 1, OverrideValue = "99" };
_repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny<CancellationToken>())).ReturnsAsync(instance);
_repoMock.Setup(r => r.GetAttributesByTemplateIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<TemplateAttribute> { new("Threshold") { IsLocked = false } });
_repoMock.Setup(r => r.GetOverridesByInstanceIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<InstanceAttributeOverride> { existing });
var result = await _sut.SetAttributeOverrideAsync(1, "Threshold", "99", "admin");
Assert.True(result.IsSuccess);
Assert.Same(existing, result.Value);
_repoMock.Verify(r => r.UpdateInstanceAttributeOverrideAsync(It.IsAny<InstanceAttributeOverride>(), It.IsAny<CancellationToken>()), Times.Never);
_repoMock.Verify(r => r.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
_auditMock.Verify(a => a.LogAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object?>(), It.IsAny<CancellationToken>()), Times.Never);
}
/// <summary>Verifies that overriding an unlocked attribute returns success.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]