perf(deployment,template-engine): batched untracked staleness loads, staging-failure detach, lock-held Disabled re-check, targeted single-entity loads (DEP-4, DEP-5, DEP-6, TPL-4, WP6 task 6.6)

DEP-4: new ITemplateEngineRepository.GetInstancesByIdsUntrackedAsync (one
AsNoTracking split query per 500-id chunk). GetInstanceStalenessAsync preloads
each chunk into its FlattenSession; FlattenCoreAsync takes a preloaded
instance (consumed once) before falling back to the tracked per-instance load.
Deploy sessions never preload, so prepare keeps its tracked load.
  Throwaway harness, SQLite, 1,000 instances x 50 overrides:
  before: 5,000 reader commands, 51,000 tracked entities
  after:  10 reader commands, 0 tracked entities
  (wall time on in-process SQLite 2.7 s -> 2.3 s; the win on SQL Server is
  the 4,990 saved round-trips and the change tracker staying empty)

DEP-5: AddPendingDeploymentAsync supersedes prior rows with a set-based
delete (DeletePendingWhereAsync) instead of tracked key stubs, and a failed
staging save calls DetachPendingChanges under dbGate so it cannot poison the
next instance's staging save on the shared bulk context.
  Regression: prior row purged between supersede and save -> before:
  DbUpdateConcurrencyException; after: stages cleanly.

DEP-6: bulk prepare (reconcileGate != null) re-reads the instance state
untracked (new IDeploymentManagerRepository.GetInstanceStateAsync) once the
operation lock is held; Disabled -> reported in SkippedInstances with the
Disabled reason, never flattened/sent/re-enabled. Placed at the top of
PrepareUnderLockAsync so it is independent of WP7's lock-ordering change.

TPL-4: area delete uses the new shallow untracked GetInstancesBySiteIdShallowAsync;
SetAlarmOverride and Delete{Attribute,Alarm,Script} read the analysis closure
instead of the whole template table; MoveTemplate's collision check is the new
TemplateNameExistsInFolderAsync (one folder's names). SiteService already used
the include-free ISiteRepository read (unchanged).
This commit is contained in:
Joseph Doherty
2026-12-03 10:09:41 -05:00
parent 04e3969071
commit 59817f5017
19 changed files with 493 additions and 57 deletions
@@ -84,6 +84,28 @@ public class PendingDeploymentRepositoryTests : IDisposable
Assert.Equal(instanceId, current.InstanceId);
}
/// <summary>
/// DEP-5 (WP6 6.6): a prior pending row that the TTL purge (or reconciliation) deleted
/// after this context loaded it must not fail the superseding stage with a concurrency
/// error — the supersede is a set-based delete, not tracked key stubs.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AddPendingDeployment_PriorRowDeletedConcurrently_DoesNotThrow()
{
var instanceId = await SeedInstanceAsync("Inst-race");
await _repository.AddPendingDeploymentAsync(NewPending("depA", instanceId, "{}"));
await _repository.SaveChangesAsync(); // depA is now tracked by this context
await _repository.AddPendingDeploymentAsync(NewPending("depB", instanceId, "{}"));
// Between the supersede and the save, the purge actor removes depA on its own
// connection/context (ExecuteDelete of expired rows).
await _context.Database.ExecuteSqlRawAsync("DELETE FROM PendingDeployments WHERE DeploymentId = 'depA'");
await _repository.SaveChangesAsync();
Assert.NotNull(await _repository.GetPendingDeploymentByIdAsync("depB"));
}
/// <summary>Verifies that pending deployments for different instances coexist.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -0,0 +1,120 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Repositories;
/// <summary>
/// WP6 task 6.6 (DEP-4, DEP-6, TPL-4): the targeted, untracked repository reads that replace
/// whole-graph or per-row tracked loads, asserted against real SQL on SQLite.
/// </summary>
public class TargetedLoadRepositoryTests : IDisposable
{
private readonly ScadaBridgeDbContext _context;
private readonly TemplateEngineRepository _templates;
private readonly DeploymentManagerRepository _deployments;
/// <summary>Initializes the test class with an in-memory context and the repositories.</summary>
public TargetedLoadRepositoryTests()
{
_context = SqliteTestHelper.CreateInMemoryContext();
_templates = new TemplateEngineRepository(_context, new TemplateGraphWatermark());
_deployments = new DeploymentManagerRepository(_context);
}
/// <summary>Releases the resources held by this test class.</summary>
public void Dispose()
{
_context.Database.CloseConnection();
_context.Dispose();
}
private async Task<(int SiteId, int TemplateId, List<int> InstanceIds)> SeedAsync(int instances)
{
var site = new Site("Site", "S1");
var template = new Template("T");
_context.Sites.Add(site);
_context.Templates.Add(template);
await _context.SaveChangesAsync();
var ids = new List<int>();
for (var i = 0; i < instances; i++)
{
var instance = new Instance($"I{i:0000}") { SiteId = site.Id, TemplateId = template.Id };
instance.AttributeOverrides.Add(new InstanceAttributeOverride("A") { OverrideValue = i.ToString() });
_context.Instances.Add(instance);
}
await _context.SaveChangesAsync();
ids.AddRange(await _context.Instances.Select(i => i.Id).ToListAsync());
_context.ChangeTracker.Clear();
return (site.Id, template.Id, ids);
}
/// <summary>DEP-4: the batched loader returns every requested instance with its children, untracked, across chunks.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetInstancesByIdsUntracked_LoadsChildren_AcrossChunks_WithoutTracking()
{
var (_, _, ids) = await SeedAsync(620);
var loaded = await _templates.GetInstancesByIdsUntrackedAsync(ids.Append(ids[0]).Append(-1).ToList());
Assert.Equal(ids.Count, loaded.Count);
Assert.All(loaded, i => Assert.Single(i.AttributeOverrides));
Assert.Empty(_context.ChangeTracker.Entries());
}
/// <summary>TPL-4: the shallow site read carries no child collections and tracks nothing.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetInstancesBySiteIdShallow_IsUntracked_AndCarriesNoChildren()
{
var (siteId, _, ids) = await SeedAsync(3);
var shallow = await _templates.GetInstancesBySiteIdShallowAsync(siteId);
Assert.Equal(ids.Count, shallow.Count);
Assert.All(shallow, i => Assert.Empty(i.AttributeOverrides));
Assert.Empty(_context.ChangeTracker.Entries());
}
/// <summary>TPL-4: the folder-move collision check is a case-insensitive sibling-name query that excludes the moved template.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task TemplateNameExistsInFolder_IsCaseInsensitive_AndExcludesSelf()
{
var folder = new TemplateFolder("F");
_context.TemplateFolders.Add(folder);
await _context.SaveChangesAsync();
var inFolder = new Template("Pump") { FolderId = folder.Id };
var atRoot = new Template("Valve");
_context.Templates.AddRange(inFolder, atRoot);
await _context.SaveChangesAsync();
Assert.True(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "PUMP", atRoot.Id));
Assert.False(await _templates.TemplateNameExistsInFolderAsync(folder.Id, "Pump", inFolder.Id));
Assert.False(await _templates.TemplateNameExistsInFolderAsync(null, "Pump", atRoot.Id));
Assert.True(await _templates.TemplateNameExistsInFolderAsync(null, "valve", inFolder.Id));
}
/// <summary>DEP-6: the state read sees a state committed after this context loaded (and tracks) the instance.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetInstanceState_BypassesIdentityResolution()
{
var (_, _, ids) = await SeedAsync(1);
var tracked = await _context.Instances.SingleAsync(i => i.Id == ids[0]);
Assert.Equal(InstanceState.NotDeployed, tracked.State);
await _context.Database.ExecuteSqlRawAsync(
"UPDATE Instances SET State = {0} WHERE Id = {1}", InstanceState.Disabled.ToString(), ids[0]);
Assert.Equal(InstanceState.NotDeployed, (await _context.Instances.SingleAsync(i => i.Id == ids[0])).State);
Assert.Equal(InstanceState.Disabled, await _deployments.GetInstanceStateAsync(ids[0]));
Assert.Null(await _deployments.GetInstanceStateAsync(-1));
}
}
@@ -397,6 +397,62 @@ public class DeploySiteAsyncTests : TestKit
Arg.Is<DeploymentRecord>(r => r.InstanceId == 2 || r.InstanceId == 4), Arg.Any<CancellationToken>());
}
/// <summary>
/// DEP-6 (WP6 6.6): an instance Disabled by another request AFTER the batch loaded its
/// candidates is caught by the fresh, lock-held state read — skipped, never flattened,
/// sent or finalised as enabled.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DeploySiteAsync_InstanceDisabledAfterTheBatchStarted_IsSkippedNotReEnabled()
{
ArrangeInstances(3);
// The candidate list (and the tracked entity Prepare re-reads) still says NotDeployed,
// but the database already holds the operator's Disable.
_repo.GetInstanceStateAsync(Arg.Any<int>(), Arg.Any<CancellationToken>())
.Returns(ci => ci.ArgAt<int>(0) == 2 ? InstanceState.Disabled : InstanceState.NotDeployed);
var commActor = Sys.ActorOf(Props.Create(() =>
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
var result = await CreateService(commActor, maxParallelism: 2).DeploySiteAsync(SiteId, "admin");
Assert.True(result.IsSuccess);
Assert.Equal(2, result.Value.SuccessCount);
Assert.DoesNotContain(result.Value.InstanceResults, r => r.UniqueName == "Inst-02");
var skipped = Assert.Single(result.Value.SkippedInstances!);
Assert.Equal("Inst-02", skipped.UniqueName);
await _pipeline.DidNotReceive().FlattenAndValidateAsync(
2, Arg.Any<CancellationToken>(), Arg.Any<bool>(), Arg.Any<FlattenSession?>());
await _repo.DidNotReceive().AddDeploymentRecordAsync(
Arg.Is<DeploymentRecord>(r => r.InstanceId == 2), Arg.Any<CancellationToken>());
Assert.False(_lockManager.IsLocked("Inst-02"));
}
/// <summary>
/// DEP-5 (WP6 6.6): a failed staging save drops its pending changes from the shared
/// context, so the instances staged after it are not poisoned by the same failure.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DeploySiteAsync_FailedStagingWrite_DetachesItsPendingChanges()
{
ArrangeInstances(3);
_repo.AddPendingDeploymentAsync(
Arg.Is<PendingDeployment>(p => p.InstanceId == 1), Arg.Any<CancellationToken>())
.Returns(Task.FromException(new InvalidOperationException("staging save lost a race")));
var commActor = Sys.ActorOf(Props.Create(() =>
new ThrottledSiteActor(new ConcurrencyTracker(), slowInstanceName: null, slowDelay: TimeSpan.Zero)));
var result = await CreateService(commActor, maxParallelism: 1).DeploySiteAsync(SiteId, "admin");
Assert.True(result.IsSuccess);
Assert.Equal(2, result.Value.SuccessCount);
Assert.Equal("Inst-01", Assert.Single(result.Value.InstanceResults, r => !r.Success).UniqueName);
_repo.Received().DetachPendingChanges();
}
/// <summary>
/// Phase 1 is serial, so an unreachable site used to cost the batch one
/// full 30-second <c>QueryTimeout</c> PER INSTANCE before a single deploy was
@@ -1,3 +1,4 @@
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
@@ -35,6 +36,9 @@ public class DeploymentServiceStalenessTests
private readonly RevisionHashService _hasher = new();
private readonly DeploymentService _service;
/// <summary>DEP-4: the batched untracked instance loader the staleness read preloads from.</summary>
private readonly ITemplateEngineRepository _templateRepo = Substitute.For<ITemplateEngineRepository>();
/// <summary>The single session every flatten in a batch must share.</summary>
private readonly FlattenSession _session = new(new TemplateGraphWatermark());
@@ -61,7 +65,7 @@ public class DeploymentServiceStalenessTests
_service = new DeploymentService(
_repo,
siteRepo,
Substitute.For<ITemplateEngineRepository>(),
_templateRepo,
_pipeline,
new CommunicationService(
Options.Create(new CommunicationOptions()),
@@ -182,6 +186,31 @@ public class DeploymentServiceStalenessTests
await _pipeline.Received(1).ComputeRevisionHashAsync(3, _session, Arg.Any<CancellationToken>());
}
/// <summary>
/// DEP-4 (WP6 6.6): the deployed instances are bulk-loaded untracked (one call for the
/// batch) and handed to the shared session, instead of one tracked load per flatten.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetInstanceStalenessAsync_BulkPreloadsDeployedInstancesUntracked()
{
var config = ScalarConfig("5");
var hash = _hasher.ComputeHash(config);
ArrangeDeployedHashes((1, hash), (2, hash));
ArrangeFlatten(1, config, hash);
ArrangeFlatten(2, config, hash);
_templateRepo.GetInstancesByIdsUntrackedAsync(Arg.Any<IReadOnlyCollection<int>>(), Arg.Any<CancellationToken>())
.Returns(ci => (IReadOnlyList<Instance>)ci.ArgAt<IReadOnlyCollection<int>>(0)
.Select(id => new Instance($"I{id}") { Id = id }).ToList());
await _service.GetInstanceStalenessAsync([1, 2, 3]); // 3 is not deployed: never loaded
await _templateRepo.Received(1).GetInstancesByIdsUntrackedAsync(
Arg.Is<IReadOnlyCollection<int>>(ids => ids.Order().SequenceEqual(new[] { 1, 2 })),
Arg.Any<CancellationToken>());
Assert.NotNull(_session.TakePreloadedInstance(1));
}
/// <summary>Verifies that a matching hash is reported as not stale and no snapshot is read.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -97,6 +97,30 @@ public class FlattenSessionCacheTests
await _siteRepo.Received(1).GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any<CancellationToken>());
}
/// <summary>
/// DEP-4 (WP6 6.6): an instance bulk-preloaded into the session is flattened from the
/// session — no per-instance tracked repository load — and is consumed once taken.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task PreloadedInstances_AreFlattenedWithoutPerInstanceLoads()
{
const int instanceCount = 5;
ArrangeSharedChain(instanceCount);
var session = _sut.CreateSession();
session.PreloadInstances(Enumerable.Range(1, instanceCount)
.Select(i => new Instance($"Tank-{i:00}") { Id = i, TemplateId = TemplateId, SiteId = SiteId }));
for (var i = 1; i <= instanceCount; i++)
{
var result = await _sut.ComputeRevisionHashAsync(i, session, CancellationToken.None);
Assert.True(result.IsSuccess);
}
await _templateRepo.DidNotReceive().GetInstanceByIdAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
Assert.Null(session.TakePreloadedInstance(1));
}
/// <summary>Verifies that no shared session, every instance reloads the chain.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -36,6 +36,16 @@ internal static class AnalysisClosureMock
},
ct);
});
// TPL-4: the folder-move collision check is a (FolderId, Name) existence query now;
// answer it from the same seeded graph.
repoMock
.Setup(r => r.TemplateNameExistsInFolderAsync(
It.IsAny<int?>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Returns(async (int? folderId, string name, int excludeId, CancellationToken ct) =>
((await repoMock.Object.GetAllTemplatesForAnalysisAsync(ct)) ?? Array.Empty<Template>())
.Any(t => t.Id != excludeId && t.FolderId == folderId
&& string.Equals(t.Name, name, StringComparison.OrdinalIgnoreCase)));
}
/// <summary>
@@ -73,7 +73,7 @@ public class AreaServiceTests
{
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Area("Building A") { Id = 1, SiteId = 1 });
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<Instance>
{
new("Inst1") { Id = 1, AreaId = 1, SiteId = 1 }
@@ -94,7 +94,7 @@ public class AreaServiceTests
{
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Area("Parent") { Id = 1, SiteId = 1 });
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<Instance>());
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<Area>
@@ -116,7 +116,7 @@ public class AreaServiceTests
{
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Area("Empty") { Id = 1, SiteId = 1 });
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<Instance>());
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<Area> { new("Empty") { Id = 1, SiteId = 1 } });
@@ -312,7 +312,7 @@ public class AreaServiceTests
new("Mid") { Id = 2, SiteId = 1, ParentAreaId = 1 },
new("Leaf") { Id = 3, SiteId = 1, ParentAreaId = 2 }
});
_repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny<CancellationToken>()))
_repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny<CancellationToken>()))
.ReturnsAsync(new List<Instance>
{
new("DeepInstance") { Id = 10, AreaId = 3, SiteId = 1 }
@@ -18,6 +18,7 @@ public class InstanceServiceTests
/// <summary>Initializes the test with a mocked repository and audit service and the service under test.</summary>
public InstanceServiceTests()
{
_repoMock.ServeClosureFromFullGraph(); // TPL-4: SetAlarmOverride reads the analysis closure
_sut = new InstanceService(_repoMock.Object, _auditMock.Object);
}