fix(worker): bound each STA message-pump pass to 64 dispatches (WIP-001, #246)
ci / portable (push) Failing after 13m57s
ci / windows-x86 (push) Successful in 12m20s
ci / java (push) Failing after 40m28s

An unbounded PeekMessage drain never returned while inbound COM callbacks
arrived at least as fast as they dispatched, so the STA loop stopped running
queued commands and stopped stamping LastActivityUtc; the heartbeat watchdog
then faulted a busy apartment as StaHung. The record-info pin raises the
dispatch ceiling a lot but is best-effort, and the drain was still unbounded.

Each pump pass now dispatches at most StaMessagePump.MaxMessagesPerPass (64),
then the loop stamps activity and services the command queue. MWMO_INPUTAVAILABLE
makes the next wait return at once while input remains, so no wakeup is lost.
StaRuntime.PumpPendingMessages (the pump step of ReadBulk/write waits) uses the
same cap so those loops re-check their deadline between slices.

Tests: a fake message flood with a queued command (command runs, activity stays
fresh, no pass exceeds the cap); a real-queue test that a pass stops at the cap.
This commit is contained in:
Joseph Doherty
2026-12-03 09:40:52 -05:00
parent c065b3678a
commit 078b9c9840
10 changed files with 272 additions and 24 deletions
@@ -182,6 +182,51 @@ public sealed class StaMessagePumpTests
Assert.Equal(3, pumped);
}
/// <summary>
/// Verifies that one pump pass stops at <see cref="StaMessagePump.MaxMessagesPerPass"/>
/// and leaves the rest of the queue for the next pass (WIP-001).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>
/// Verifies that a pump pass rejects a cap that would dispatch nothing.
/// </summary>
[Fact]
public void PumpPendingMessages_NonPositiveCap_Throws()
{
StaMessagePump pump = new();
Assert.Throws<ArgumentOutOfRangeException>(() => pump.PumpPendingMessages(0));
}
/// <summary>
/// Verifies that WaitForWorkOrMessages returns once a Windows message is posted to the STA thread.
/// </summary>
@@ -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}).");
}
/// <summary>
/// WIP-001: an inbound message flood must not starve the command queue
/// or freeze <see cref="StaRuntime.LastActivityUtc"/>. 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
/// <c>StaHung</c>. 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 <c>HeartbeatGrace</c> (15 s in production).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<int> 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;
}
}
/// <summary>
/// WRK-02: an exception that kills the STA loop after a successful
/// <see cref="StaRuntime.Start"/> must be surfaced — recorded on
@@ -33,7 +33,7 @@ internal sealed class ControllableMessagePump : IStaMessagePump
}
/// <inheritdoc />
public int PumpPendingMessages()
public int PumpPendingMessages(int maxMessages)
{
Interlocked.Increment(ref pumpCount);
Exception? exception = Interlocked.Exchange(ref throwOnNextPump, null);
@@ -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;
/// <summary>
/// Test <see cref="IStaMessagePump"/> that simulates an inbound Windows
/// message flood: while <see cref="Flooding"/> 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 <c>OnDataChange</c>. The wait returns at once
/// while flooding, as <c>MsgWaitForMultipleObjectsEx</c> with
/// <c>MWMO_INPUTAVAILABLE</c> does while input is present.
/// </summary>
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;
/// <summary>Gets or sets a value indicating whether messages keep arriving.</summary>
public bool Flooding
{
get => Volatile.Read(ref flooding) != 0;
set => Volatile.Write(ref flooding, value ? 1 : 0);
}
/// <summary>Gets the total number of simulated messages dispatched.</summary>
public long Dispatched => Interlocked.Read(ref dispatched);
/// <summary>Gets the most messages any single pump pass dispatched.</summary>
public int LargestPass => Volatile.Read(ref largestPass);
/// <summary>Gets the smallest <c>maxMessages</c> cap any caller passed.</summary>
public int SmallestRequestedCap => Volatile.Read(ref smallestRequestedCap);
/// <inheritdoc />
public void WaitForWorkOrMessages(WaitHandle commandWakeEvent, TimeSpan timeout)
{
if (Flooding)
{
return;
}
commandWakeEvent.WaitOne(timeout);
}
/// <inheritdoc />
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;
}
}
@@ -16,7 +16,11 @@ internal interface IStaMessagePump
/// <param name="timeout">Maximum time to wait.</param>
void WaitForWorkOrMessages(WaitHandle commandWakeEvent, TimeSpan timeout);
/// <summary>Pumps and dispatches all pending Windows messages.</summary>
/// <summary>
/// Pumps and dispatches pending Windows messages until the queue is
/// empty or <paramref name="maxMessages"/> have been dispatched.
/// </summary>
/// <param name="maxMessages">Maximum number of messages to dispatch in this pass.</param>
/// <returns>The number of messages dispatched.</returns>
int PumpPendingMessages();
int PumpPendingMessages(int maxMessages);
}
@@ -39,13 +39,47 @@ public sealed class StaMessagePump : IStaMessagePump
}
}
/// <summary>Pumps and dispatches all pending Windows messages, returning the count processed.</summary>
/// <summary>
/// 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 <c>StaHung</c>
/// (WIP-001). Stopping after this many messages costs no wakeups: the
/// next <c>MsgWaitForMultipleObjectsEx</c> runs with
/// <c>MWMO_INPUTAVAILABLE</c> and returns at once while input remains.
/// </summary>
public const int MaxMessagesPerPass = 64;
/// <summary>
/// Pumps and dispatches pending Windows messages, at most
/// <see cref="MaxMessagesPerPass"/> of them, returning the count processed.
/// </summary>
/// <returns>The number of messages pumped and dispatched.</returns>
public int PumpPendingMessages()
{
return PumpPendingMessages(MaxMessagesPerPass);
}
/// <summary>
/// Pumps and dispatches pending Windows messages until the queue is
/// empty or <paramref name="maxMessages"/> have been dispatched.
/// </summary>
/// <param name="maxMessages">Maximum number of messages to dispatch in this pass.</param>
/// <returns>The number of messages pumped and dispatched.</returns>
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);
@@ -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 <see cref="StaMessagePump.MaxMessagesPerPass"/>
/// messages so a caller's wait loop can re-check its deadline and
/// completion condition between slices of a message flood.
/// </summary>
/// <returns>The number of messages pumped.</returns>
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();
}
}
}
@@ -44,20 +44,23 @@ internal static class StaWaitHelper
/// </summary>
/// <remarks>
/// <para>
/// <em>Caller contract: the pump step must drain the message queue
/// to empty on every call.</em> The wait uses
/// <em>Caller contract: the pump step must remove messages from
/// the queue on every call.</em> The wait uses
/// <see cref="StaNativeMethods.MwmoInputAvailable"/>, which reports
/// input that is merely <em>present</em> — including input an earlier
/// <c>PeekMessage</c> 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
/// <c>PM_REMOVE</c>) 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 <c>PeekMessage(..., PM_REMOVE)</c> in a loop
/// until it returns false, exactly as
/// <see cref="StaMessagePump.PumpPendingMessages"/> does.
/// not ship. Remove with <c>PeekMessage(..., PM_REMOVE)</c> as
/// <see cref="StaMessagePump.PumpPendingMessages(int)"/> does. A
/// bounded pass (at most <see cref="StaMessagePump.MaxMessagesPerPass"/>)
/// satisfies the contract: the immediate re-wake while a backlog
/// remains is real dispatch work, and the queue empties after
/// enough passes.
/// </para>
/// <para>
/// The wait does not <c>DangerousAddRef</c> the handle. That is