fix(worker): unregister-first shutdown cleanup order, guarded + logged (#175, R21-K10)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m32s
ci / java (push) Successful in 2m21s
ci / portable (push) Failing after 4m30s

ShutdownGracefully now Unregisters every server handle first (MXAccess drops its
items and advise subscriptions with it). Only for a server whose Unregister fails
does the UnAdvise -> RemoveItem fallback run. Each step is guarded, logged at Debug,
and the method is idempotent. #176 (AuthenticateUser cache) is unaffected.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-10 04:26:55 -05:00
parent ace12f81ad
commit 53562ddc17
3 changed files with 125 additions and 12 deletions
+4 -1
View File
@@ -228,7 +228,10 @@ Shutdown:
1. Mark the command queue as completing.
2. Drain or reject pending commands according to shutdown mode.
3. Optionally issue MXAccess cleanup calls for active handles.
3. Issue MXAccess cleanup: `Unregister` every tracked server handle first (MXAccess removes
its items and advise subscriptions with it). Only for a server whose `Unregister` failed,
fall back to `UnAdvise` then `RemoveItem` over its remaining handles. Each step is
guarded (a failure is recorded, never skips the rest) and logged at Debug (R21-K10, #175).
4. Detach event handlers.
5. Release COM references.
6. Uninitialize COM.
@@ -822,10 +822,10 @@ public sealed class MxAccessCommandExecutorTests
fakeComObject.OperationNames);
}
/// <summary>Verifies that ShutdownGracefullyAsync cleans up handles in advice, item, server order.</summary>
/// <summary>Verifies that ShutdownGracefullyAsync unregisters first and skips the redundant per-item calls (R21-K10).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ShutdownGracefullyAsync_CleansHandlesInAdviceItemServerOrder()
public async Task ShutdownGracefullyAsync_UnregistersFirstAndSkipsPerItemCleanup()
{
FakeMxAccessComObject fakeComObject = new(
registerHandle: 58,
@@ -843,11 +843,58 @@ public sealed class MxAccessCommandExecutorTests
Assert.True(result.Succeeded);
Assert.Equal(
new[] { "UnAdvise:58:510", "RemoveItem:58:510", "Unregister:58" },
new[] { "Unregister:58" },
fakeComObject.OperationNames.Where(name => name.StartsWith("Un", StringComparison.Ordinal)
|| name.StartsWith("Remove", StringComparison.Ordinal)));
}
/// <summary>Verifies that a failed Unregister falls back to UnAdvise then RemoveItem, in that order after Unregister.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ShutdownGracefullyAsync_UnregisterFailure_FallsBackToUnAdviseThenRemoveItem()
{
FakeMxAccessComObject fakeComObject = new(
registerHandle: 62,
addItemHandle: 514,
unregisterException: new COMException("Invalid handle.", unchecked((int)0x80070057)));
FakeMxAccessComObjectFactory factory = new(fakeComObject);
using StaRuntime runtime = CreateRuntime();
using MxAccessStaSession session = new(runtime, factory, new NoopEventSink());
await session.StartAsync(workerProcessId: 1234);
await session.DispatchAsync(CreateRegisterCommand("register-fallback", "client-a"));
await session.DispatchAsync(CreateAddItemCommand("add-fallback", 62, "Galaxy.Tag.Value"));
await session.DispatchAsync(CreateAdviseCommand("advise-fallback", 62, 514));
MxAccessShutdownResult result = await session.ShutdownGracefullyAsync(TimeSpan.FromSeconds(2));
Assert.Equal(new[] { "Unregister" }, result.Failures.Select(failure => failure.Operation));
Assert.Equal(
new[] { "Unregister:62", "UnAdvise:62:514", "RemoveItem:62:514" },
fakeComObject.OperationNames.Where(name => name.StartsWith("Un", StringComparison.Ordinal)
|| name.StartsWith("Remove", StringComparison.Ordinal)));
}
/// <summary>Verifies that a second ShutdownGracefullyAsync is a no-op and issues no further COM calls.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ShutdownGracefullyAsync_CalledTwice_IsIdempotent()
{
FakeMxAccessComObject fakeComObject = new(registerHandle: 63, addItemHandle: 515);
FakeMxAccessComObjectFactory factory = new(fakeComObject);
using StaRuntime runtime = CreateRuntime();
using MxAccessStaSession session = new(runtime, factory, new NoopEventSink());
await session.StartAsync(workerProcessId: 1234);
await session.DispatchAsync(CreateRegisterCommand("register-twice", "client-a"));
await session.ShutdownGracefullyAsync(TimeSpan.FromSeconds(2));
int callsAfterFirst = fakeComObject.OperationNames.Count();
MxAccessShutdownResult second = await session.ShutdownGracefullyAsync(TimeSpan.FromSeconds(2));
Assert.True(second.Succeeded);
Assert.Equal(callsAfterFirst, fakeComObject.OperationNames.Count());
Assert.Single(fakeComObject.OperationNames, name => name == "Unregister:63");
}
/// <summary>Verifies that ShutdownGracefullyAsync records cleanup failures and continues.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
@@ -872,7 +919,7 @@ public sealed class MxAccessCommandExecutorTests
MxAccessShutdownResult result = await session.ShutdownGracefullyAsync(TimeSpan.FromSeconds(2));
Assert.False(result.Succeeded);
Assert.Equal(new[] { "UnAdvise", "RemoveItem", "Unregister" }, result.Failures.Select(failure => failure.Operation));
Assert.Equal(new[] { "Unregister", "UnAdvise", "RemoveItem" }, result.Failures.Select(failure => failure.Operation));
Assert.All(result.Failures, failure => Assert.Equal(hresult, failure.HResult));
Assert.Contains("Unregister:59", fakeComObject.OperationNames);
}
@@ -1304,7 +1304,20 @@ public sealed class MxAccessSession : IDisposable
};
}
/// <summary>Gracefully shuts down the session, cleaning up all handles.</summary>
/// <summary>
/// Optional sink for per-step shutdown diagnostics (Debug level). Defaults to
/// <see cref="System.Diagnostics.Debug.WriteLine(string)"/>. Tests substitute a collector.
/// </summary>
internal Action<string>? ShutdownStepSink { get; set; }
/// <summary>
/// Gracefully shuts down the session. Unregister runs first (R21-K10): MXAccess
/// removes a server's items and advise subscriptions with it, so a successful
/// Unregister makes the per-item UnAdvise/RemoveItem calls redundant for that server.
/// Only for a server whose Unregister FAILED does the fallback UnAdvise then
/// RemoveItem sweep run over its remaining handles. Every step is guarded so one
/// failure never skips the rest; calling it again after completion is a no-op.
/// </summary>
/// <returns>The shutdown result, including any per-handle cleanup failures.</returns>
public MxAccessShutdownResult ShutdownGracefully()
{
@@ -1315,14 +1328,37 @@ public sealed class MxAccessSession : IDisposable
List<MxAccessShutdownFailure> failures = new();
CleanupAdviceHandles(failures);
CleanupItemHandles(failures);
CleanupServerHandles(failures);
HashSet<int> unregisteredFailed = CleanupServerHandles(failures);
if (unregisteredFailed.Count > 0)
{
CleanupAdviceHandles(failures, unregisteredFailed);
CleanupItemHandles(failures, unregisteredFailed);
}
DisposeCore(failures);
return new MxAccessShutdownResult(failures);
}
private void LogShutdownStep(string message)
{
try
{
if (ShutdownStepSink is { } sink)
{
sink(message);
}
else
{
System.Diagnostics.Debug.WriteLine("MxAccessSession shutdown: " + message);
}
}
catch
{
// Diagnostics must never break cleanup.
}
}
/// <inheritdoc />
public void Dispose()
{
@@ -1334,11 +1370,18 @@ public sealed class MxAccessSession : IDisposable
DisposeCore(failures: null);
}
private void CleanupAdviceHandles(ICollection<MxAccessShutdownFailure> failures)
private void CleanupAdviceHandles(
ICollection<MxAccessShutdownFailure> failures,
HashSet<int> serverHandles)
{
HashSet<long> cleanedPairs = new();
foreach (RegisteredAdviceHandle adviceHandle in handleRegistry.AdviceHandles)
{
if (!serverHandles.Contains(adviceHandle.ServerHandle))
{
continue;
}
long key = CreateItemKey(adviceHandle.ServerHandle, adviceHandle.ItemHandle);
if (!cleanedPairs.Add(key))
{
@@ -1349,9 +1392,11 @@ public sealed class MxAccessSession : IDisposable
{
mxAccessServer.UnAdvise(adviceHandle.ServerHandle, adviceHandle.ItemHandle);
handleRegistry.RemoveAdviceHandles(adviceHandle.ServerHandle, adviceHandle.ItemHandle);
LogShutdownStep($"UnAdvise server={adviceHandle.ServerHandle} item={adviceHandle.ItemHandle} ok (fallback)");
}
catch (Exception exception)
{
LogShutdownStep($"UnAdvise server={adviceHandle.ServerHandle} item={adviceHandle.ItemHandle} failed: {exception.GetType().Name}");
failures.Add(new MxAccessShutdownFailure(
nameof(UnAdvise),
adviceHandle.ServerHandle,
@@ -1361,17 +1406,26 @@ public sealed class MxAccessSession : IDisposable
}
}
private void CleanupItemHandles(ICollection<MxAccessShutdownFailure> failures)
private void CleanupItemHandles(
ICollection<MxAccessShutdownFailure> failures,
HashSet<int> serverHandles)
{
foreach (RegisteredItemHandle itemHandle in handleRegistry.ItemHandles)
{
if (!serverHandles.Contains(itemHandle.ServerHandle))
{
continue;
}
try
{
mxAccessServer.RemoveItem(itemHandle.ServerHandle, itemHandle.ItemHandle);
handleRegistry.RemoveItemHandle(itemHandle.ServerHandle, itemHandle.ItemHandle);
LogShutdownStep($"RemoveItem server={itemHandle.ServerHandle} item={itemHandle.ItemHandle} ok (fallback)");
}
catch (Exception exception)
{
LogShutdownStep($"RemoveItem server={itemHandle.ServerHandle} item={itemHandle.ItemHandle} failed: {exception.GetType().Name}");
failures.Add(new MxAccessShutdownFailure(
nameof(RemoveItem),
itemHandle.ServerHandle,
@@ -1381,17 +1435,22 @@ public sealed class MxAccessSession : IDisposable
}
}
private void CleanupServerHandles(ICollection<MxAccessShutdownFailure> failures)
/// <summary>Unregisters every tracked server first; returns the handles whose Unregister failed.</summary>
private HashSet<int> CleanupServerHandles(ICollection<MxAccessShutdownFailure> failures)
{
HashSet<int> failed = new();
foreach (RegisteredServerHandle serverHandle in handleRegistry.ServerHandles)
{
try
{
mxAccessServer.Unregister(serverHandle.ServerHandle);
handleRegistry.UnregisterServerHandle(serverHandle.ServerHandle);
LogShutdownStep($"Unregister server={serverHandle.ServerHandle} ok");
}
catch (Exception exception)
{
failed.Add(serverHandle.ServerHandle);
LogShutdownStep($"Unregister server={serverHandle.ServerHandle} failed: {exception.GetType().Name}");
failures.Add(new MxAccessShutdownFailure(
nameof(Unregister),
serverHandle.ServerHandle,
@@ -1399,6 +1458,8 @@ public sealed class MxAccessSession : IDisposable
exception));
}
}
return failed;
}
private static long CreateItemKey(
@@ -1461,6 +1522,7 @@ public sealed class MxAccessSession : IDisposable
try
{
eventSink.Detach();
LogShutdownStep("DetachEvents ok");
}
catch (Exception exception)
{
@@ -1477,6 +1539,7 @@ public sealed class MxAccessSession : IDisposable
if (Marshal.IsComObject(mxAccessComObject))
{
Marshal.FinalReleaseComObject(mxAccessComObject);
LogShutdownStep("ReleaseComObject ok");
}
}
catch (Exception exception) when (failures is not null)