From 731be13e4eb80d2cc5f8422a4afd969b309c226a Mon Sep 17 00:00:00 2001 From: kuba Date: Wed, 2 Dec 2026 13:22:13 +0000 Subject: [PATCH 1/4] [Tests] Give job-wake waiters their own threads and wake them when a test ends The waiters were thread-pool items that block for up to 10 s. In a full parallel Libs run the pool is saturated by other blocking tests and injects threads slowly, so a waiter could start more than 5 s late ("the waiter never went to sleep"). Its late start then left it asleep in the process-wide sleeper mask, where the next test's wake over the other workers' bits woke it ("Expected 0, Actual 2"). Reproduced with every pool worker blocked: all three waiter tests fail with the same message before, pass after. --- .../Kernel/JobWakeRuntimeTests.cs | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/tests/SharpEmu.Libs.Tests/Kernel/JobWakeRuntimeTests.cs b/tests/SharpEmu.Libs.Tests/Kernel/JobWakeRuntimeTests.cs index f7bc593b4..8a394bc77 100644 --- a/tests/SharpEmu.Libs.Tests/Kernel/JobWakeRuntimeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Kernel/JobWakeRuntimeTests.cs @@ -60,7 +60,8 @@ public void AWakeEndsTheWaitLongBeforeItsTimeoutAndOnlyForEligibleSleepers() const int Worker = 42; var bit = 1UL << Worker; var watch = Stopwatch.StartNew(); - var waiter = Task.Run(() => JobWakeRuntime.Wait(Worker, Generation(), 10_000_000, null)); + using var cleanup = new WakeOnExit(bit); + var waiter = StartWaiter(() => JobWakeRuntime.Wait(Worker, Generation(), 10_000_000, null)); WaitForSleeper(bit); Assert.Equal(bit, Pollers() & bit); @@ -90,7 +91,8 @@ public void AQueueCheckingSleeperIsNotAPoller() const int Worker = 45; var bit = 1UL << Worker; - var waiter = Task.Run(() => JobWakeRuntime.Wait(Worker, Generation(), 10_000_000, (FixedWork?)new FixedWork(0))); + using var cleanup = new WakeOnExit(bit); + var waiter = StartWaiter(() => JobWakeRuntime.Wait(Worker, Generation(), 10_000_000, (FixedWork?)new FixedWork(0))); WaitForSleeper(bit); Assert.Equal(0UL, Pollers() & bit); Assert.Equal(1, JobWakeRuntime.Wake(bit, 1, Everyone)); @@ -107,8 +109,9 @@ public void AWakeStopsAtItsCount() } const ulong Pair = (1UL << 43) | (1UL << 44); + using var cleanup = new WakeOnExit(Pair); var waiters = new[] { 43, 44 } - .Select(worker => Task.Run(() => JobWakeRuntime.Wait(worker, Generation(), 10_000_000, null))) + .Select(worker => StartWaiter(() => JobWakeRuntime.Wait(worker, Generation(), 10_000_000, null))) .ToArray(); WaitForSleeper(Pair); @@ -160,6 +163,30 @@ public void GuestQueuesReportWorkersWithAPositiveCountOrAMailbox() private static int BitCount(ulong value) => System.Numerics.BitOperations.PopCount(value); + // A waiter blocks its thread for up to its timeout, so it gets a thread of its own: as a thread-pool item it waited + // for the pool to inject a thread, which a full parallel run saturated by other blocking tests took past the 5 s + // WaitForSleeper allows ("the waiter never went to sleep"). + private static Task StartWaiter(Func wait) => + Task.Factory.StartNew(wait, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + + // Wakes the test's workers when it ends, pass or fail: a waiter left asleep sits in the process-wide sleeper mask for + // its 10 s timeout, and the next test's wake over every other worker's bit found it (after AWakeStopsAtItsCount gave + // up on its late waiters, AWakeEnds... saw "Expected 0, Actual 2"). + private readonly struct WakeOnExit(ulong bits) : IDisposable + { + public void Dispose() + { + var watch = Stopwatch.StartNew(); + while ((Sleepers() & bits) != 0 && watch.Elapsed < TimeSpan.FromSeconds(5)) + { + JobWakeRuntime.Wake(bits, MaximumWorkerCount, Everyone); + Thread.Sleep(1); + } + } + } + + private const long MaximumWorkerCount = JobWakeRuntime.MaximumWorkers; + private static void WaitForSleeper(ulong bits) { var watch = Stopwatch.StartNew(); From 0389cebab80d97e1ec70cdcdc93eb831f4bd2641 Mon Sep 17 00:00:00 2001 From: kuba Date: Wed, 2 Dec 2026 13:22:13 +0000 Subject: [PATCH 2/4] [Tests] Install the guest font factory in FontTextLayoutTests The exports read the process-wide factory, which only FontExportsTests and FontWritingTests installed; a filtered run without them failed two tests with "No guest font factory was selected". Before: 2 of 13 fail alone; after: 13 of 13. --- tests/SharpEmu.Libs.Tests/Font/FontTextLayoutTests.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/SharpEmu.Libs.Tests/Font/FontTextLayoutTests.cs b/tests/SharpEmu.Libs.Tests/Font/FontTextLayoutTests.cs index 4ce83ad32..bf93043a9 100644 --- a/tests/SharpEmu.Libs.Tests/Font/FontTextLayoutTests.cs +++ b/tests/SharpEmu.Libs.Tests/Font/FontTextLayoutTests.cs @@ -22,7 +22,13 @@ public sealed class FontTextLayoutTests private readonly FakeCpuMemory _memory = new(Base, 0x10000); private readonly CpuContext _ctx; - public FontTextLayoutTests() => _ctx = new CpuContext(_memory, Generation.Gen5); + // The exports read the process-wide guest font factory: install it here rather than relying on another class + // having run first (a filtered run without FontExportsTests left it unset). + public FontTextLayoutTests() + { + GuestFontServices.Initialize(FontExportsTests.Factory); + _ctx = new CpuContext(_memory, Generation.Gen5); + } [Fact] public void TombRaiderTextLayoutImports_AreRegistered() From 7310589b81e286d5b88ab3d12ba1e12fbaa27a42 Mon Sep 17 00:00:00 2001 From: kuba Date: Wed, 2 Dec 2026 13:22:13 +0000 Subject: [PATCH 3/4] [Tests] Bound the remote hold test by its max hold, not a scheduling margin ALongSleepIsHeldWhileTheRemoteWaitsAndReturnsWhenItEnds asserted the sleep returned within grace + 1 s of the end; a full Libs run measured 2.43 s. The product's held sleep reads the remote every 4 ms and returns at the first read past LastEnd + grace, so anything past that is a thread (the sleeper, or the test before it published) not running. The case the bound guarded against, a sleep that missed the end, now returns only at an explicit 30 s max hold and is still told apart. The failure message reports the publish delay and the GC pause time across the interval, to say which next time. --- .../HLE/HostCompileStallTests.cs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/tests/SharpEmu.Libs.Tests/HLE/HostCompileStallTests.cs b/tests/SharpEmu.Libs.Tests/HLE/HostCompileStallTests.cs index 3dbf6e350..2a5400926 100644 --- a/tests/SharpEmu.Libs.Tests/HLE/HostCompileStallTests.cs +++ b/tests/SharpEmu.Libs.Tests/HLE/HostCompileStallTests.cs @@ -21,6 +21,8 @@ public sealed class HostCompileStallTests // the test makes longer than this). No test asserts on a margin a late thread can cross. private static readonly TimeSpan Prompt = TimeSpan.FromSeconds(1); private static readonly TimeSpan Patience = TimeSpan.FromSeconds(5); + // Longer than any scheduling delay a test tolerates, so a hold that ran to it is told from a late return. + private static readonly TimeSpan MissedEndHold = TimeSpan.FromSeconds(30); [Fact] public void ALongSleepWithNoStallReturnsAtOnce() @@ -115,7 +117,8 @@ public void ALongSleepIsHeldWhileTheRemoteWaitsAndReturnsWhenItEnds() { var reports = new List(); var remote = new FakeChannel(); - var stall = new HostCompileStall(LongSleep, Grace, enabled: true, held => reports.Add(held), MinimumWait) { Remote = remote }; + // A max hold no scheduling delay reaches: a sleep that missed the end returns only after it (or the join gives up). + var stall = new HostCompileStall(LongSleep, Grace, enabled: true, held => reports.Add(held), MinimumWait, maxHold: MissedEndHold) { Remote = remote }; remote.Publish(new HostCompileStallState(1, Stopwatch.GetTimestamp(), 0)); // A wait counts once it lasted the minimum. Thread.Sleep(MinimumWait + TimeSpan.FromMilliseconds(30)); @@ -127,12 +130,20 @@ public void ALongSleepIsHeldWhileTheRemoteWaitsAndReturnsWhenItEnds() Assert.Equal(0, returned()); Assert.True(stall.IsHolding); + var pausedBefore = GC.GetTotalPauseDuration(); var ended = Stopwatch.GetTimestamp(); remote.Publish(new HostCompileStallState(0, 0, ended)); - Assert.True(sleeper.Join(TimeSpan.FromSeconds(5))); + var published = Stopwatch.GetElapsedTime(ended); + Assert.True(sleeper.Join(MissedEndHold + Patience)); var held = Stopwatch.GetElapsedTime(ended, returned()); - // Promptly after the grace: a sleep that missed the end would return at DefaultMaxHold. - Assert.InRange(held, Grace - TimeSpan.FromMilliseconds(20), Grace + Prompt); + // Not before the grace, and because of the end, not the max hold. The held sleep reads the remote every 4 ms and + // returns at the first read past LastEnd + grace, so anything beyond that is the sleeper (or this thread, before + // it published) not running: a full Libs run once kept it 2.4 s, so the upper bound is the max hold's, not a + // scheduling margin. + Assert.True(held >= Grace - TimeSpan.FromMilliseconds(20) && held < MissedEndHold - Patience, + $"held {held.TotalMilliseconds:F0} ms after the end (grace {Grace.TotalMilliseconds:F0} ms, max hold " + + $"{MissedEndHold.TotalSeconds:F0} s); published {published.TotalMilliseconds:F0} ms after the end; GC pauses " + + $"meanwhile {(GC.GetTotalPauseDuration() - pausedBefore).TotalMilliseconds:F0} ms"); Assert.False(stall.IsHolding); Assert.Equal([true, false], reports); } From e1485eb58fa784b679b0799df6114dad82c6101c Mon Sep 17 00:00:00 2001 From: kuba Date: Wed, 2 Dec 2026 14:03:57 +0000 Subject: [PATCH 4/4] [Tests] Let the first-frame test accept a playback that finished past its end FirstFrameWaitsUntilPresentationStarts waited 10 s for frame 2 of a two-frame, 2 fps movie. When the test thread is held up for more than 0.5 s after it starts the clock (a full Libs run froze the test process for seconds to tens of seconds: the same moment failed HostCompileStall and GameLibraryWatcher tests), the next poll swaps in frame 2 and, its time already over, finishes the playback in the same call and returns false. That is the documented product behaviour (a frame the clock has passed is never shown), so the test now accepts either a later frame or a playback finished with its clock past the movie's duration. The theory case pollDelayMs=1100 fails with the old assertion exactly as the full run did (current=1 decoded=2 finished=True) and passes now. MediaFramePlayback.DescribeState, an internal diagnostic, is printed by the frame waits' timeouts (queued and decoded frames, decoder thread, which clock and where it stands). --- src/SharpEmu.Libs/Media/MediaFramePlayback.cs | 21 +++++++++ .../Media/MediaFramePlaybackTests.cs | 46 ++++++++++++++++--- 2 files changed, 61 insertions(+), 6 deletions(-) diff --git a/src/SharpEmu.Libs/Media/MediaFramePlayback.cs b/src/SharpEmu.Libs/Media/MediaFramePlayback.cs index a5eca1b50..e4528cdb6 100644 --- a/src/SharpEmu.Libs/Media/MediaFramePlayback.cs +++ b/src/SharpEmu.Libs/Media/MediaFramePlayback.cs @@ -527,5 +527,26 @@ public void Dispose() } } + /// + /// The state a frame wait depends on, for a test's failure message: whether the decoder produced the frame (queued, + /// decoded count, its thread) or the clock has not reached it (which clock, and where it stands). + /// + internal string DescribeState() + { + lock (_gate) + { + var audioRunning = GuestAudioClock.IsRunning; + return $"current={_currentFrameIndex} queued={_decodedFrames.Count} " + + $"next_queued={(_decodedFrames.Count > 0 ? _decodedFrames.Peek().Index : -1)} " + + $"decoded={_nextDecodedFrameIndex} decoder_completed={_decoderCompleted} " + + $"decoder_thread={_decoderThread.ThreadState} free_buffers={_freeBuffers.Count} " + + $"finished={_finished} paused={_paused} clock_started={_playbackClockStarted} " + + $"target={CurrentTargetFrameIndexLocked()} playback_s={CurrentPlaybackSecondsLocked():F3} " + + $"wall_s={(_playbackClockStarted ? CurrentWallPlaybackSecondsLocked() : 0):F3} " + + $"follows_audio={_followGuestAudioClock && audioRunning} audio_running={audioRunning} " + + $"audio_played_s={GuestAudioClock.PlayedSeconds:F3} audio_start_s={_audioStartSeconds:F3}"; + } + } + private readonly record struct DecodedFrame(long Index, byte[] Pixels); } diff --git a/tests/SharpEmu.Libs.Tests/Media/MediaFramePlaybackTests.cs b/tests/SharpEmu.Libs.Tests/Media/MediaFramePlaybackTests.cs index ea3b8512e..6cf4d1792 100644 --- a/tests/SharpEmu.Libs.Tests/Media/MediaFramePlaybackTests.cs +++ b/tests/SharpEmu.Libs.Tests/Media/MediaFramePlaybackTests.cs @@ -43,11 +43,15 @@ private static byte[] WaitForAdvancedFrame(MediaFramePlayback playback) Thread.Sleep(1); } - throw new TimeoutException("The decoder did not produce a frame."); + throw new TimeoutException($"The decoder did not produce a frame: {playback.DescribeState()}"); } - [Fact] - public void FirstFrameWaitsUntilPresentationStarts() + // pollDelayMs stands for the test thread being held up after it started the clock (a full Libs run froze this + // process for seconds): past the movie's end, a poll swaps in frame 2 and finds its time over in the same call. + [Theory] + [InlineData(0)] + [InlineData(1100)] + public void FirstFrameWaitsUntilPresentationStarts(int pollDelayMs) { using var playback = new MediaFramePlayback(new SequenceDecoder(1, 2)); @@ -62,7 +66,37 @@ public void FirstFrameWaitsUntilPresentationStarts() Assert.True(playback.TryGetFrame(true, out held, out advanced)); Assert.False(advanced); Assert.Equal(1, held[0]); - Assert.Equal(2, WaitForAdvancedFrame(playback)[0]); + Thread.Sleep(pollDelayMs); + AssertMovesOnFromTheFirstFrame(playback, lastFrame: 2); + } + + // Once presentation started, playback leaves the first frame: it shows a later one, or, when the poll came after the + // movie's whole duration (a frame the clock has passed is never shown, the last one included), it has finished. + private static void AssertMovesOnFromTheFirstFrame(MediaFramePlayback playback, byte lastFrame) + { + var duration = lastFrame * (double)playback.FramesPerSecondDenominator / playback.FramesPerSecondNumerator; + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); + while (DateTime.UtcNow < deadline) + { + if (playback.TryGetFrame(true, out var frame, out var advanced)) + { + if (advanced) + { + Assert.InRange(frame[0], (byte)2, lastFrame); + return; + } + } + else + { + Assert.True(playback.IsFinished, playback.DescribeState()); + Assert.True(playback.PlaybackProgress.Seconds >= duration, playback.DescribeState()); + return; + } + + Thread.Sleep(1); + } + + throw new TimeoutException($"Playback stayed on its first frame: {playback.DescribeState()}"); } [Fact] @@ -120,7 +154,7 @@ private static byte[] WaitForFrame( Thread.Sleep(1); } - throw new TimeoutException("The decoder did not produce a frame."); + throw new TimeoutException($"The decoder did not produce a frame: {playback.DescribeState()}"); } private static byte[] WaitForGuestFrame( @@ -143,7 +177,7 @@ private static byte[] WaitForGuestFrame( Thread.Sleep(1); } - throw new TimeoutException("The decoder did not produce the requested guest frame."); + throw new TimeoutException($"The decoder did not produce the requested guest frame: {playback.DescribeState()}"); } private sealed class SequenceDecoder(params byte[] values) : IMediaFrameDecoder