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