Skip to content

feat(ci): Capture diagnostics when runtime tests stall - #24007

Open
MartinZikmund wants to merge 6 commits into
masterfrom
dev/mazi/ci-stall-diagnostics
Open

MartinZikmund wants to merge 6 commits into
masterfrom
dev/mazi/ci-stall-diagnostics

Conversation

@MartinZikmund

@MartinZikmund MartinZikmund commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

GitHub Issue: closes #24006

Related: #24005 (macOS host freeze), #23967 (When_MsAppData Linux hang) — this PR does not fix either, it makes them diagnosable.

PR Type:

🏗️ Build or CI related changes

What changed? 🚀

macOS and Linux desktop Skia runtime tests freeze mid-test and get killed by the 60-minute job timeout, leaving no evidence of what blocked. The log just stops. There is no stack, no dump, and no way to tell whether the UI thread, the thread pool, or the whole process stopped.

This adds two complementary instruments. They answer different halves of the question, which is why both are here.

1. TestRunStallMonitor — in-process heartbeat

src/SamplesApp/SamplesApp.UnitTests.Shared/Controls/UnitTest/TestRunStallMonitor.cs

Emits one line per interval (30 s on CI) while tests run:

[stall-monitor] elapsed=00:21:14 inTest=00:00:03 dispatcher=2ms threadPool=0ms gcPauseDelta=41ms test='…When_Focused_Element_In_Scaled_Viewbox'
[stall-monitor] STALL elapsed=00:24:14 inTest=00:03:03 dispatcher=BLOCKED(>5s) threadPool=0ms gcPauseDelta=0ms test='…When_Focused_Element_In_Scaled_Viewbox'

The design point is that the three signals are independent, so the shape of the output identifies the culprit:

observation conclusion
heartbeat continues, dispatcher=BLOCKED, threadPool fine UI thread is blocked
heartbeat continues, threadPool=STARVED thread-pool starvation (e.g. sync-over-async)
heartbeat continues, both fine, inTest climbing the test's own await never completes — a test bug
large gcPauseDelta a GC pause, not a hang
no heartbeat line at all the whole process/runtime stopped (kernel, GC, host)

The heartbeat runs on a dedicated thread, not a timer or the thread pool — a pool-starvation hang must still produce output, otherwise it is indistinguishable from a fully frozen process. That distinction is the entire point of the instrument.

Enabled automatically under IS_CI; locally it is off unless you set UNO_TEST_STALL_MONITOR_INTERVAL_SECONDS.

2. stall-watchdog.sh — out-of-process stack capture

build/test-scripts/stall-watchdog.sh, wired into the macOS and Linux drivers.

Watches the console log. When it goes quiet past a threshold (default 180 s) it captures, while the process is still stuck:

  • dotnet-stack report — managed stacks
  • macOS: sample <pid> 10 — native stacks for every thread, including AppKit/CoreAnimation frames that managed stacks cannot show
  • Linux: eu-stack, /proc/<pid>/status, /wchan, and per-thread stat/wchan
  • ps snapshot, and the log tail so the capture records which test was running

It re-arms, so a run that stalls three times yields three captures (capped, default 6). Published as a new runtime-tests-desktop-skia-{macos,linux[-framebuffer]}-diagnostics artifact via condition: always() + continueOnError: true.

UNO_WATCHDOG_HARD_TIMEOUT_SECONDS (default 3300 s = 55 min, against the 60-minute job wall) captures a final snapshot and then SIGTERMs the app so the results XML and failed-test list are still written. 55 min was chosen deliberately: the longest observed successful macOS run is ~52 min, so this rescues diagnostics from runs that would have been killed at 60 while leaving every currently-passing run untouched.

3. macOS driver no longer aborts on a non-zero app exit

macos-skia-runtime-tests.sh ran under set -e, so a crash or non-zero exit skipped list-failed entirely and the retry re-ran the whole ~8.5k-test suite. It now captures the exit code and continues, matching what the Linux driver already does. (fail-empty still fails the build when no results could be read, so a crash with no results is still red.)

Validation ✅

Runtime — stall-watchdog.sh executed end-to-end against a simulated stalling process on Ubuntu 24.04 (WSL), driving two distinct stalls plus a hard-timeout case:

=== TEST 1: two stalls, observe-only ===
captures: 2 (one per stall, proving re-arm works)
  stall-01-…: context.txt log-tail.txt proc-status.txt proc-threads.txt proc-wchan.txt ps.txt
  stall-02-…: context.txt log-tail.txt proc-status.txt proc-threads.txt proc-wchan.txt ps.txt
--- log-tail.txt of first capture ---
Running test Alpha_3                     <- correctly identifies the test that was running
--- watchdog output ---
[watchdog] dotnet-stack install failed (continuing)   <- degrades gracefully without the tool
=== TEST 2: hard timeout ===
RESULT: app terminated by watchdog (hard timeout OK)

Compile — SamplesApp.Skia.csproj builds clean (net10.0, 0 errors). Verified the new type is actually in the output rather than silently excluded: TestRunStallMonitor, [stall-monitor], UnoTestStallMonitor and STARVED(> are all present in SamplesApp.Skia.dll.

Not validated at runtime: the in-process heartbeat has not run on a real macOS/Linux CI agent — that only happens once this is merged. It is logging-only and disabled off-CI, so the blast radius is a few extra stdout lines per run.

Notes for reviewers

  • The two Linux stages (X11 and Framebuffer) share one template, so the diagnostics artifact name is suffixed with testResultLabel to avoid a collision. (The pre-existing …-linux-failures artifact is not suffixed and so does collide between those two stages — flagging it, not fixing it here.)
  • The watchdog never exits non-zero and every capture step is individually tolerant: it observes a run and must not be able to fail one.
  • Cost when nothing stalls: one stdout line per 30 s, plus a pgrep and a stat per 15 s.

PR Checklist ✅

  • 🧪 Added Runtime tests, UI tests, or a manual test sample (for bug fixes / features, if applicable) — N/A, CI diagnostics; validated by executing the watchdog against a simulated stall (above)
  • 📚 Docs have been added/updated following the documentation template (for bug fixes / features) — N/A, no user-facing behaviour change
  • 🖼️ Validated PR Screenshots Compare Test Run results.
  • ❗ Contains NO breaking changes
  • 👀 Reviewed 2 other open pull requests (optional but appreciated!)

Update: two defects found by running this instrumentation against real CI data

Both instruments have now been exercised against the macOS runs this PR's own CI produced. Two
things prevented them from answering the question they were built for; both are fixed here.

1. The watchdog could never fire (abb52d5)

The watchdog used the console log's mtime as the liveness signal — but the in-process heartbeat
writes to that same log every 30 s. The file is therefore never quiet for the 180 s threshold, so
no capture could ever happen. The two instruments cancelled each other out.

This is not a theoretical interaction. Build 229532, attempt 1 — a full instrumented suite — hit
a real freeze and reported it correctly:

19:07:08 [stall-monitor] STALL elapsed=00:29:06 inTest=00:02:16 dispatcher=35ms ...
19:10:09 [stall-monitor] STALL elapsed=00:32:07 inTest=00:05:16 dispatcher=54ms ...

The runtime-tests-desktop-skia-macos-diagnostics artifact for that build contains no stacks.
The one run that reproduced the freeze under instrumentation still produced no evidence of it.

Progress is now the count of test-start lines, which the heartbeat does not affect. Verified against
a process that stalls while a heartbeat keeps writing — unchanged watchdog captures nothing, this
one captures the stall.

2. The dispatcher was probed at the wrong priority (954ff36)

The probe was dispatcher.RunAsync(...) — normal priority. Nearly every wait in the runtime
tests funnels through WindowHelper.WaitForIdle, which enqueues at idle priority: the lowest of
NativeDispatcher's four queues, and one that is served only when every higher queue is empty
(NativeDispatcher.DispatchItems, for (var p = 0; p <= 3; p++)). A steady stream of
normal-priority work leaves the normal probe reporting single-digit milliseconds while every test
wait blocks indefinitely.

The same build shows exactly that shape. Throughout a 5m16s freeze in
Given_TextBlock.When_Focus_Changes_Selection_Is_Not_Shown — a test whose only waits are
WaitForIdle and WaitForRender — every instrument reported healthy:

signal during the freeze
dispatcher (normal priority) 31–60 ms
threadPool 0 ms
gcPauseDelta 0 ms
heartbeat itself never missed a 30 s tick

So the freeze is not a blocked UI thread, not GC, not pool starvation, and not a stopped
process — the four things this monitor could already distinguish. The idle queue was the one thing
it did not measure, and it is the queue every one of those waits depends on.

dispatcherIdle= now reports it. One probe stays outstanding at a time and its age is reported, so
a blocked queue neither piles up work nor hides how long it has been blocked.

Why this matters for #24005

#24005 is blocked on "no stack dump exists for a stalled process". With these two fixes, one
instrumented macOS run should settle it:

  • dispatcher healthy + dispatcherIdle=BLOCKED(...) → the idle queue is starved; WaitForIdle
    can never return, and the follow-up question is what floods the higher-priority queues on macOS.
  • both healthy → the hang is inside the test's own await, and the watchdog's sample/dotnet-stack
    captures (which can now actually fire) say where.

Added validation

  • Runtime, watchdog — fail-before/pass-after against a process that stalls while a heartbeat
    keeps writing to the log: unchanged script captures 0, fixed script captures the stall
    (capturing diagnostics (no test started for 5s)).
  • Runtime, idle probe — SamplesApp.Skia.Generic on Windows, Given_ContentPresenter, monitor
    at a 2 s interval: dispatcher=0..67ms dispatcherIdle=0..52ms across 12 heartbeats, run exits 0.
  • Compile — SamplesApp.Skia.csproj, net10.0, 0 warnings / 0 errors.

Still not validated on a macOS agent — that is what merging this is for.

Copilot AI lite review requested due to automatic review settings August 7, 2026 14:42
@github-actions github-actions Bot added area/build Categorizes an issue or PR as relevant to build infrastructure area/automation Categorizes an issue or PR as relevant to project automation labels Aug 7, 2026
@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 5m 32s —— View job


PR Review — feat(ci): Capture diagnostics when runtime tests stall

  • Gather context
  • Read changed files
  • Analyze for correctness, async discipline, code style issues
  • Post inline comments
  • Update summary

Overall verdict: ✅ Approve with minor fixes

The design is sound and well-reasoned. The two-instrument approach (in-process heartbeat + out-of-process watchdog) correctly separates the diagnostic signals, and the graceful-degradation story (|| true everywhere, continueOnError: true, never exits non-zero) is solid. The macOS set +e fix for the non-zero exit abort is a clear correctness improvement.

Issues found — 3 minor, 2 nits

Minor — TestRunStallMonitor.cs

# Severity Line Summary
1 Minor L158–168 ManualResetEventSlim in ProbeThreadPool() is never disposed — leaks a kernel wait handle per tick and leaves a latent ObjectDisposedException risk in the thread-pool callback on the timeout path. Can be disposed on the success and queue-failed paths; timeout path must stay unmanaged.
2 Minor L203–207 _disposed guard in Dispose() is not volatile / not atomic — two concurrent callers can both pass the check, leading to double-Cancel + double-Dispose() on the CancellationTokenSource. Use Interlocked.CompareExchange on an int flag.
3 Minor L212 _thread.Join(2 s) is shorter than ProbeTimeout (5 s), so _cts.Dispose() can be called while the background thread is mid-probe. The practical race is near-zero (cancelled token short-circuits before the next WaitHandle access), but the join should cover the maximum blocking time.

Nit — shell scripts

# Severity Location Summary
4 Nit stall-watchdog.sh L138 Hard-timeout capture bypasses MAX_CAPTURES, so total captures can reach MAX_CAPTURES + 1. Intentional, but a one-line comment prevents future confusion.
5 Nit macos-skia-runtime-tests.sh L41 APP_EXIT is captured and echoed but not acted on — add a comment confirming it's informational only, to avoid a "forgotten check" read-later.

Cross-cutting notes

  • #nullable enable is correctly present at the top of the new TestRunStallMonitor.cs. The UnitTestsControl.cs field _stallMonitor is declared without ? (nullable-oblivious context, no #nullable enable in that file) — consistent with the pre-existing style of that file.
  • The Interlocked.Exchange(ref _stallMonitor, null)?.Dispose() pattern in UnitTestsControl.cs is correct and ensures only one caller reaches Dispose() from the outside; the fix in finding Paths are either not shown or shown not as in the UWP Designer #2 adds the same safety inside the class.
  • No event Action / event Action<T> — not applicable here.
  • No allocations in hot paths beyond what the diagnostic intent requires.
  • Conventional Commits format (feat(ci):) is correct.
  • The two Linux stages sharing a single template with testResultLabel-suffixed artifact names is noted correctly in the PR description.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves diagnosability of Desktop Skia runtime-test stalls on macOS and Linux by adding (1) an in-process heartbeat during test execution and (2) an out-of-process watchdog that captures stacks and publishes them as CI artifacts, even on failure/timeouts.

Changes:

  • Add TestRunStallMonitor heartbeat logging during runtime test execution (CI-enabled by default).
  • Add stall-watchdog.sh and wire it into macOS/Linux runtime-test drivers to capture diagnostics when console output stalls, plus a hard-timeout termination path.
  • Publish new “stall diagnostics” artifacts from macOS/Linux CI jobs using condition: always().

Review summary (verdict + counts):

  • Verdict: requires changes
  • Issues found: 2 bugs, 1 performance

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/SamplesApp/SamplesApp.UnitTests.Shared/Controls/UnitTest/UnitTestsControl.cs Starts/stops the stall monitor and updates current test name during execution.
src/SamplesApp/SamplesApp.UnitTests.Shared/Controls/UnitTest/TestRunStallMonitor.cs New heartbeat monitor that probes dispatcher + thread pool and logs periodic status.
build/test-scripts/stall-watchdog.sh New out-of-process watchdog that detects log silence and captures managed/native diagnostics.
build/test-scripts/macos-skia-runtime-tests.sh Runs watchdog alongside tests, tees console log, and preserves post-run failed-test list generation.
build/test-scripts/linux-skia-runtime-tests.sh Runs watchdog alongside tests, tees console log (both Xvfb and non-Xvfb paths).
build/ci/tests/.azure-devops-tests-macos-skia.yml Publishes macOS stall diagnostics artifact unconditionally.
build/ci/tests/.azure-devops-tests-linux-skia.yml Publishes Linux stall diagnostics artifact unconditionally (with result-label suffix).
Suppressed comments (1)

build/test-scripts/stall-watchdog.sh:85

  • The Darwin capture path also relies on timeout, which may be unavailable on the macOS hosted image. If timeout is missing, both sample and vmmap captures can be skipped entirely, which defeats the purpose of macOS diagnostics.
		Darwin)
			# Native stacks for every thread, including AppKit/CoreAnimation frames that
			# managed stacks cannot show. This is the artefact for a host-level livelock.
			timeout 120 sample "$pid" 10 -f "$dir/sample.txt" >/dev/null 2>&1 \
				|| log "sample failed"
			timeout 60 vmmap --summary "$pid" > "$dir/vmmap.txt" 2>&1 || true
			;;

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread build/test-scripts/stall-watchdog.sh Resolved
Comment thread build/test-scripts/stall-watchdog.sh Resolved
@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 226424 has failed on Uno.UI - CI.

kazo0 added a commit that referenced this pull request Aug 8, 2026
When_Reorder_DragDrop_ScrollsAwayFromDraggedItem_KeepsExtentAndPositions
fails intermittently on the iOS Skia CI leg, always on the mid-drag
extent assertion and always with the same values: ExtentHeight 1560
instead of 1440, exactly 3 phantom 40px rows. Observed on master build
225991 (attempt 1, passed on retry), PR #24007 build 226424, and PR
#24012 build 226524 where 5/5 stage attempts failed on this single test
across different hosted agents.

The identical values every failure point at a timing-dependent residue
of the extent estimation fixed by #23946 surfacing on the iOS simulator
profile — tracked in #24013. Desktop and Android Skia legs keep running
the test, so the regression coverage #23946 added stays in place.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NsWEWZN3E2AtwQm7UU1cFm
kazo0 added a commit that referenced this pull request Aug 9, 2026
When_Reorder_DragDrop_ScrollsAwayFromDraggedItem_KeepsExtentAndPositions
fails intermittently on the iOS Skia CI leg, always on the mid-drag
extent assertion and always with the same values: ExtentHeight 1560
instead of 1440, exactly 3 phantom 40px rows. Observed on master build
225991 (attempt 1, passed on retry), PR #24007 build 226424, and PR
#24012 build 226524 where 5/5 stage attempts failed on this single test
across different hosted agents.

The identical values every failure point at a timing-dependent residue
of the extent estimation fixed by #23946 surfacing on the iOS simulator
profile — tracked in #24013. Desktop and Android Skia legs keep running
the test, so the regression coverage #23946 added stays in place.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NsWEWZN3E2AtwQm7UU1cFm
(cherry picked from commit c0ce315)

# Conflicts:
#	src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Controls/Given_ListViewBase.cs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think a more effective method would be enforce a per-test hard timeout, like 1min, on the engine level
for heavy tests, we can adjust case-by-case with [TimeoutAttribute]
(which you have mentioned in an issue for uno7)

Copilot AI review requested due to automatic review settings August 22, 2026 09:47
@MartinZikmund
MartinZikmund force-pushed the dev/mazi/ci-stall-diagnostics branch from f2fd5c6 to 77ecb59 Compare August 22, 2026 09:47
@github-actions

github-actions Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 3m 32s —— View job


PR Review — feat(ci): Capture diagnostics when runtime tests stall

  • Gather context
  • Read changed files
  • Analyze for correctness, async discipline, code style issues
  • Post inline comments
  • Update summary

Overall verdict: ✅ Approve with minor fixes

The design is sound. The two-instrument split (in-process heartbeat on a dedicated thread + out-of-process watchdog writing artifacts) correctly separates the diagnostic signals, and the graceful-degradation story (|| true everywhere, continueOnError: true, never exits non-zero) is solid. The macOS set +e fix is a real correctness improvement.

The prior review found the three issues that matter before merge. I've confirmed them and added one new finding.

Issues — 1 new, 3 confirmed from prior review

New inline comment posted:

Severity File Line Summary
Minor stall-watchdog.sh L74 timeout is not reliably available on macOS (it's GNU coreutils, not a macOS built-in). Without it, dotnet-stack report and sample run unguarded — when the target is stuck in a kernel or GC state these tools can hang, freezing the watchdog instead of completing the capture.

Confirmed from prior inline review (still open):

Severity File Lines Summary
Minor TestRunStallMonitor.cs L158–168 ManualResetEventSlim in ProbeThreadPool() is never disposed — the timeout path must stay unmanaged, but the success and queue-failed paths can and should call Dispose().
Minor TestRunStallMonitor.cs L203–207 _disposed is a plain bool with no synchronization; two concurrent callers can both pass the guard and double-cancel/double-dispose the CancellationTokenSource. Use Interlocked.CompareExchange on an int field.
Minor TestRunStallMonitor.cs L212 _thread.Join(2 s) is shorter than ProbeTimeout (5 s); _cts.Dispose() can be called while the background thread is mid-probe. Raise to ≥ 10 s.

Cross-cutting notes

  • #nullable enable is correctly present; no event Action / event Action<T> violations.
  • The Interlocked.Exchange(ref _stallMonitor, null)?.Dispose() pattern in UnitTestsControl.cs ensures only one external caller reaches Dispose() — the fix in finding Paths are either not shown or shown not as in the UWP Designer #2 adds the same safety inside the class, which completes the picture.
  • The two Linux stages sharing one template with testResultLabel-suffixed artifact names is correctly called out in the PR description; not a bug introduced here.
  • Conventional Commits format (feat(ci):) is correct.

Comment thread build/test-scripts/stall-watchdog.sh Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Suppressed comments (2)

build/test-scripts/stall-watchdog.sh:76

  • stall-watchdog.sh relies on timeout(1) for all captures, but macOS agents typically don’t ship timeout (see the existing comment in ios-uitest-run.sh). When timeout is missing, the watchdog will skip dotnet-stack/sample/vmmap captures, which defeats the purpose of the diagnostics on macOS. Add a wrapper that uses timeout/gtimeout when available and otherwise enforces a timeout via a background watchdog + kill.
	# Managed stacks — the primary artefact for a managed deadlock or a hung await.
	if command -v dotnet-stack >/dev/null 2>&1; then
		timeout 120 dotnet-stack report --process-id "$pid" > "$dir/dotnet-stack.txt" 2>&1 \
			|| log "dotnet-stack failed (see $dir/dotnet-stack.txt)"
	fi

src/SamplesApp/SamplesApp.UnitTests.Shared/Controls/UnitTest/TestRunStallMonitor.cs:160

  • ProbeThreadPool allocates a new ManualResetEventSlim each tick but never disposes it. Since Wait(...) can allocate an underlying WaitHandle, this can unnecessarily retain OS handles until GC/finalization during long test runs. Dispose the event and guard the queued callback against Set-after-dispose races.
	private static string ProbeThreadPool()
	{
		var sw = Stopwatch.StartNew();
		var signal = new ManualResetEventSlim(false);

@unodevops

Copy link
Copy Markdown
Contributor

@MartinZikmund
MartinZikmund changed the base branch from master to feature/breakingchanges August 22, 2026 14:56
@MartinZikmund
MartinZikmund force-pushed the dev/mazi/ci-stall-diagnostics branch from 77ecb59 to 8c4c2c2 Compare August 22, 2026 14:57
@github-actions

github-actions Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 4m 37s —— View job


PR Review — feat(ci): Capture diagnostics when runtime tests stall

  • Gather context
  • Read changed files
  • Analyze for correctness, async discipline, code style issues
  • Post inline comments
  • Update summary

Overall verdict: fix-first (3 minor, 2 nits)

The two-instrument design is sound: dedicated-thread heartbeat + out-of-process watchdog cleanly separates the four diagnostic signals described in the PR. The macOS set +e fix is a clear correctness improvement. Graceful degradation (|| true, continueOnError: true, watchdog never exits non-zero) is correctly applied throughout.

Three issues need to land before merge; two more are nits.

Issues

# Severity Location Summary
1 Minor TestRunStallMonitor.cs L168 ManualResetEventSlim leaked on every tick — dispose on success and queue-failed paths; the timeout path must stay unmanaged (work item may still call Set())
2 Minor TestRunStallMonitor.cs L210 _disposed is a plain bool — two concurrent callers can both pass the guard and double-cancel/double-dispose the CancellationTokenSource; use Interlocked.CompareExchange on an int field
3 Minor stall-watchdog.sh L74 timeout is GNU coreutils, not a macOS built-in — when absent, dotnet-stack, sample, and vmmap run unguarded and can freeze the watchdog itself; add a gtimeout/timeout/bare fallback wrapper
4 Nit TestRunStallMonitor.cs L212 _thread.Join(2 s) is shorter than ProbeTimeout (5 s) — raise to ≥ 10 s so _cts.Dispose() cannot be called while the background thread is mid-probe
5 Nit macos-skia-runtime-tests.sh L61 / linux-skia-runtime-tests.sh L56 kill $WATCHDOG_PID without a subsequent wait leaves the watchdog as a zombie during artifact publishing

Cross-cutting notes

  • #nullable enable is correctly present in TestRunStallMonitor.cs. The _stallMonitor field in UnitTestsControl.cs omits ? — consistent with that file's nullable-oblivious style (no #nullable enable at the top).
  • The Interlocked.Exchange(ref _stallMonitor, null)?.Dispose() pattern in UnitTestsControl.cs correctly ensures only one external caller reaches Dispose(). Issue Paths are either not shown or shown not as in the UWP Designer #2 adds the same safety inside the class itself.
  • No event Action / event Action<T> violations.
  • Conventional Commits format (feat(ci):) is correct.
  • The Linux artifact name being suffixed with testResultLabel (preventing collision between the two Linux stages) is correctly noted in the PR description; the pre-existing linux-failures collision is not introduced here.

@MartinZikmund
MartinZikmund changed the base branch from feature/breakingchanges to master September 2, 2026 20:02
@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 231689 has failed on Uno.UI - CI.

@morning4coffe-dev morning4coffe-dev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The monitor introduces a thread requirement on a test host that also runs on ordinary browser-WASM. That needs a platform-safe path before approval. The captured WASM CI log also ends without a result file, although it does not expose a managed stack trace, so I am not attributing every CI failure solely from its red status.

Name = "UnoTestStallMonitor",
Priority = ThreadPriority.AboveNormal,
};
_thread.Start();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Do not start this Thread on the single-threaded WASM host. TryStart is enabled by IS_CI by default and has no browser/thread-capability guard; UnitTestsControl.RunTests calls it at lines 756-758 before its try/finally and before test enumeration. .NET's thread-disabled runtime rejects Thread.Start (see https://github.com/dotnet/runtime/blob/v10.0.0/src/mono/mono/metadata/threads.c#L4818-L4829). A diagnostic feature must not prevent the test run or result publication. Keep this implementation for supported hosts and provide an explicit browser-safe/disabled path.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f4be2c4. TryStart now returns null up front on OperatingSystem.IsBrowser(), logging [stall-monitor] disabled: no dedicated threads on this runtime. Separately, any exception while starting the monitor is caught and logged as disabled, so a diagnostic can never keep the run from starting or publishing results on any other host either.

Same commit picks up the bot threads: capture tools are bounded through a with_timeout helper (timeout, then gtimeout, then a manual kill) since macOS agents may have neither; the watchdog is waited after kill; Dispose joins for 3x the probe timeout and only disposes the token source once the loop has actually exited; the thread-pool probe uses a TaskCompletionSource instead of an undisposed ManualResetEventSlim.

Runtime check on Skia desktop Release with a 2 s interval over Given_ContentPresenter: 11 heartbeat lines (dispatcher, dispatcherIdle, threadPool all reporting), clean stop, 270/270 passed.

@MartinZikmund
MartinZikmund force-pushed the dev/mazi/ci-stall-diagnostics branch from 0feff49 to f4be2c4 Compare September 23, 2026 07:41
@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 3m 30s —— View job


PR Review — feat(ci): Capture diagnostics when runtime tests stall

  • Gather context (diff since last review, prior findings, WASM thread-safety concern)
  • Read changed files
  • Analyze for correctness, async discipline, code style issues
  • Post inline comments
  • Update summary

Overall verdict: ✅ Approve

This review covers the latest commit, f4be2c4a ("Keep the stall monitor off single-threaded WASM"), pushed since the last round. It resolves the outstanding blocker and most of the previously-reported minor issues:

Fixed in this commit:

  • P1 blocker (morning4coffe-dev, CHANGES_REQUESTED) — TestRunStallMonitor.TryStart now checks OperatingSystem.IsBrowser() before starting the dedicated thread and returns null (logging instead) on that runtime. The whole constructor call is also wrapped in try/catch so any other host that rejects Thread.Start degrades to "disabled" instead of failing RunTests before its try/finally (UnitTestsControl.cs:756) is even entered.
  • ManualResetEventSlim leak in ProbeThreadPool() — replaced with a TaskCompletionSource(RunContinuationsAsynchronously). This is a better fix than the disposal patch suggested earlier: nothing needs disposing, and there's no ObjectDisposedException risk on the timeout path since a Task can be safely observed/discarded without disposal.
  • _thread.Join shorter than the worst-case probe time — raised from 2 s to ProbeTimeout * 3 + 2s (17 s), correctly covering the three sequential probes (ProbeDispatcher, ProbeIdleQueue, ProbeThreadPool) added across earlier commits. _cts.Dispose() is now also conditioned on the join succeeding, avoiding disposing the token source under a still-running loop.
  • macOS missing timeout(1) — stall-watchdog.sh now has a with_timeout wrapper that falls back to gtimeout, then to a manual background-kill implementation, applied to all dotnet-stack/sample/vmmap/eu-stack calls.
  • Watchdog zombie process — both macos-skia-runtime-tests.sh and linux-skia-runtime-tests.sh now wait $WATCHDOG_PID after kill.

Left as-is (previously reported, non-blocking):

  • _disposed is still a plain bool, not Interlocked-guarded — practically safe here since the only caller reaches Dispose() via Interlocked.Exchange(ref _stallMonitor, null)?.Dispose() in UnitTestsControl.cs:793, so double-entry isn't currently reachable.
  • ProbeDispatcher() still enqueues a fresh probe every tick rather than reusing the "one outstanding probe" pattern ProbeIdleQueue() uses — could understate how long the normal-priority queue was blocked if it fires a burst on unblock.
  • Generic catch (Exception e) clauses in Loop()/ProbeDispatcher()/GetProcessIdSafe() — intentional per the "must never fail the run it's observing" design, but flagged again by the code-quality bot each round.

New nit posted inline: Dispose() now leaves _cts undisposed (leaked) when the thread doesn't stop within the 17 s join budget — a reasonable trade-off given the alternative (disposing under a live loop), just noting it's intentional.

Cross-cutting notes

  • #nullable enable correctly present; no event Action/event Action<T> violations.
  • Conventional Commits format is correct across all commits, including the new fix(ci):.
  • Validation method: code-review only in this pass (no local build/runtime execution performed). The PR author's own validation (macOS build 229772, WASM concern now addressed by the browser guard) is the runtime evidence of record.

@unodevops

Copy link
Copy Markdown
Contributor

@MartinZikmund
MartinZikmund force-pushed the dev/mazi/ci-stall-diagnostics branch from f4be2c4 to 1e6c129 Compare September 24, 2026 08:30
@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 1m 42s —— View job


PR Review — feat(ci): Capture diagnostics when runtime tests stall

  • Gather context (diff since last review: 0e51c2b1 "Keep one dispatcher probe outstanding", 1e6c129d "Note hard-timeout capture skips the cap")
  • Read changed files
  • Analyze for correctness, async discipline, code style issues
  • Post inline comments
  • Update summary

Overall verdict: ✅ Approve

This review covers the two commits pushed since the last round (0e51c2b1, 1e6c129d). Both are targeted fixes for issues raised in prior reviews, and both hold up under inspection — no new findings, no inline comments to post.

0e51c2b1 — "Keep one dispatcher probe outstanding"

  • Extracts the idle-queue probe's "exactly one outstanding probe" pattern into a shared ProbeQueue(Func<Task>? probe, ref Task? pending, ref long startedAt) and reuses it for both ProbeDispatcher() and ProbeIdleQueue(). This resolves the previously-flagged accumulation problem where the normal-priority probe queued a fresh task every tick regardless of whether the prior one had completed — a burst on unblock could previously understate how long the dispatcher had actually been stuck. Traced through the logic: when pending is incomplete, the method returns immediately with the accumulated block duration without enqueuing more work; when it completes, it re-probes and records a fresh startedAt. Correct in both branches, including the exception path (pending reset to null).
  • _disposed changed from a plain bool to int guarded by Interlocked.Exchange(ref _disposed, 1), resolving the double-Cancel/double-Dispose race flagged in every prior round. This is now correct in isolation, independent of the Interlocked.Exchange(ref _stallMonitor, null)?.Dispose() guard already present in UnitTestsControl.cs:793.
  • Verified the _thread.Join(ProbeTimeout * 3 + TimeSpan.FromSeconds(2)) budget (17s) still covers the worst case under the new logic: a probe only blocks for the full ProbeTimeout on its first call (when pending is null); once parked as "outstanding", later ticks return immediately. So the worst single tick — all three probes freshly starting at once — is still bounded at 3 × 5s, matching the join budget. No regression there.

1e6c129d — "Note hard-timeout capture skips the cap"

  • One-line comment (# One-shot and terminal, so it deliberately ignores MAX_CAPTURES.) on the hard-timeout capture in stall-watchdog.sh, exactly the nit requested in the 2026-08-07 review. No behavior change.

Cross-cutting notes

  • Conventional Commits format (fix(ci):, chore(ci):) is correct.
  • All previously-blocking findings across this PR's review history are now resolved: the WASM thread guard, the watchdog's mtime-vs-progress liveness signal, the timeout/gtimeout fallback, the zombie watchdog process (wait after kill), the ManualResetEventSlim leak (replaced with TaskCompletionSource), the join-timeout budget, and now the _disposed race and dispatcher-probe accumulation.
  • Remaining items are the ones already called out as intentional trade-offs in the 2026-09-23 review and not reopened here: generic catch (Exception) clauses (by design — "the monitor must never fail a run it only observes") and _cts staying undisposed if _thread.Join times out (accepted over disposing under a possibly-still-running loop).
  • No event Action/event Action<T> violations, no DependencyProperty changes, no XAML changes in this diff.
    · branch dev/mazi/ci-stall-diagnostics

@MartinZikmund

Copy link
Copy Markdown
Member Author

🤖 Addressed PR comments up to this point

Rebased onto current master.

  • @morning4coffe-dev (changes requested, WASM thread requirement): fixed in c1bc601 (rebased f4be2c4a504), where the monitor is skipped on OperatingSystem.IsBrowser() and any startup failure is logged as disabled. See the inline reply; could you take another look?
  • Bot threads: the dispatcher probe now keeps a single outstanding probe and Dispose is Interlocked-guarded (0e51c2b). Added a hard-timeout comment (1e6c129). Everything else was already covered by the earlier commit or is intentional, and each has an inline reply.

Comment on lines +209 to +213
catch (Exception e)
{
pending = null;
return $"error({e.GetType().Name})";
}
@unodevops

Copy link
Copy Markdown
Contributor

MartinZikmund and others added 6 commits October 3, 2026 10:48
macOS and Linux desktop Skia runtime tests freeze mid-test and are killed
by the 60-minute job timeout, leaving no evidence of what blocked.

Adds two complementary instruments:

- TestRunStallMonitor: an in-process heartbeat on a dedicated thread that
  separately probes the UI dispatcher and the thread pool each tick. A
  dedicated thread is used so pool starvation cannot silence it, which is
  what separates "UI thread blocked" from "pool starved" from "process
  frozen" (no heartbeat line at all). Enabled on CI, opt-in locally via
  UNO_TEST_STALL_MONITOR_INTERVAL_SECONDS.

- stall-watchdog.sh: watches the console log and, once it goes quiet,
  captures managed stacks (dotnet-stack), native stacks (sample on macOS,
  eu-stack and /proc on Linux) and process state, re-arming for each
  subsequent stall. Optionally terminates the app before the job wall so
  results and the failed-test list are still written.

The macOS driver no longer aborts on a non-zero app exit, so the
failed-test list is written and a retry can run only the failures instead
of the whole suite.

closes #24006
refs #24005, #23967

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01RgHbZ4EHYrK6uTkPTtKbq8
The watchdog treated the console log's mtime as the liveness signal, but the
in-process stall monitor writes a heartbeat to that same log every 30s. The file
is therefore never quiet for the 180s threshold and no capture could ever fire.

Build 229532 shows the consequence: the heartbeat correctly reported
`STALL ... inTest=00:05:16`, and the diagnostics artifact contains no stacks --
the one run that reproduced the freeze under instrumentation still produced no
evidence of it.

Progress is now the count of test-start lines, which the heartbeat does not
affect. Verified against a process that stalls while a heartbeat keeps writing:
unchanged watchdog captures nothing, this one captures the stall.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BGKr3vEBkqQJA6Su8NQMXq
The monitor probed the dispatcher at normal priority only. Nearly every wait in
the runtime tests funnels through `WindowHelper.WaitForIdle`, which enqueues at
idle priority -- the lowest of the dispatcher's four queues, served only when
every higher queue is empty. A steady stream of normal-priority work leaves the
normal probe reporting single-digit milliseconds while every test wait blocks,
so the existing signal cannot see that case at all.

This is not hypothetical. Build 229532 stalled 5m16s inside a test whose only
waits are `WaitForIdle`/`WaitForRender`, and reported `dispatcher=31ms`,
`threadPool=0ms`, `gcPauseDelta=0ms` throughout -- every instrument healthy while
nothing progressed. The idle queue was the one thing not measured.

One probe stays outstanding at a time and its age is reported, so a blocked queue
neither piles up work nor hides how long it has been blocked.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01BGKr3vEBkqQJA6Su8NQMXq
The monitor starts a dedicated thread, which the browser runtime
refuses. It now stays disabled there, and any failure to start is
logged instead of breaking the run it observes. Also bound capture
tools where macOS has no timeout(1), reap the watchdog after killing
it, and stop disposing the token source under a live probe loop.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01WHHcu5U9N25wvKGNFCrpJm
The normal-priority dispatcher probe now shares the idle probe's
one-outstanding-probe logic, so a blocked queue reports how long it has
been stuck instead of piling up probes. Dispose guards with Interlocked.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Copilot AI lite review requested due to automatic review settings October 3, 2026 08:48
@MartinZikmund
MartinZikmund force-pushed the dev/mazi/ci-stall-diagnostics branch from 1e6c129 to 29c23d6 Compare October 3, 2026 08:48
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @MartinZikmund's task in 1m 2s —— View job


PR Review — feat(ci): Capture diagnostics when runtime tests stall

  • Gather context (diff since last review)
  • Read changed files
  • Analyze for correctness, async discipline, code style issues
  • Post inline comments
  • Update summary

Overall verdict: ✅ Approve — no changes since last review

I checked the current branch state (HEAD at 29c23d6c) against the content reviewed in the previous rounds (2026-09-23/24) and confirmed by @morning4coffe-dev's approval on 2026-09-28. No new commits have landed since then — this trigger did not introduce any diff to review. The 7 changed files match the SHAs already evaluated:

  • TestRunStallMonitor.cs (284 lines) — browser guard via OperatingSystem.IsBrowser(), TryStart wrapped in try/catch so a startup failure degrades to disabled, ProbeQueue shared between the dispatcher and idle-queue probes (one-outstanding-probe pattern, no accumulation), thread-pool probe uses TaskCompletionSource (no leaked ManualResetEventSlim), _disposed is Interlocked-guarded, Dispose() joins for ProbeTimeout * 3 + 2s and only disposes _cts if the join succeeds.
  • stall-watchdog.sh (184 lines) — progress is keyed on test-start count rather than log mtime (so the in-process heartbeat and the watchdog no longer cancel each other out), with_timeout falls back timeout → gtimeout → manual background-kill, hard-timeout capture has its MAX_CAPTURES-bypass documented.
  • macos-skia-runtime-tests.sh / linux-skia-runtime-tests.sh — non-zero app exit no longer aborts the script, watchdog is waited after kill (no zombie).

All issues raised across the five prior review passes (Copilot, github-actions bot, github-code-quality, morning4coffe-dev's WASM-thread blocker) have been resolved or explicitly accepted as intentional trade-offs by the author, with inline replies on each thread:

  • Generic catch (Exception) clauses — intentional (monitor must never fail the run it observes).
  • _cts left undisposed if _thread.Join times out — intentional (avoids disposing under a possibly-still-running loop).

Since there's nothing new in this diff, I have no additional findings to post inline.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +126 to +127
find_pid() {
pgrep -f "$PROC_PATTERN" 2>/dev/null | head -n 1
progress_count() {
local f=$1
[ -f "$f" ] || { echo 0; return; }
grep -c "$PROGRESS_PATTERN" "$f" 2>/dev/null || echo 0
Comment on lines +43 to +44
chmod +x $BUILD_SOURCESDIRECTORY/build/test-scripts/stall-watchdog.sh
$BUILD_SOURCESDIRECTORY/build/test-scripts/stall-watchdog.sh \
$BUILD_SOURCESDIRECTORY/build/test-scripts/stall-watchdog.sh \
"$APP_LOG" "$UITEST_DIAGNOSTICS_DIR" "dotnet.*SamplesApp\.dll" &
WATCHDOG_PID=$!
trap 'kill $WATCHDOG_PID 2>/dev/null || true' EXIT
Comment on lines +32 to +37
export UITEST_DIAGNOSTICS_DIR=$BUILD_SOURCESDIRECTORY/build/uitests-diagnostics
export UNO_WATCHDOG_HARD_TIMEOUT_SECONDS=${UNO_WATCHDOG_HARD_TIMEOUT_SECONDS:-3300}
mkdir -p $UITEST_DIAGNOSTICS_DIR
APP_LOG=$UITEST_DIAGNOSTICS_DIR/runtime-tests-console.log

chmod +x $BUILD_SOURCESDIRECTORY/build/test-scripts/stall-watchdog.sh
$BUILD_SOURCESDIRECTORY/build/test-scripts/stall-watchdog.sh \
"$APP_LOG" "$UITEST_DIAGNOSTICS_DIR" "dotnet.*SamplesApp\.dll" &
WATCHDOG_PID=$!
trap 'kill $WATCHDOG_PID 2>/dev/null || true' EXIT
Copilot AI lite review requested due to automatic review settings October 3, 2026 09:06
@unodevops

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +32 to +39
export UITEST_DIAGNOSTICS_DIR=$BUILD_SOURCESDIRECTORY/build/uitests-diagnostics
export UNO_WATCHDOG_HARD_TIMEOUT_SECONDS=${UNO_WATCHDOG_HARD_TIMEOUT_SECONDS:-3300}
mkdir -p $UITEST_DIAGNOSTICS_DIR
APP_LOG=$UITEST_DIAGNOSTICS_DIR/runtime-tests-console.log

chmod +x $BUILD_SOURCESDIRECTORY/build/test-scripts/stall-watchdog.sh
$BUILD_SOURCESDIRECTORY/build/test-scripts/stall-watchdog.sh \
"$APP_LOG" "$UITEST_DIAGNOSTICS_DIR" "dotnet.*SamplesApp\.dll" &
progress_count() {
local f=$1
[ -f "$f" ] || { echo 0; return; }
grep -c "$PROGRESS_PATTERN" "$f" 2>/dev/null || echo 0
Comment on lines +209 to +213
catch (Exception e)
{
pending = null;
return $"error({e.GetType().Name})";
}
Comment on lines +275 to +282
// A tick can be blocked in each of its three probes in turn; disposing the source under a live
// loop would fault its next wait.
if (_thread.Join(ProbeTimeout * 3 + TimeSpan.FromSeconds(2)))
{
_cts.Dispose();
}

Console.WriteLine($"{LogPrefix} stopped after {Format(_runElapsed.Elapsed)}");
private List<TestCaseResult> _testCases = new();
private TestRun _currentRun;
private long _scrollableHeightCallbackToken;
private TestRunStallMonitor _stallMonitor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/automation Categorizes an issue or PR as relevant to project automation area/build Categorizes an issue or PR as relevant to build infrastructure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Desktop Skia runtime-test stalls are undiagnosable: no stacks or heartbeat captured before the job timeout

5 participants