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
@@ -413,6 +413,16 @@ public interface IDeploymentManagerRepository
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
/// <returns>The instance, or null if not found.</returns>
Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
/// <summary>
/// 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.
/// </summary>
/// <param name="instanceId">The instance id.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The state, or <see langword="null"/> when the instance does not exist.</returns>
Task<InstanceState?> GetInstanceStateAsync(int instanceId, CancellationToken cancellationToken = default);
/// <summary>
/// Gets an instance by unique name.
/// </summary>
@@ -286,6 +286,18 @@ public interface ITemplateEngineRepository
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task that resolves to the matching instance, or <see langword="null"/> if not found.</returns>
Task<Instance?> GetInstanceByIdAsync(int id, CancellationToken cancellationToken = default);
/// <summary>
/// DEP-4: loads several instances with the same child collections as
/// <see cref="GetInstanceByIdAsync"/>, <b>untracked</b>, 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.
/// </summary>
/// <param name="ids">The instance ids; missing ids are absent from the result.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The instances found.</returns>
Task<IReadOnlyList<Instance>> GetInstancesByIdsUntrackedAsync(
IReadOnlyCollection<int> ids, CancellationToken cancellationToken = default);
/// <summary>Retrieves all instances.</summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A task that resolves to a read-only list of all instances.</returns>
@@ -301,6 +313,30 @@ public interface ITemplateEngineRepository
/// <returns>A task that resolves to a read-only list of instances for the specified site.</returns>
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default);
/// <summary>
/// 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.
/// </summary>
/// <param name="siteId">The site ID.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The site's instances, shallow and untracked.</returns>
Task<IReadOnlyList<Instance>> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default);
/// <summary>
/// TPL-4: whether a template other than <paramref name="excludeTemplateId"/> named
/// <paramref name="name"/> (case-insensitively) already sits in <paramref name="folderId"/>
/// (<see langword="null"/> = the root) — the folder-move collision check, which used to load
/// the whole template table.
/// </summary>
/// <param name="folderId">The destination folder, or null for the root.</param>
/// <param name="name">The template name.</param>
/// <param name="excludeTemplateId">The template being moved.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns><see langword="true"/> when a sibling with that name exists.</returns>
Task<bool> TemplateNameExistsInFolderAsync(
int? folderId, string name, int excludeTemplateId, CancellationToken cancellationToken = default);
/// <summary>Reads one bounded, untracked page of topology instance rows for a site/area.</summary>
/// <param name="siteId">The site ID.</param>
/// <param name="areaId">The area ID to filter by, or null for every area.</param>
@@ -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<PendingDeployment>()
.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<PendingDeployment>().AddAsync(pending, cancellationToken);
}
@@ -505,29 +504,6 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
return rows.Count;
}
/// <summary>
/// Marks the pending row with primary key <paramref name="id"/> for deletion on the next
/// <c>SaveChanges</c> without loading it: an already-tracked instance is removed in place,
/// otherwise a key-only stub is attached and removed (EF deletes by key).
/// </summary>
/// <param name="id">Primary key of the pending row.</param>
private void RemovePendingByKey(int id)
{
var set = _dbContext.Set<PendingDeployment>();
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);
}
/// <inheritdoc />
public async Task<int> PurgeTerminalDeploymentRecordsAsync(
DateTimeOffset cutoffUtc,
@@ -777,6 +753,17 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
// --- Instance lookups for deployment pipeline ---
/// <inheritdoc />
public async Task<InstanceState?> 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<Instance>()
.Where(i => i.Id == instanceId)
.Select(i => (InstanceState?)i.State)
.FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default)
{
@@ -501,6 +501,29 @@ public class TemplateEngineRepository : ITemplateEngineRepository
.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
}
/// <inheritdoc />
public async Task<IReadOnlyList<Instance>> GetInstancesByIdsUntrackedAsync(
IReadOnlyCollection<int> ids, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(ids);
var result = new List<Instance>(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;
}
/// <inheritdoc />
public async Task<IReadOnlyList<Instance>> GetAllInstancesAsync(CancellationToken cancellationToken = default)
{
@@ -521,6 +544,30 @@ public class TemplateEngineRepository : ITemplateEngineRepository
.ToListAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdShallowAsync(int siteId, CancellationToken cancellationToken = default)
{
return await _context.Instances
.AsNoTracking()
.Where(i => i.SiteId == siteId)
.ToListAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<bool> 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));
}
/// <inheritdoc />
public async Task<IReadOnlyList<Instance>> GetInstancesBySiteIdAsync(int siteId, CancellationToken cancellationToken = default)
{
@@ -63,6 +63,9 @@ public class DeploymentService
/// Reason reported on every <see cref="SkippedInstanceResult"/> a bulk site
/// deploy produces for a <see cref="InstanceState.Disabled"/> instance.
/// </summary>
/// <summary>DEP-4: instances bulk-loaded (untracked) per chunk by the fleet staleness read.</summary>
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<DeploymentRecord>? EarlyResult)
Result<DeploymentRecord>? EarlyResult,
string? SkipReason = null)
{
/// <summary>
/// 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.
/// </summary>
/// <param name="reason">The skip reason shown in the bulk summary.</param>
/// <returns>A prepared deployment holding no lock, with <see cref="SkipReason"/> set.</returns>
public static PreparedDeployment Skipped(string reason) =>
new(null!, string.Empty, null!, string.Empty, string.Empty, string.Empty, null,
Result<DeploymentRecord>.Failure(reason), reason);
/// <summary>Builds a prepare-phase-resolved deployment carrying the given result and holding no lock.</summary>
/// <param name="result">The result to hand back to the caller.</param>
/// <returns>A prepared deployment whose <see cref="EarlyResult"/> is set.</returns>
@@ -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<int, string>();
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<Instance>)Array.Empty<Instance>());
}
evaluated++;
// Read-only path: hash only — no validation (its result was always discarded
@@ -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<int, CachedChain> _chains = new();
private readonly Dictionary<int, (long Version, IReadOnlyList<TemplateComposition> Compositions)> _compositions = new();
private readonly Dictionary<int, IReadOnlyDictionary<int, DataConnection>> _dataConnections = new();
private readonly Dictionary<int, Instance> _preloadedInstances = new();
private IReadOnlyList<ResolvedScript>? _sharedScripts;
private IReadOnlyDictionary<string, string>? _schemaLibrary;
@@ -78,6 +80,27 @@ public sealed class FlattenSession
/// <summary>Number of per-site data-connection queries that missed the memo.</summary>
public int DataConnectionLoads { get; private set; }
/// <summary>
/// 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.
/// </summary>
/// <param name="instances">The preloaded instances.</param>
public void PreloadInstances(IEnumerable<Instance> instances)
{
foreach (var instance in instances)
_preloadedInstances[instance.Id] = instance;
}
/// <summary>
/// Takes (and forgets) a preloaded instance, so a chunked caller never holds more than
/// one chunk of the fleet in memory.
/// </summary>
/// <param name="instanceId">The instance id.</param>
/// <returns>The preloaded instance, or <see langword="null"/> when none was preloaded.</returns>
public Instance? TakePreloadedInstance(int instanceId) =>
_preloadedInstances.Remove(instanceId, out var instance) ? instance : null;
/// <summary>
/// Every template id this session resolved — the union of all inheritance and
/// composed chains it walked. The staleness fast path records the watermark
@@ -190,8 +190,9 @@ public class FlatteningPipeline : IFlatteningPipeline
private async Task<Result<(FlattenedConfiguration Config, IReadOnlyDictionary<int, DataConnection> 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<int, DataConnection>)>.Failure(
$"Instance with ID {instanceId} not found.");
@@ -188,7 +188,8 @@ public class AreaService
return Result<bool>.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
@@ -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);
@@ -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<Template>.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)