diff --git a/docs/requirements/Component-DeploymentManager.md b/docs/requirements/Component-DeploymentManager.md
index 228d2068..7bf9c3ed 100644
--- a/docs/requirements/Component-DeploymentManager.md
+++ b/docs/requirements/Component-DeploymentManager.md
@@ -90,6 +90,7 @@ All mutating operations on a single instance (deploy, disable, enable, delete) s
- Only one mutating operation per instance can be in-flight at a time. A second operation is rejected with an "operation in progress" error.
- **Different instances**: Operations on different instances can proceed **in parallel**, even at the same site. Each tracks status independently. This supports the bulk "deploy all out-of-date instances" operation efficiently.
+- **Lock first, then validate.** Each command loads the instance (to learn its name), acquires the lock, then **reloads the instance and runs the state-transition check on the fresh state** (`IDeploymentManagerRepository.ReloadInstanceAsync`; an instance deleted meanwhile reports "not found"). A command that waited behind another one therefore never acts on the state it loaded before the wait — e.g. a Delete queued behind a deploy sees `Enabled`, not the stale `NotDeployed`, and tears the site down instead of orphaning it (review DEP-2).
> **`OperationLockManager` scope invariant (recorded decision, arch-review 05).** The
> per-instance locks are **per-node, in-memory**. Mutual exclusion therefore holds only
@@ -149,7 +150,7 @@ optimistically-concurrent status record.
It runs the ordinary deployment pipeline in three phases, of which only the middle
one is parallel:
-1. **Prepare (serial).** Validate transition, take the operation lock, flatten +
+1. **Prepare (serial).** Take the operation lock, validate the transition against the freshly reloaded instance, flatten +
validate, run query-before-redeploy reconciliation, insert the `InProgress`
record. Every step here touches the scoped, non-thread-safe `DbContext`, so the
phase is strictly serial. All instances share ONE `FlattenSession`, so a
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..6f213da2 100644
--- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Repositories/IDeploymentManagerRepository.cs
@@ -414,6 +414,16 @@ public interface IDeploymentManagerRepository
/// The instance, or null if not found.
Task GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
///
+ /// Refreshes in place from the database so a caller that
+ /// waited for the per-instance operation lock can validate the state the command ahead
+ /// of it left behind (DEP-2). A tracked entity is reloaded; an untracked one has its
+ /// re-read.
+ ///
+ /// The instance previously loaded by .
+ /// A cancellation token that can be used to cancel the operation.
+ /// when the instance no longer exists (it was deleted meanwhile); otherwise .
+ Task ReloadInstanceAsync(Instance instance, CancellationToken cancellationToken = default);
+ ///
/// Gets an instance by unique name.
///
/// The unique instance name.
diff --git a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs
index 435252ec..d486d90c 100644
--- a/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase/Repositories/DeploymentManagerRepository.cs
@@ -778,6 +778,29 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
// --- Instance lookups for deployment pipeline ---
///
+ public async Task ReloadInstanceAsync(Instance instance, CancellationToken cancellationToken = default)
+ {
+ var entry = _dbContext.Entry(instance);
+ if (entry.State == EntityState.Detached)
+ {
+ // Loaded without tracking (a NoTracking circuit context): there is no entry to
+ // reload, so re-read the one column the transition check depends on.
+ var fresh = await _dbContext.Set()
+ .AsNoTracking()
+ .Where(i => i.Id == instance.Id)
+ .Select(i => (InstanceState?)i.State)
+ .FirstOrDefaultAsync(cancellationToken);
+ if (fresh is null)
+ return true;
+ instance.State = fresh.Value;
+ return false;
+ }
+
+ // EF detaches the entity when the row has been deleted meanwhile.
+ await entry.ReloadAsync(cancellationToken);
+ return entry.State == EntityState.Detached;
+ }
+
public async Task GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default)
{
return await _dbContext.Set()
diff --git a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs
index 968ac9e6..6b79c22d 100644
--- a/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.DeploymentManager/DeploymentService.cs
@@ -281,17 +281,27 @@ public class DeploymentService
if (instance == null)
return PreparedDeployment.Resolved(Result.Failure($"Instance with ID {instanceId} not found."));
- // Validate state transition
- var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "deploy");
- if (transitionError != null)
- return PreparedDeployment.Resolved(Result.Failure(transitionError));
-
- // Acquire per-instance operation lock
+ // Acquire the per-instance operation lock BEFORE validating the state transition:
+ // a command that waited behind another one must judge the state that command left
+ // behind, not the copy loaded before the wait (DEP-2).
var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
try
{
+ if (await _repository.ReloadInstanceAsync(instance, cancellationToken))
+ {
+ lockHandle.Dispose();
+ return PreparedDeployment.Resolved(Result.Failure($"Instance with ID {instanceId} not found."));
+ }
+
+ var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "deploy");
+ if (transitionError != null)
+ {
+ lockHandle.Dispose();
+ return PreparedDeployment.Resolved(Result.Failure(transitionError));
+ }
+
return await PrepareUnderLockAsync(
instance, user, session, reconcileGate, lockHandle, cancellationToken);
}
@@ -1626,13 +1636,18 @@ public class DeploymentService
if (instance == null)
return Result.Failure($"Instance with ID {instanceId} not found.");
+ // Lock first, then validate against the state as it is NOW (DEP-2): a command that
+ // waited behind another one must not act on the copy loaded before the wait.
+ using var lockHandle = await _lockManager.AcquireAsync(
+ instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
+
+ if (await _repository.ReloadInstanceAsync(instance, cancellationToken))
+ return Result.Failure($"Instance with ID {instanceId} not found.");
+
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "disable");
if (transitionError != null)
return Result.Failure(transitionError);
- using var lockHandle = await _lockManager.AcquireAsync(
- instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
-
var commandId = Guid.NewGuid().ToString("N");
var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken);
var command = new DisableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow);
@@ -1696,13 +1711,18 @@ public class DeploymentService
if (instance == null)
return Result.Failure($"Instance with ID {instanceId} not found.");
+ // Lock first, then validate against the state as it is NOW (DEP-2): a command that
+ // waited behind another one must not act on the copy loaded before the wait.
+ using var lockHandle = await _lockManager.AcquireAsync(
+ instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
+
+ if (await _repository.ReloadInstanceAsync(instance, cancellationToken))
+ return Result.Failure($"Instance with ID {instanceId} not found.");
+
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "enable");
if (transitionError != null)
return Result.Failure(transitionError);
- using var lockHandle = await _lockManager.AcquireAsync(
- instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
-
var commandId = Guid.NewGuid().ToString("N");
var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken);
var command = new EnableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow);
@@ -1765,13 +1785,18 @@ public class DeploymentService
if (instance == null)
return Result.Failure($"Instance with ID {instanceId} not found.");
+ // Lock first, then validate against the state as it is NOW (DEP-2): a command that
+ // waited behind another one must not act on the copy loaded before the wait.
+ using var lockHandle = await _lockManager.AcquireAsync(
+ instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
+
+ if (await _repository.ReloadInstanceAsync(instance, cancellationToken))
+ return Result.Failure($"Instance with ID {instanceId} not found.");
+
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "delete");
if (transitionError != null)
return Result.Failure(transitionError);
- using var lockHandle = await _lockManager.AcquireAsync(
- instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
-
var commandId = Guid.NewGuid().ToString("N");
// A NotDeployed instance has no live Instance Actor at any site, so Delete is
diff --git a/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/ReloadInstanceRepositoryTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/ReloadInstanceRepositoryTests.cs
new file mode 100644
index 00000000..b3cfa317
--- /dev/null
+++ b/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/ReloadInstanceRepositoryTests.cs
@@ -0,0 +1,94 @@
+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.ConfigurationDatabase.Repositories;
+
+namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;
+
+///
+/// DEP-2: refreshes an instance a command
+/// loaded before it waited for the per-instance operation lock. The competing write goes through
+/// ExecuteUpdate/ExecuteDelete so the tracked copy stays stale, as it would under a
+/// second DbContext.
+///
+public class ReloadInstanceRepositoryTests : IDisposable
+{
+ private readonly ScadaBridgeDbContext _context = SqliteTestHelper.CreateInMemoryContext();
+ private readonly DeploymentManagerRepository _repository;
+
+ /// Initializes the repository under test.
+ public ReloadInstanceRepositoryTests() => _repository = new DeploymentManagerRepository(_context);
+
+ /// Releases the database context.
+ public void Dispose()
+ {
+ _context.Database.CloseConnection();
+ _context.Dispose();
+ }
+
+ private async Task SeedAsync(InstanceState state)
+ {
+ var site = new Site("S", "SI-S");
+ _context.Sites.Add(site);
+ var template = new Template("T");
+ _context.Templates.Add(template);
+ await _context.SaveChangesAsync();
+ var instance = new Instance("Inst") { SiteId = site.Id, TemplateId = template.Id, State = state };
+ _context.Instances.Add(instance);
+ await _context.SaveChangesAsync();
+ return instance.Id;
+ }
+
+ /// A tracked entity picks up a state written behind its back.
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task ReloadInstanceAsync_Tracked_SeesStateWrittenMeanwhile()
+ {
+ var id = await SeedAsync(InstanceState.NotDeployed);
+ var instance = (await _repository.GetInstanceByIdAsync(id))!;
+ await _context.Instances.Where(i => i.Id == id)
+ .ExecuteUpdateAsync(s => s.SetProperty(i => i.State, InstanceState.Enabled));
+ Assert.Equal(InstanceState.NotDeployed, instance.State); // stale, as in the race
+
+ var removed = await _repository.ReloadInstanceAsync(instance);
+
+ Assert.False(removed);
+ Assert.Equal(InstanceState.Enabled, instance.State);
+ Assert.Equal(EntityState.Unchanged, _context.Entry(instance).State);
+ }
+
+ /// An untracked entity gets its state re-read.
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task ReloadInstanceAsync_Untracked_SeesStateWrittenMeanwhile()
+ {
+ var id = await SeedAsync(InstanceState.Enabled);
+ var instance = await _context.Instances.AsNoTracking().SingleAsync(i => i.Id == id);
+ await _context.Instances.Where(i => i.Id == id)
+ .ExecuteUpdateAsync(s => s.SetProperty(i => i.State, InstanceState.Disabled));
+
+ var removed = await _repository.ReloadInstanceAsync(instance);
+
+ Assert.False(removed);
+ Assert.Equal(InstanceState.Disabled, instance.State);
+ }
+
+ /// A row deleted meanwhile is reported as removed, tracked or not.
+ /// Whether the instance is loaded with tracking.
+ /// A task that represents the asynchronous operation.
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public async Task ReloadInstanceAsync_RowDeleted_ReportsRemoved(bool tracked)
+ {
+ var id = await SeedAsync(InstanceState.Enabled);
+ var instance = tracked
+ ? (await _repository.GetInstanceByIdAsync(id))!
+ : await _context.Instances.AsNoTracking().SingleAsync(i => i.Id == id);
+ await _context.Instances.Where(i => i.Id == id).ExecuteDeleteAsync();
+
+ Assert.True(await _repository.ReloadInstanceAsync(instance));
+ }
+}
diff --git a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceTests.cs
index 1bc82507..2ef6e438 100644
--- a/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceTests.cs
+++ b/tests/ZB.MOM.WW.ScadaBridge.DeploymentManager.Tests/DeploymentServiceTests.cs
@@ -1259,6 +1259,84 @@ public class DeploymentServiceTests : TestKit
Assert.Equal(1, serializationCounters.MaxConcurrent);
}
+ // ── DEP-2: validate the state transition AFTER the operation lock is held ──
+
+ ///
+ /// A command that waited behind another one must judge the state that command left behind:
+ /// here the instance was Enabled when loaded, but another Disable finished while this one
+ /// waited for the lock. Validating the stale copy would send a second Disable to the site.
+ ///
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task DisableInstanceAsync_StateChangedWhileWaitingForLock_FailsTransitionCheckOnFreshState()
+ {
+ var instance = new Instance("RaceDisable") { Id = 80, SiteId = 1, State = InstanceState.Enabled };
+ _repo.GetInstanceByIdAsync(80, Arg.Any()).Returns(instance);
+ // The reload observes what the lock holder committed.
+ _repo.ReloadInstanceAsync(instance, Arg.Any()).Returns(_ =>
+ {
+ instance.State = InstanceState.Disabled;
+ return Task.FromResult(false);
+ });
+
+ using var held = await _lockManager.AcquireAsync("RaceDisable", TimeSpan.FromSeconds(5), CancellationToken.None);
+ var pending = _service.DisableInstanceAsync(80, "admin");
+ await Task.Delay(100);
+ Assert.False(pending.IsCompleted, "the command must wait for the lock before validating");
+ held.Dispose();
+
+ var result = await pending;
+
+ // The default _service has no comm actor: reaching the site would throw, so a clean
+ // failure proves the transition check ran on the fresh Disabled state first.
+ Assert.True(result.IsFailure);
+ Assert.Contains("not allowed", result.Error);
+ }
+
+ ///
+ /// Instance X was NotDeployed when the Delete loaded it, then a deploy that held the lock left it
+ /// Enabled. The Delete must take the site round-trip, not the NotDeployed central-only shortcut.
+ ///
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task DeleteInstanceAsync_DeployCompletedWhileWaiting_TearsDownSiteInsteadOfSkippingIt()
+ {
+ var instance = new Instance("RaceDelete") { Id = 81, SiteId = 1, State = InstanceState.NotDeployed };
+ _repo.GetInstanceByIdAsync(81, Arg.Any()).Returns(instance);
+ _repo.ReloadInstanceAsync(instance, Arg.Any()).Returns(_ =>
+ {
+ instance.State = InstanceState.Enabled;
+ return Task.FromResult(false);
+ });
+
+ var counters = new ReconcileProbeCounters();
+ var commActor = Sys.ActorOf(Props.Create(() =>
+ new ReconcileProbeActor(counters, siteHash: "x", failQuery: false)));
+ var service = CreateServiceWithCommActor(commActor);
+
+ var result = await service.DeleteInstanceAsync(81, "admin");
+
+ Assert.True(result.IsSuccess);
+ await _audit.Received().LogAsync(
+ "admin", "Delete", "Instance", "81", "RaceDelete",
+ Arg.Is