diff --git a/docs/requirements/Component-DeploymentManager.md b/docs/requirements/Component-DeploymentManager.md
index 228d2068..276a9380 100644
--- a/docs/requirements/Component-DeploymentManager.md
+++ b/docs/requirements/Component-DeploymentManager.md
@@ -180,6 +180,14 @@ site-wide push would silently restart every piece of equipment an operator had
deliberately stopped; they are reported in the summary's `SkippedInstances` with
the reason "Disabled — bulk deploy preserves disabled state; deploy individually
to re-enable", and the single-instance deploy remains the explicit re-enable path.
+The skip is re-checked once each instance's operation lock is held (DEP-6, 2026-12-03):
+the candidate list is read once when the batch starts, so an instance an operator
+disables while the batch is still preparing earlier instances is caught by a fresh,
+untracked state read (`IDeploymentManagerRepository.GetInstanceStateAsync`) and reported
+as skipped with the same reason, instead of being deployed and re-enabled. A failed
+staging write detaches its pending changes so it cannot poison the staging writes of
+the instances after it on the shared unit of work (DEP-5), and the supersede of a prior
+`PendingDeployment` row is a set-based delete rather than tracked key stubs.
**Up-to-date instances are skipped too (unless `force`), at batch cost.** The
pre-filter reads the deployed-hash projection (`GetDeployedRevisionHashesAsync`) and
diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs
index 24ef39bc..ff2455a2 100644
--- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs
@@ -413,6 +413,16 @@ public interface IDeploymentManagerRepository
/// A cancellation token that can be used to cancel the operation.
/// The instance, or null if not found.
Task GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
+
+ ///
+ /// DEP-6: reads an instance's CURRENT lifecycle state straight from the database,
+ /// untracked — bypassing EF identity resolution, which would otherwise answer with the
+ /// state of an entity this unit of work loaded earlier.
+ ///
+ /// The instance id.
+ /// Cancellation token.
+ /// The state, or when the instance does not exist.
+ Task GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default);
///
/// Gets an instance by unique name.
///
diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs
index c78677e6..77e7c495 100644
--- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/ITemplateEngineRepository.cs
@@ -286,6 +286,18 @@ public interface ITemplateEngineRepository
/// Cancellation token.
/// A task that resolves to the matching instance, or if not found.
Task GetInstanceByIdAsync(int id, CancellationToken cancellationToken = default);
+
+ ///
+ /// DEP-4: loads several instances with the same child collections as
+ /// , untracked, in one split query per chunk of
+ /// ids — for read-only paths (fleet staleness) that must not fill the scoped change
+ /// tracker with every deployed instance's overrides and bindings.
+ ///
+ /// The instance ids; missing ids are absent from the result.
+ /// Cancellation token.
+ /// The instances found.
+ Task> GetInstancesByIdsUntrackedAsync(
+ IReadOnlyCollection ids, CancellationToken cancellationToken = default);
/// Retrieves all instances.
/// Cancellation token.
/// A task that resolves to a read-only list of all instances.
@@ -301,6 +313,30 @@ public interface ITemplateEngineRepository
/// A task that resolves to a read-only list of instances for the specified site.
Task> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default);
+ ///
+ /// TPL-4: a site's instances WITHOUT their child collections, untracked — for checks
+ /// that only need identity, name and area (area/site delete guards), which used to load
+ /// and track every instance's overrides and bindings.
+ ///
+ /// The site ID.
+ /// Cancellation token.
+ /// The site's instances, shallow and untracked.
+ Task> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default);
+
+ ///
+ /// TPL-4: whether a template other than named
+ /// (case-insensitively) already sits in
+ /// ( = the root) — the folder-move collision check, which used to load
+ /// the whole template table.
+ ///
+ /// The destination folder, or null for the root.
+ /// The template name.
+ /// The template being moved.
+ /// Cancellation token.
+ /// when a sibling with that name exists.
+ Task TemplateNameExistsInFolderAsync(
+ int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default);
+
/// Reads one bounded, untracked page of topology instance rows for a site/area.
/// The site ID.
/// The area ID to filter by, or null for every area.
diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs
index 435252ec..ac05b215 100644
--- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs
@@ -407,21 +407,20 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
// Supersession: a newer deploy for the same instance replaces any prior pending
// row. Safe because the per-instance operation lock serializes same-instance
- // deploys. SaveChanges is deferred to the caller, matching the other Add methods.
+ // deploys. The new row's SaveChanges is deferred to the caller, matching the other
+ // Add methods.
//
- // Only the prior rows' KEYS are read: each row carries the whole flattened
- // ConfigurationJson (tens of KB), and materialising it just to delete it was the
- // dominant cost of the supersede. The delete itself stays a tracked Remove (not
- // ExecuteDelete) so it still commits atomically with the new row in the caller's
- // SaveChanges.
- var priorIds = await _dbContext.Set()
- .Where(p => p.InstanceId == pending.InstanceId)
- .Select(p => p.Id)
- .ToListAsync(cancellationToken);
- foreach (var id in priorIds)
- {
- RemovePendingByKey(id);
- }
+ // DEP-5: the prior rows are removed with a set-based ExecuteDelete keyed on the
+ // instance — never materialised (each carries the whole flattened ConfigurationJson)
+ // and never tracked. The old tracked key-only stubs made the caller's SaveChanges
+ // throw DbUpdateConcurrencyException whenever the TTL purge (or reconciliation)
+ // removed one of those rows first, and the failed stub then stayed tracked and
+ // poisoned every later staging save on the shared bulk-deploy context. The trade
+ // is that the supersede commits on its own, just before the insert: a failed
+ // insert leaves the instance with no pending row, which is what the superseded
+ // deploy was about to become anyway.
+ var instanceId = pending.InstanceId;
+ await DeletePendingWhereAsync(p => p.InstanceId == instanceId, cancellationToken);
await _dbContext.Set().AddAsync(pending, cancellationToken);
}
@@ -505,29 +504,6 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
return rows.Count;
}
- ///
- /// Marks the pending row with primary key for deletion on the next
- /// SaveChanges without loading it: an already-tracked instance is removed in place,
- /// otherwise a key-only stub is attached and removed (EF deletes by key).
- ///
- /// Primary key of the pending row.
- private void RemovePendingByKey(int id)
- {
- var set = _dbContext.Set();
- var tracked = set.Local.FirstOrDefault(p => p.Id == id);
- if (tracked != null)
- {
- set.Remove(tracked);
- return;
- }
-
- var stub = new PendingDeployment(
- string.Empty, 0, string.Empty, string.Empty, string.Empty,
- default, default) { Id = id };
- set.Attach(stub);
- set.Remove(stub);
- }
-
///
public async Task PurgeTerminalDeploymentRecordsAsync(
DateTimeOffset cutoffUtc,
@@ -777,6 +753,17 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
// --- Instance lookups for deployment pipeline ---
+ ///
+ public async Task GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default)
+ {
+ // A scalar projection is never tracked and never identity-resolved, so this sees a
+ // state committed by another request after this context loaded the instance.
+ return await _dbContext.Set()
+ .Where(i => i.Id == instanceId)
+ .Select(i => (InstanceState?)i.State)
+ .FirstOrDefaultAsync(cancellationToken);
+ }
+
///
public async Task GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default)
{
diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs
index 5bef7c5a..8658168d 100644
--- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/TemplateEngineRepository.cs
@@ -501,6 +501,29 @@ public class TemplateEngineRepository : ITemplateEngineRepository
.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
}
+ ///
+ public async Task> GetInstancesByIdsUntrackedAsync(
+ IReadOnlyCollection ids, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(ids);
+ var result = new List(ids.Count);
+ // Chunked so the IN list stays well under SQL Server's 2,100-parameter limit.
+ foreach (var chunk in ids.Distinct().Chunk(500))
+ {
+ result.AddRange(await _context.Instances
+ .AsNoTracking()
+ .Where(i => chunk.Contains(i.Id))
+ .Include(i => i.AttributeOverrides)
+ .Include(i => i.AlarmOverrides)
+ .Include(i => i.ConnectionBindings)
+ .Include(i => i.NativeAlarmSourceOverrides)
+ .AsSplitQuery()
+ .ToListAsync(cancellationToken));
+ }
+
+ return result;
+ }
+
///
public async Task> GetAllInstancesAsync(CancellationToken cancellationToken = default)
{
@@ -521,6 +544,30 @@ public class TemplateEngineRepository : ITemplateEngineRepository
.ToListAsync(cancellationToken);
}
+ ///
+ public async Task> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default)
+ {
+ return await _context.Instances
+ .AsNoTracking()
+ .Where(i => i.SiteId == siteId)
+ .ToListAsync(cancellationToken);
+ }
+
+ ///
+ public async Task TemplateNameExistsInFolderAsync(
+ int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default)
+ {
+ ArgumentNullException.ThrowIfNull(name);
+ // Only the destination folder's names are read (one narrow projection), then compared
+ // case-insensitively in memory — independent of the database collation.
+ var siblingNames = await _context.Templates
+ .AsNoTracking()
+ .Where(t => t.FolderId == folderId && t.Id != excludeTemplateId)
+ .Select(t => t.Name)
+ .ToListAsync(cancellationToken);
+ return siblingNames.Any(n => string.Equals(n, name, StringComparison.OrdinalIgnoreCase));
+ }
+
///
public async Task> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default)
{
diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs
index 968ac9e6..1b201f74 100644
--- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs
@@ -63,6 +63,9 @@ public class DeploymentService
/// Reason reported on every a bulk site
/// deploy produces for a instance.
///
+ /// DEP-4: instances bulk-loaded (untracked) per chunk by the fleet staleness read.
+ private const int StalenessPreloadChunk = 500;
+
internal const string DisabledSkipReason =
"Disabled — bulk deploy preserves disabled state; deploy individually to re-enable";
@@ -320,6 +323,20 @@ public class DeploymentService
{
var instanceId = instance.Id;
+ // DEP-6: a bulk deploy loaded its candidates once, up front, and EF identity
+ // resolution hands Prepare that same tracked entity — so a Disable committed after
+ // the batch started was invisible here, and the batch would deploy (and finalise
+ // as enabled) an instance the operator had just stopped. Disable/enable take this
+ // operation lock too, so a fresh, untracked read of the state taken while holding
+ // it is authoritative. Single-instance deploy (no reconcileGate) keeps
+ // deploy-and-enable as its explicit operator action.
+ if (reconcileGate is not null
+ && await _repository.GetInstanceStateAsync(instanceId, cancellationToken) == InstanceState.Disabled)
+ {
+ lockHandle.Dispose();
+ return PreparedDeployment.Skipped(DisabledSkipReason);
+ }
+
// Generate unique deployment ID
var deploymentId = Guid.NewGuid().ToString("N");
@@ -493,6 +510,15 @@ public class DeploymentService
{
command = await StagePendingDeploymentAsync(prepared, user, cancellationToken);
}
+ catch
+ {
+ // DEP-5: a failed staging save leaves its Added row tracked on the scoped
+ // context; in a bulk deploy every later instance's staging save would retry
+ // it and fail the same way. Drop it while still holding dbGate (the only
+ // repository writer in phase 2), like MarkDeploymentFailedAsync does (P7-5).
+ _repository.DetachPendingChanges();
+ throw;
+ }
finally
{
dbGate?.Release();
@@ -823,8 +849,19 @@ public class DeploymentService
string ConfigJson,
string SiteIdentifier,
IDisposable? LockHandle,
- Result? EarlyResult)
+ Result? EarlyResult,
+ string? SkipReason = null)
{
+ ///
+ /// DEP-6: a bulk-deploy instance found Disabled once its operation lock was held —
+ /// reported as a skipped row (never sent, never re-enabled), not as a failure.
+ ///
+ /// The skip reason shown in the bulk summary.
+ /// A prepared deployment holding no lock, with set.
+ public static PreparedDeployment Skipped(string reason) =>
+ new(null!, string.Empty, null!, string.Empty, string.Empty, string.Empty, null,
+ Result.Failure(reason), reason);
+
/// Builds a prepare-phase-resolved deployment carrying the given result and holding no lock.
/// The result to hand back to the caller.
/// A prepared deployment whose is set.
@@ -1067,6 +1104,13 @@ public class DeploymentService
continue;
}
+ if (step.SkipReason is { } skipReason)
+ {
+ skipped.Add(new SkippedInstanceResult(instance.Id, instance.UniqueName, skipReason));
+ disabledCount++;
+ continue;
+ }
+
if (step.EarlyResult is { } early)
{
results.Add(ToInstanceResult(instance.Id, instance.UniqueName, early));
@@ -2067,13 +2111,25 @@ public class DeploymentService
// resolved together after the loop with ONE untracked snapshot read.
var mismatched = new Dictionary();
- foreach (var instanceId in instanceIds.Distinct())
+ // DEP-4: load the deployed instances in untracked chunks (one split query each)
+ // instead of a tracked four-Include load per instance — the evaluator's scoped
+ // context used to end up tracking every deployed instance, override and binding.
+ var toEvaluate = instanceIds.Distinct().Where(deployedHashes.ContainsKey).ToList();
+ foreach (var instanceId in toEvaluate)
{
cancellationToken.ThrowIfCancellationRequested();
if (!deployedHashes.TryGetValue(instanceId, out var deployedHash))
continue;
+ if ((evaluated % StalenessPreloadChunk) == 0)
+ {
+ var chunk = toEvaluate.Skip(evaluated).Take(StalenessPreloadChunk).ToList();
+ session.PreloadInstances(
+ await _templateRepository.GetInstancesByIdsUntrackedAsync(chunk, cancellationToken)
+ ?? (IReadOnlyList)Array.Empty());
+ }
+
evaluated++;
// Read-only path: hash only — no validation (its result was always discarded
diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs
index 3a7656ad..4fcc8096 100644
--- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlattenSession.cs
@@ -1,3 +1,4 @@
+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.Interfaces.Services;
@@ -48,6 +49,7 @@ public sealed class FlattenSession
private readonly Dictionary _chains = new();
private readonly Dictionary Compositions)> _compositions = new();
private readonly Dictionary> _dataConnections = new();
+ private readonly Dictionary _preloadedInstances = new();
private IReadOnlyList? _sharedScripts;
private IReadOnlyDictionary? _schemaLibrary;
@@ -78,6 +80,27 @@ public sealed class FlattenSession
/// Number of per-site data-connection queries that missed the memo.
public int DataConnectionLoads { get; private set; }
+ ///
+ /// DEP-4: hands the session instances already loaded in bulk (untracked) so the flatten
+ /// does not load each one again. Only read-only callers (fleet staleness) preload; a
+ /// deploy's session never does, so prepare keeps its tracked load.
+ ///
+ /// The preloaded instances.
+ public void PreloadInstances(IEnumerable instances)
+ {
+ foreach (var instance in instances)
+ _preloadedInstances[instance.Id] = instance;
+ }
+
+ ///
+ /// Takes (and forgets) a preloaded instance, so a chunked caller never holds more than
+ /// one chunk of the fleet in memory.
+ ///
+ /// The instance id.
+ /// The preloaded instance, or when none was preloaded.
+ public Instance? TakePreloadedInstance(int instanceId) =>
+ _preloadedInstances.Remove(instanceId, out var instance) ? instance : null;
+
///
/// Every template id this session resolved — the union of all inheritance and
/// composed chains it walked. The staleness fast path records the watermark
diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs
index c609abc9..03049e36 100644
--- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/FlatteningPipeline.cs
@@ -190,8 +190,9 @@ public class FlatteningPipeline : IFlatteningPipeline
private async Task DataConnections)>>
FlattenCoreAsync(int instanceId, FlattenSession session, CancellationToken cancellationToken)
{
- // Load instance with full graph
- var instance = await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken);
+ // Load instance with full graph (DEP-4: a read-only caller may have bulk-preloaded it)
+ var instance = session.TakePreloadedInstance(instanceId)
+ ?? await _templateRepo.GetInstanceByIdAsync(instanceId, cancellationToken);
if (instance == null)
return Result<(FlattenedConfiguration, IReadOnlyDictionary)>.Failure(
$"Instance with ID {instanceId} not found.");
diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs
index 4e317c95..d3d3e1b0 100644
--- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/AreaService.cs
@@ -188,7 +188,8 @@ public class AreaService
return Result.Failure($"Area with ID {areaId} not found.");
// Check for instances assigned to this area
- var allInstances = await _repository.GetInstancesBySiteIdAsync(area.SiteId, cancellationToken);
+ // TPL-4: shallow + untracked — only AreaId/UniqueName are read.
+ var allInstances = await _repository.GetInstancesBySiteIdShallowAsync(area.SiteId, cancellationToken);
var allAreas = await _repository.GetAreasBySiteIdAsync(area.SiteId, cancellationToken);
// Collect this area and all descendant area IDs
diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs
index 39e5be85..43db0eb0 100644
--- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs
@@ -247,7 +247,9 @@ public class InstanceService
// rule for a composed alarm. Mirrors SetAttributeOverrideAsync.
// The resolver reads member names and lock flags only, so the no-tracking,
// script-body-free analysis projection suffices (review 2026-10-21 04/P6, 08/P1).
- var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
+ // TPL-4: the template's analysis closure (chain + compositions) is all the resolver
+ // walks — not the whole template table.
+ var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(instance.TemplateId, cancellationToken);
var resolvedAlarm = TemplateResolver
.ResolveAllMembers(instance.TemplateId, allTemplates)
.FirstOrDefault(m => m.MemberType == "Alarm" && m.CanonicalName == alarmCanonicalName);
diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs
index ac79c963..d37946fb 100644
--- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/TemplateService.cs
@@ -228,12 +228,9 @@ public class TemplateService
// only invariant the move can break is two templates sharing a
// (FolderId, Name) at the destination, which the design's
// naming-collisions-are-design-time-errors rule forbids.
- var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
- var collision = allTemplates.FirstOrDefault(t =>
- t.Id != templateId &&
- t.FolderId == newFolderId &&
- string.Equals(t.Name, template.Name, StringComparison.OrdinalIgnoreCase));
- if (collision != null)
+ // TPL-4: a (FolderId, Name) existence query, not a load of every template.
+ if (await _repository.TemplateNameExistsInFolderAsync(
+ newFolderId, template.Name, templateId, cancellationToken))
{
var location = newFolderId.HasValue ? "the target folder" : "the root";
return Result.Failure(
@@ -449,7 +446,9 @@ public class TemplateService
var template = await _repository.GetTemplateByIdAsync(attribute.TemplateId, cancellationToken);
if (template?.ParentTemplateId != null)
{
- var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
+ // TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
+ var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
+ template.ParentTemplateId.Value, cancellationToken);
var parentMember = TemplateResolver.FindMemberByCanonicalName(
attribute.Name, template.ParentTemplateId.Value, allTemplates);
if (parentMember != null)
@@ -676,7 +675,9 @@ public class TemplateService
var template = await _repository.GetTemplateByIdAsync(alarm.TemplateId, cancellationToken);
if (template?.ParentTemplateId != null)
{
- var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
+ // TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
+ var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
+ template.ParentTemplateId.Value, cancellationToken);
var parentMember = TemplateResolver.FindMemberByCanonicalName(
alarm.Name, template.ParentTemplateId.Value, allTemplates);
if (parentMember != null)
@@ -853,7 +854,9 @@ public class TemplateService
var template = await _repository.GetTemplateByIdAsync(script.TemplateId, cancellationToken);
if (template?.ParentTemplateId != null)
{
- var allTemplates = await _repository.GetAllTemplatesForAnalysisAsync(cancellationToken);
+ // TPL-4: the parent's analysis closure is all FindMemberByCanonicalName walks.
+ var allTemplates = await _repository.GetTemplateAnalysisClosureAsync(
+ template.ParentTemplateId.Value, cancellationToken);
var parentMember = TemplateResolver.FindMemberByCanonicalName(
script.Name, template.ParentTemplateId.Value, allTemplates);
if (parentMember != null)
diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/PendingDeploymentRepositoryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/PendingDeploymentRepositoryTests.cs
index 24774dbc..4fc35bc7 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/PendingDeploymentRepositoryTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/PendingDeploymentRepositoryTests.cs
@@ -84,6 +84,28 @@ public class PendingDeploymentRepositoryTests : IDisposable
Assert.Equal(instanceId, current.InstanceId);
}
+ ///
+ /// 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.
+ ///
+ /// A task that represents the asynchronous operation.
+ [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"));
+ }
+
/// Verifies that pending deployments for different instances coexist.
/// A task that represents the asynchronous operation.
[Fact]
diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/TargetedLoadRepositoryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/TargetedLoadRepositoryTests.cs
new file mode 100644
index 00000000..d1b25c49
--- /dev/null
+++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/Repositories/TargetedLoadRepositoryTests.cs
@@ -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;
+
+///
+/// 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.
+///
+public class TargetedLoadRepositoryTests : IDisposable
+{
+ private readonly ScadaBridgeDbContext _context;
+ private readonly TemplateEngineRepository _templates;
+ private readonly DeploymentManagerRepository _deployments;
+
+ /// Initializes the test class with an in-memory context and the repositories.
+ public TargetedLoadRepositoryTests()
+ {
+ _context = SqliteTestHelper.CreateInMemoryContext();
+ _templates = new TemplateEngineRepository(_context, new TemplateGraphWatermark());
+ _deployments = new DeploymentManagerRepository(_context);
+ }
+
+ /// Releases the resources held by this test class.
+ public void Dispose()
+ {
+ _context.Database.CloseConnection();
+ _context.Dispose();
+ }
+
+ private async Task<(int SiteId, int TemplateId, List 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();
+ 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);
+ }
+
+ /// DEP-4: the batched loader returns every requested instance with its children, untracked, across chunks.
+ /// A task that represents the asynchronous operation.
+ [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());
+ }
+
+ /// TPL-4: the shallow site read carries no child collections and tracks nothing.
+ /// A task that represents the asynchronous operation.
+ [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());
+ }
+
+ /// TPL-4: the folder-move collision check is a case-insensitive sibling-name query that excludes the moved template.
+ /// A task that represents the asynchronous operation.
+ [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));
+ }
+
+ /// DEP-6: the state read sees a state committed after this context loaded (and tracks) the instance.
+ /// A task that represents the asynchronous operation.
+ [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));
+ }
+}
diff --git a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploySiteAsyncTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploySiteAsyncTests.cs
index 463c98a1..257d2bb5 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploySiteAsyncTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploySiteAsyncTests.cs
@@ -397,6 +397,62 @@ public class DeploySiteAsyncTests : TestKit
Arg.Is(r => r.InstanceId == 2 || r.InstanceId == 4), Arg.Any());
}
+ ///
+ /// 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.
+ ///
+ /// A task that represents the asynchronous operation.
+ [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(), Arg.Any())
+ .Returns(ci => ci.ArgAt(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(), Arg.Any(), Arg.Any());
+ await _repo.DidNotReceive().AddDeploymentRecordAsync(
+ Arg.Is(r => r.InstanceId == 2), Arg.Any());
+ Assert.False(_lockManager.IsLocked("Inst-02"));
+ }
+
+ ///
+ /// 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.
+ ///
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task DeploySiteAsync_FailedStagingWrite_DetachesItsPendingChanges()
+ {
+ ArrangeInstances(3);
+ _repo.AddPendingDeploymentAsync(
+ Arg.Is(p => p.InstanceId == 1), Arg.Any())
+ .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();
+ }
+
///
/// Phase 1 is serial, so an unreachable site used to cost the batch one
/// full 30-second QueryTimeout PER INSTANCE before a single deploy was
diff --git a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceStalenessTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceStalenessTests.cs
index 45c59a63..f552b277 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceStalenessTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceStalenessTests.cs
@@ -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;
+ /// DEP-4: the batched untracked instance loader the staleness read preloads from.
+ private readonly ITemplateEngineRepository _templateRepo = Substitute.For();
+
/// The single session every flatten in a batch must share.
private readonly FlattenSession _session = new(new TemplateGraphWatermark());
@@ -61,7 +65,7 @@ public class DeploymentServiceStalenessTests
_service = new DeploymentService(
_repo,
siteRepo,
- Substitute.For(),
+ _templateRepo,
_pipeline,
new CommunicationService(
Options.Create(new CommunicationOptions()),
@@ -182,6 +186,31 @@ public class DeploymentServiceStalenessTests
await _pipeline.Received(1).ComputeRevisionHashAsync(3, _session, Arg.Any());
}
+ ///
+ /// 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.
+ ///
+ /// A task that represents the asynchronous operation.
+ [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>(), Arg.Any())
+ .Returns(ci => (IReadOnlyList)ci.ArgAt>(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>(ids => ids.Order().SequenceEqual(new[] { 1, 2 })),
+ Arg.Any());
+ Assert.NotNull(_session.TakePreloadedInstance(1));
+ }
+
/// Verifies that a matching hash is reported as not stale and no snapshot is read.
/// A task that represents the asynchronous operation.
[Fact]
diff --git a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/FlattenSessionCacheTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/FlattenSessionCacheTests.cs
index 1fc2ffce..6c3bdf5e 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/FlattenSessionCacheTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/FlattenSessionCacheTests.cs
@@ -97,6 +97,30 @@ public class FlattenSessionCacheTests
await _siteRepo.Received(1).GetDataConnectionsBySiteIdAsync(SiteId, Arg.Any());
}
+ ///
+ /// 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.
+ ///
+ /// A task that represents the asynchronous operation.
+ [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(), Arg.Any());
+ Assert.Null(session.TakePreloadedInstance(1));
+ }
+
/// Verifies that no shared session, every instance reloads the chain.
/// A task that represents the asynchronous operation.
[Fact]
diff --git a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/AnalysisClosureMock.cs b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/AnalysisClosureMock.cs
index 15649487..58775307 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/AnalysisClosureMock.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/AnalysisClosureMock.cs
@@ -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(), It.IsAny(), It.IsAny(), It.IsAny()))
+ .Returns(async (int? folderId, string name, int excludeId, CancellationToken ct) =>
+ ((await repoMock.Object.GetAllTemplatesForAnalysisAsync(ct)) ?? Array.Empty())
+ .Any(t => t.Id != excludeId && t.FolderId == folderId
+ && string.Equals(t.Name, name, StringComparison.OrdinalIgnoreCase)));
}
///
diff --git a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/AreaServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/AreaServiceTests.cs
index f14d7145..56e3921e 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/AreaServiceTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/AreaServiceTests.cs
@@ -73,7 +73,7 @@ public class AreaServiceTests
{
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny()))
.ReturnsAsync(new Area("Building A") { Id = 1, SiteId = 1 });
- _repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny()))
+ _repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny()))
.ReturnsAsync(new List
{
new("Inst1") { Id = 1, AreaId = 1, SiteId = 1 }
@@ -94,7 +94,7 @@ public class AreaServiceTests
{
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny()))
.ReturnsAsync(new Area("Parent") { Id = 1, SiteId = 1 });
- _repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny()))
+ _repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny()))
.ReturnsAsync(new List());
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny()))
.ReturnsAsync(new List
@@ -116,7 +116,7 @@ public class AreaServiceTests
{
_repoMock.Setup(r => r.GetAreaByIdAsync(1, It.IsAny()))
.ReturnsAsync(new Area("Empty") { Id = 1, SiteId = 1 });
- _repoMock.Setup(r => r.GetInstancesBySiteIdAsync(1, It.IsAny()))
+ _repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny()))
.ReturnsAsync(new List());
_repoMock.Setup(r => r.GetAreasBySiteIdAsync(1, It.IsAny()))
.ReturnsAsync(new List { 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()))
+ _repoMock.Setup(r => r.GetInstancesBySiteIdShallowAsync(1, It.IsAny()))
.ReturnsAsync(new List
{
new("DeepInstance") { Id = 10, AreaId = 3, SiteId = 1 }
diff --git a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceTests.cs
index 4789ae02..dde5c6b1 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceTests.cs
@@ -18,6 +18,7 @@ public class InstanceServiceTests
/// Initializes the test with a mocked repository and audit service and the service under test.
public InstanceServiceTests()
{
+ _repoMock.ServeClosureFromFullGraph(); // TPL-4: SetAlarmOverride reads the analysis closure
_sut = new InstanceService(_repoMock.Object, _auditMock.Object);
}