fix(deployment): take the operation lock before validating the state transition (DEP-2, WP7 task 7.4)

Deploy/Disable/Enable/Delete now acquire the per-instance lock first, then reload the instance
(new IDeploymentManagerRepository.ReloadInstanceAsync) and validate on the fresh state, so a
Delete queued behind a deploy no longer takes the NotDeployed shortcut and orphans the running instance.
This commit is contained in:
Joseph Doherty
2026-12-03 09:45:24 -05:00
parent 47a7c0dde4
commit 517f093ce9
6 changed files with 247 additions and 16 deletions
@@ -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. - 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. - **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 > **`OperationLockManager` scope invariant (recorded decision, arch-review 05).** The
> per-instance locks are **per-node, in-memory**. Mutual exclusion therefore holds only > 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 It runs the ordinary deployment pipeline in three phases, of which only the middle
one is parallel: 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` validate, run query-before-redeploy reconciliation, insert the `InProgress`
record. Every step here touches the scoped, non-thread-safe `DbContext`, so the record. Every step here touches the scoped, non-thread-safe `DbContext`, so the
phase is strictly serial. All instances share ONE `FlattenSession`, so a phase is strictly serial. All instances share ONE `FlattenSession`, so a
@@ -414,6 +414,16 @@ public interface IDeploymentManagerRepository
/// <returns>The instance, or null if not found.</returns> /// <returns>The instance, or null if not found.</returns>
Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default); Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default);
/// <summary> /// <summary>
/// Refreshes <paramref name="instance"/> 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
/// <see cref="Instance.State"/> re-read.
/// </summary>
/// <param name="instance">The instance previously loaded by <see cref="GetInstanceByIdAsync"/>.</param>
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
/// <returns><see langword="true"/> when the instance no longer exists (it was deleted meanwhile); otherwise <see langword="false"/>.</returns>
Task<bool> ReloadInstanceAsync(Instance instance, CancellationToken cancellationToken = default);
/// <summary>
/// Gets an instance by unique name. /// Gets an instance by unique name.
/// </summary> /// </summary>
/// <param name="uniqueName">The unique instance name.</param> /// <param name="uniqueName">The unique instance name.</param>
@@ -778,6 +778,29 @@ public class DeploymentManagerRepository : IDeploymentManagerRepository
// --- Instance lookups for deployment pipeline --- // --- Instance lookups for deployment pipeline ---
/// <inheritdoc /> /// <inheritdoc />
public async Task<bool> 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<Instance>()
.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<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default) public async Task<Instance?> GetInstanceByIdAsync(int instanceId, CancellationToken cancellationToken = default)
{ {
return await _dbContext.Set<Instance>() return await _dbContext.Set<Instance>()
@@ -281,17 +281,27 @@ public class DeploymentService
if (instance == null) if (instance == null)
return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure($"Instance with ID {instanceId} not found.")); return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure($"Instance with ID {instanceId} not found."));
// Validate state transition // Acquire the per-instance operation lock BEFORE validating the state transition:
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "deploy"); // a command that waited behind another one must judge the state that command left
if (transitionError != null) // behind, not the copy loaded before the wait (DEP-2).
return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure(transitionError));
// Acquire per-instance operation lock
var lockHandle = await _lockManager.AcquireAsync( var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken); instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
try try
{ {
if (await _repository.ReloadInstanceAsync(instance, cancellationToken))
{
lockHandle.Dispose();
return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure($"Instance with ID {instanceId} not found."));
}
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "deploy");
if (transitionError != null)
{
lockHandle.Dispose();
return PreparedDeployment.Resolved(Result<DeploymentRecord>.Failure(transitionError));
}
return await PrepareUnderLockAsync( return await PrepareUnderLockAsync(
instance, user, session, reconcileGate, lockHandle, cancellationToken); instance, user, session, reconcileGate, lockHandle, cancellationToken);
} }
@@ -1626,13 +1636,18 @@ public class DeploymentService
if (instance == null) if (instance == null)
return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found."); return Result<InstanceLifecycleResponse>.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<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found.");
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "disable"); var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "disable");
if (transitionError != null) if (transitionError != null)
return Result<InstanceLifecycleResponse>.Failure(transitionError); return Result<InstanceLifecycleResponse>.Failure(transitionError);
using var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
var commandId = Guid.NewGuid().ToString("N"); var commandId = Guid.NewGuid().ToString("N");
var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken); var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken);
var command = new DisableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow); var command = new DisableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow);
@@ -1696,13 +1711,18 @@ public class DeploymentService
if (instance == null) if (instance == null)
return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found."); return Result<InstanceLifecycleResponse>.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<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found.");
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "enable"); var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "enable");
if (transitionError != null) if (transitionError != null)
return Result<InstanceLifecycleResponse>.Failure(transitionError); return Result<InstanceLifecycleResponse>.Failure(transitionError);
using var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
var commandId = Guid.NewGuid().ToString("N"); var commandId = Guid.NewGuid().ToString("N");
var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken); var siteId = await ResolveSiteIdentifierAsync(instance.SiteId, cancellationToken);
var command = new EnableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow); var command = new EnableInstanceCommand(commandId, instance.UniqueName, DateTimeOffset.UtcNow);
@@ -1765,13 +1785,18 @@ public class DeploymentService
if (instance == null) if (instance == null)
return Result<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found."); return Result<InstanceLifecycleResponse>.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<InstanceLifecycleResponse>.Failure($"Instance with ID {instanceId} not found.");
var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "delete"); var transitionError = StateTransitionValidator.ValidateTransition(instance.State, "delete");
if (transitionError != null) if (transitionError != null)
return Result<InstanceLifecycleResponse>.Failure(transitionError); return Result<InstanceLifecycleResponse>.Failure(transitionError);
using var lockHandle = await _lockManager.AcquireAsync(
instance.UniqueName, _options.OperationLockTimeout, cancellationToken);
var commandId = Guid.NewGuid().ToString("N"); var commandId = Guid.NewGuid().ToString("N");
// A NotDeployed instance has no live Instance Actor at any site, so Delete is // A NotDeployed instance has no live Instance Actor at any site, so Delete is
@@ -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;
/// <summary>
/// DEP-2: <see cref="DeploymentManagerRepository.ReloadInstanceAsync"/> refreshes an instance a command
/// loaded before it waited for the per-instance operation lock. The competing write goes through
/// <c>ExecuteUpdate</c>/<c>ExecuteDelete</c> so the tracked copy stays stale, as it would under a
/// second DbContext.
/// </summary>
public class ReloadInstanceRepositoryTests : IDisposable
{
private readonly ScadaBridgeDbContext _context = SqliteTestHelper.CreateInMemoryContext();
private readonly DeploymentManagerRepository _repository;
/// <summary>Initializes the repository under test.</summary>
public ReloadInstanceRepositoryTests() => _repository = new DeploymentManagerRepository(_context);
/// <summary>Releases the database context.</summary>
public void Dispose()
{
_context.Database.CloseConnection();
_context.Dispose();
}
private async Task<int> 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;
}
/// <summary>A tracked entity picks up a state written behind its back.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>An untracked entity gets its state re-read.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>A row deleted meanwhile is reported as removed, tracked or not.</summary>
/// <param name="tracked">Whether the instance is loaded with tracking.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[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));
}
}
@@ -1259,6 +1259,84 @@ public class DeploymentServiceTests : TestKit
Assert.Equal(1, serializationCounters.MaxConcurrent); Assert.Equal(1, serializationCounters.MaxConcurrent);
} }
// ── DEP-2: validate the state transition AFTER the operation lock is held ──
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DisableInstanceAsync_StateChangedWhileWaitingForLock_FailsTransitionCheckOnFreshState()
{
var instance = new Instance("RaceDisable") { Id = 80, SiteId = 1, State = InstanceState.Enabled };
_repo.GetInstanceByIdAsync(80, Arg.Any<CancellationToken>()).Returns(instance);
// The reload observes what the lock holder committed.
_repo.ReloadInstanceAsync(instance, Arg.Any<CancellationToken>()).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);
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DeleteInstanceAsync_DeployCompletedWhileWaiting_TearsDownSiteInsteadOfSkippingIt()
{
var instance = new Instance("RaceDelete") { Id = 81, SiteId = 1, State = InstanceState.NotDeployed };
_repo.GetInstanceByIdAsync(81, Arg.Any<CancellationToken>()).Returns(instance);
_repo.ReloadInstanceAsync(instance, Arg.Any<CancellationToken>()).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<object>(o => !o.ToString()!.Contains("SiteRoundTripSkipped")), Arg.Any<CancellationToken>());
}
/// <summary>An instance deleted by another command while this one waited is reported as not found.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task EnableInstanceAsync_InstanceDeletedWhileWaiting_ReturnsNotFound()
{
var instance = new Instance("RaceGone") { Id = 82, SiteId = 1, State = InstanceState.Disabled };
_repo.GetInstanceByIdAsync(82, Arg.Any<CancellationToken>()).Returns(instance);
_repo.ReloadInstanceAsync(instance, Arg.Any<CancellationToken>()).Returns(true);
var result = await _service.EnableInstanceAsync(82, "admin");
Assert.True(result.IsFailure);
Assert.Contains("not found", result.Error);
}
// ── Query-the-site-before-redeploy idempotency ── // ── Query-the-site-before-redeploy idempotency ──
/// <summary> /// <summary>