diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md index ec38b3af..21443d7e 100644 --- a/docs/MxAccessWorkerInstanceDesign.md +++ b/docs/MxAccessWorkerInstanceDesign.md @@ -255,11 +255,18 @@ while not shutdown: QS_ALLINPUT, MWMO_INPUTAVAILABLE) - while PeekMessage: + repeat at most 64 times while PeekMessage: TranslateMessage DispatchMessage ``` +Each pump pass dispatches at most `StaMessagePump.MaxMessagesPerPass` (64) +messages, then the loop stamps activity and returns to the command queue. An +unbounded drain never returns while COM callbacks arrive at least as fast as +they dispatch, so queued commands would not run and the activity stamp would +freeze until the watchdog reported `StaHung`. `MWMO_INPUTAVAILABLE` makes the +next wait return at once while input remains, so the cap loses no wakeups. + The command queue should signal a Win32 event or equivalent wait handle so the STA can wake without busy-waiting. @@ -338,11 +345,14 @@ message wake is what carries it. `MWMO_INPUTAVAILABLE` makes the drain contract load-bearing: the wait wakes on input that is merely *present*, including input an earlier `PeekMessage` saw but -did not remove. A `pumpStep` that drains only part of the queue — or a no-op one -— therefore leaves a message that satisfies the wake condition forever, and the +did not remove. A `pumpStep` that removes nothing — a no-op, or a peek without +`PM_REMOVE` — therefore leaves a message that satisfies the wake condition forever, and the loop spins at 100% CPU until its deadline (deadline and reply shape still hold; -it is a CPU fault, not a correctness one). Every `pumpStep` must drain to empty, -as `StaRuntime.PumpPendingMessages` does. +it is a CPU fault, not a correctness one). Every `pumpStep` must remove messages +on each call. `StaRuntime.PumpPendingMessages` removes up to 64 per call: a +backlog larger than that makes the next wait return at once, and the next step +dispatches the next slice, so the loop only stays busy while there is real +dispatch work and re-checks its deadline between slices. The wait slice is capped at 50 ms so `pumpStep` runs periodically even when nothing wakes the wait — a process with no STA message queue (unit tests drive diff --git a/docs/WorkerSta.md b/docs/WorkerSta.md index 84de4eb1..52d6ff53 100644 --- a/docs/WorkerSta.md +++ b/docs/WorkerSta.md @@ -48,7 +48,7 @@ while (!IsShutdownRequested()) { ProcessQueuedCommands(); messagePump.WaitForWorkOrMessages(commandWakeEvent, idlePumpInterval); - messagePump.PumpPendingMessages(); + messagePump.PumpPendingMessages(StaMessagePump.MaxMessagesPerPass); MarkActivity(); } ``` @@ -57,14 +57,15 @@ while (!IsShutdownRequested()) ### The message pump -`StaMessagePump.WaitForWorkOrMessages` calls `MsgWaitForMultipleObjectsEx` with `QS_ALLINPUT` and `MWMO_INPUTAVAILABLE`, so the wait wakes for either a signal on `commandWakeEvent` or any new message in the thread's Windows queue. `PumpPendingMessages` then drains the queue with `PM_REMOVE`: +`StaMessagePump.WaitForWorkOrMessages` calls `MsgWaitForMultipleObjectsEx` with `QS_ALLINPUT` and `MWMO_INPUTAVAILABLE`, so the wait wakes for either a signal on `commandWakeEvent` or any new message in the thread's Windows queue. `PumpPendingMessages` then dispatches pending messages with `PM_REMOVE`, at most `MaxMessagesPerPass` (64) per pass: ```csharp -public int PumpPendingMessages() +public int PumpPendingMessages(int maxMessages) { int pumpedMessages = 0; - while (PeekMessage(out NativeMessage message, IntPtr.Zero, 0, 0, PmRemove)) + while (pumpedMessages < maxMessages + && PeekMessage(out NativeMessage message, IntPtr.Zero, 0, 0, PmRemove)) { TranslateMessage(ref message); DispatchMessage(ref message); @@ -77,6 +78,8 @@ public int PumpPendingMessages() `DispatchMessage` is what causes the COM marshaler to deliver event sink calls onto the STA thread; without this loop, MXAccess events never surface to managed code. +The pass is bounded because an unbounded drain never returns while inbound COM callbacks arrive at least as fast as they dispatch. The loop then stops running queued commands (including an `UnAdvise` a client sends to shed load) and stops stamping `LastActivityUtc`, and the heartbeat watchdog reports the busy apartment as `StaHung` after `HeartbeatGrace`. Bounding the pass loses no wakeups: `MWMO_INPUTAVAILABLE` makes the next wait return at once while input remains, so under a flood the loop alternates one command-queue pass and one 64-message slice, stamping activity after each slice. `StaRuntime.PumpPendingMessages()`, which commands that hold the STA call from their wait loops, uses the same cap so those loops re-check their deadline between slices. + ## Work Items and the Command Queue `StaRuntime` exposes two `InvokeAsync` overloads. Both wrap the delegate in an internal `StaWorkItem`, enqueue it on a `ConcurrentQueue`, and signal `commandWakeEvent`: diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaMessagePumpTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaMessagePumpTests.cs index 3f4e30a1..80651176 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaMessagePumpTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaMessagePumpTests.cs @@ -182,6 +182,51 @@ public sealed class StaMessagePumpTests Assert.Equal(3, pumped); } + /// + /// Verifies that one pump pass stops at + /// and leaves the rest of the queue for the next pass (WIP-001). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task PumpPendingMessages_MoreThanCapPosted_DispatchesCapPerPass() + { + StaMessagePump pump = new(); + int posted = StaMessagePump.MaxMessagesPerPass + 10; + + (int First, int Second, int Third) passes = await RunOnStaThreadAsync(() => + { + int drained; + do + { + drained = pump.PumpPendingMessages(); + } + while (drained > 0); + + uint threadId = GetCurrentThreadId(); + for (int index = 0; index < posted; index++) + { + Assert.True(PostThreadMessage(threadId, WmNull, UIntPtr.Zero, IntPtr.Zero)); + } + + return (pump.PumpPendingMessages(), pump.PumpPendingMessages(), pump.PumpPendingMessages()); + }); + + Assert.Equal(StaMessagePump.MaxMessagesPerPass, passes.First); + Assert.Equal(10, passes.Second); + Assert.Equal(0, passes.Third); + } + + /// + /// Verifies that a pump pass rejects a cap that would dispatch nothing. + /// + [Fact] + public void PumpPendingMessages_NonPositiveCap_Throws() + { + StaMessagePump pump = new(); + + Assert.Throws(() => pump.PumpPendingMessages(0)); + } + /// /// Verifies that WaitForWorkOrMessages returns once a Windows message is posted to the STA thread. /// diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaRuntimeTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaRuntimeTests.cs index 1a336f9d..3492c624 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaRuntimeTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaRuntimeTests.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using ZB.MOM.WW.MxGateway.Worker.Sta; @@ -193,6 +194,65 @@ public sealed class StaRuntimeTests $"Expected a pump between queued work items (first saw {pumpsSeenByFirst}, second saw {pumpsSeenBySecond})."); } + /// + /// WIP-001: an inbound message flood must not starve the command queue + /// or freeze . Before the pump + /// pass was bounded, a queue that refilled as fast as it drained kept + /// the STA inside one pump call: queued commands never ran and the + /// activity stamp froze until the heartbeat watchdog reported + /// StaHung. The fake keeps flooding for the whole test, so the + /// command completing at all proves the loop returns to its queue + /// between bounded slices; the staleness bound stands in for the + /// watchdog's HeartbeatGrace (15 s in production). + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task MessageFlood_QueuedCommandRunsAndActivityStaysFresh() + { + FloodingMessagePump pump = new(); + using StaRuntime runtime = new(new RecordingComApartmentInitializer(), pump, TimeSpan.FromSeconds(30)); + runtime.Start(); + pump.Flooding = true; + try + { + // Let the flood establish itself before queueing the command. + Assert.True( + SpinWait.SpinUntil(() => pump.Dispatched > StaMessagePump.MaxMessagesPerPass * 4, TimeSpan.FromSeconds(5)), + "The flood never started dispatching."); + + TimeSpan worstStaleness = TimeSpan.Zero; + Stopwatch window = Stopwatch.StartNew(); + while (window.Elapsed < TimeSpan.FromMilliseconds(500)) + { + TimeSpan staleness = DateTimeOffset.UtcNow - runtime.LastActivityUtc; + if (staleness > worstStaleness) + { + worstStaleness = staleness; + } + + Thread.Sleep(5); + } + + Task command = runtime.InvokeAsync(() => Thread.CurrentThread.ManagedThreadId); + Task finished = await Task.WhenAny(command, Task.Delay(TimeSpan.FromSeconds(10))); + + Assert.Same(command, finished); + Assert.Equal(runtime.StaThreadId, await command); + Assert.True(pump.Flooding, "The flood must still be running when the command completes."); + Assert.True( + worstStaleness < TimeSpan.FromSeconds(2), + $"LastActivityUtc went {worstStaleness} stale during the flood."); + Assert.Equal(StaMessagePump.MaxMessagesPerPass, pump.SmallestRequestedCap); + Assert.True( + pump.LargestPass <= StaMessagePump.MaxMessagesPerPass, + $"A pump pass dispatched {pump.LargestPass} messages."); + } + finally + { + pump.Flooding = false; + } + } + /// /// WRK-02: an exception that kills the STA loop after a successful /// must be surfaced — recorded on diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/ControllableMessagePump.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/ControllableMessagePump.cs index 7658629d..e57e3ed6 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/ControllableMessagePump.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/ControllableMessagePump.cs @@ -33,7 +33,7 @@ internal sealed class ControllableMessagePump : IStaMessagePump } /// - public int PumpPendingMessages() + public int PumpPendingMessages(int maxMessages) { Interlocked.Increment(ref pumpCount); Exception? exception = Interlocked.Exchange(ref throwOnNextPump, null); diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/FloodingMessagePump.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/FloodingMessagePump.cs new file mode 100644 index 00000000..41fb60cf --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/TestSupport/FloodingMessagePump.cs @@ -0,0 +1,80 @@ +using System; +using System.Diagnostics; +using System.Threading; +using ZB.MOM.WW.MxGateway.Worker.Sta; + +namespace ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport; + +/// +/// Test that simulates an inbound Windows +/// message flood: while is set, the queue refills as +/// fast as it is drained, so a pump pass only ends when it reaches the cap +/// the caller passes. Each simulated dispatch burns a little CPU, standing in +/// for MXAccess marshalling one OnDataChange. The wait returns at once +/// while flooding, as MsgWaitForMultipleObjectsEx with +/// MWMO_INPUTAVAILABLE does while input is present. +/// +internal sealed class FloodingMessagePump : IStaMessagePump +{ + private static readonly TimeSpan DispatchCost = TimeSpan.FromTicks(500); // 50 microseconds + private int flooding; + private long dispatched; + private int largestPass; + private int smallestRequestedCap = int.MaxValue; + + /// Gets or sets a value indicating whether messages keep arriving. + public bool Flooding + { + get => Volatile.Read(ref flooding) != 0; + set => Volatile.Write(ref flooding, value ? 1 : 0); + } + + /// Gets the total number of simulated messages dispatched. + public long Dispatched => Interlocked.Read(ref dispatched); + + /// Gets the most messages any single pump pass dispatched. + public int LargestPass => Volatile.Read(ref largestPass); + + /// Gets the smallest maxMessages cap any caller passed. + public int SmallestRequestedCap => Volatile.Read(ref smallestRequestedCap); + + /// + public void WaitForWorkOrMessages(WaitHandle commandWakeEvent, TimeSpan timeout) + { + if (Flooding) + { + return; + } + + commandWakeEvent.WaitOne(timeout); + } + + /// + public int PumpPendingMessages(int maxMessages) + { + if (maxMessages < SmallestRequestedCap) + { + Volatile.Write(ref smallestRequestedCap, maxMessages); + } + + int pumped = 0; + while (pumped < maxMessages && Flooding) + { + Stopwatch cost = Stopwatch.StartNew(); + while (cost.Elapsed < DispatchCost) + { + Thread.SpinWait(20); + } + + pumped++; + Interlocked.Increment(ref dispatched); + } + + if (pumped > LargestPass) + { + Volatile.Write(ref largestPass, pumped); + } + + return pumped; + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Sta/IStaMessagePump.cs b/src/ZB.MOM.WW.MxGateway.Worker/Sta/IStaMessagePump.cs index c850d124..2b8c48e9 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Sta/IStaMessagePump.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Sta/IStaMessagePump.cs @@ -16,7 +16,11 @@ internal interface IStaMessagePump /// Maximum time to wait. void WaitForWorkOrMessages(WaitHandle commandWakeEvent, TimeSpan timeout); - /// Pumps and dispatches all pending Windows messages. + /// + /// Pumps and dispatches pending Windows messages until the queue is + /// empty or have been dispatched. + /// + /// Maximum number of messages to dispatch in this pass. /// The number of messages dispatched. - int PumpPendingMessages(); + int PumpPendingMessages(int maxMessages); } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaMessagePump.cs b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaMessagePump.cs index 8e6e758d..e80ae7fd 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaMessagePump.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaMessagePump.cs @@ -39,13 +39,47 @@ public sealed class StaMessagePump : IStaMessagePump } } - /// Pumps and dispatches all pending Windows messages, returning the count processed. + /// + /// Upper bound on the messages one pump pass dispatches. A pass that + /// drained to empty never returned while inbound COM callbacks arrived + /// at least as fast as they dispatched, so the STA loop stopped + /// servicing its command queue and stopped stamping activity, and the + /// heartbeat watchdog reported a busy apartment as StaHung + /// (WIP-001). Stopping after this many messages costs no wakeups: the + /// next MsgWaitForMultipleObjectsEx runs with + /// MWMO_INPUTAVAILABLE and returns at once while input remains. + /// + public const int MaxMessagesPerPass = 64; + + /// + /// Pumps and dispatches pending Windows messages, at most + /// of them, returning the count processed. + /// /// The number of messages pumped and dispatched. public int PumpPendingMessages() { + return PumpPendingMessages(MaxMessagesPerPass); + } + + /// + /// Pumps and dispatches pending Windows messages until the queue is + /// empty or have been dispatched. + /// + /// Maximum number of messages to dispatch in this pass. + /// The number of messages pumped and dispatched. + public int PumpPendingMessages(int maxMessages) + { + if (maxMessages <= 0) + { + throw new ArgumentOutOfRangeException( + nameof(maxMessages), + "A pump pass must be allowed to dispatch at least one message."); + } + int pumpedMessages = 0; - while (PeekMessage(out NativeMessage message, IntPtr.Zero, 0, 0, PmRemove)) + while (pumpedMessages < maxMessages + && PeekMessage(out NativeMessage message, IntPtr.Zero, 0, 0, PmRemove)) { TranslateMessage(ref message); DispatchMessage(ref message); diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaRuntime.cs b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaRuntime.cs index ac160417..cab1d6d8 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaRuntime.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaRuntime.cs @@ -160,11 +160,14 @@ public sealed class StaRuntime : IDisposable /// pumping) still accrues staleness and faults correctly. Callers must /// already be on the STA; the method is otherwise safe (PeekMessage simply /// finds no messages). + /// One call dispatches at most + /// messages so a caller's wait loop can re-check its deadline and + /// completion condition between slices of a message flood. /// /// The number of messages pumped. public int PumpPendingMessages() { - int pumpedMessages = messagePump.PumpPendingMessages(); + int pumpedMessages = messagePump.PumpPendingMessages(StaMessagePump.MaxMessagesPerPass); MarkActivity(); return pumpedMessages; } @@ -332,11 +335,16 @@ public sealed class StaRuntime : IDisposable started = true; startedEvent.Set(); + // Each pass dispatches a bounded slice of the Windows message + // queue, then stamps activity and returns to the command queue. + // Under an inbound event flood the wait returns at once + // (MWMO_INPUTAVAILABLE), so the loop alternates command work and + // message slices instead of draining messages forever. while (!IsShutdownRequested()) { ProcessQueuedCommands(); messagePump.WaitForWorkOrMessages(commandWakeEvent, idlePumpInterval); - messagePump.PumpPendingMessages(); + messagePump.PumpPendingMessages(StaMessagePump.MaxMessagesPerPass); MarkActivity(); } @@ -417,7 +425,8 @@ public sealed class StaRuntime : IDisposable // empty queue is cheap, so the per-item cost is negligible. if (!commandQueue.IsEmpty) { - messagePump.PumpPendingMessages(); + messagePump.PumpPendingMessages(StaMessagePump.MaxMessagesPerPass); + MarkActivity(); } } } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaWaitHelper.cs b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaWaitHelper.cs index 1171f7a3..aafbc37a 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaWaitHelper.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaWaitHelper.cs @@ -44,20 +44,23 @@ internal static class StaWaitHelper /// /// /// - /// Caller contract: the pump step must drain the message queue - /// to empty on every call. The wait uses + /// Caller contract: the pump step must remove messages from + /// the queue on every call. The wait uses /// , which reports /// input that is merely present — including input an earlier /// PeekMessage has already seen but not removed. A caller - /// whose pump step drains only part of the queue, or does nothing at - /// all, therefore leaves a message that satisfies the wake condition + /// whose pump step removes nothing (a no-op, or a peek without + /// PM_REMOVE) therefore leaves a message that satisfies the wake condition /// forever: every wait returns immediately, and the caller's poll /// loop degenerates into a busy loop that spins the thread at 100% /// until its deadline. That is a CPU fault, not a correctness one — /// the loop still honors its deadline and return shape — but it must - /// not ship. Drain with PeekMessage(..., PM_REMOVE) in a loop - /// until it returns false, exactly as - /// does. + /// not ship. Remove with PeekMessage(..., PM_REMOVE) as + /// does. A + /// bounded pass (at most ) + /// satisfies the contract: the immediate re-wake while a backlog + /// remains is real dispatch work, and the queue empties after + /// enough passes. /// /// /// The wait does not DangerousAddRef the handle. That is