Repository navigation
feat(macos): Dedicated Metal render thread - #23594
morning4coffe-dev merged 15 commits into
Conversation
|
Claude finished @MartinZikmund's task in 5m 10s —— View job Code Review
Verdict: fix-first (draft PR, as intended — 1 crash-risk finding before this ships) SummaryThe design is sound and mirrors the Win32/X11 pattern correctly. The ObjC drawable lifecycle (
Cross-cutting notes
|
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23594/wasm-skia-net9/index.html |
|
|
8906333 to
569d9ed
Compare
|
Claude finished @MartinZikmund's task in 5m 48s —— View job Code Review
Verdict: fix-first (draft PR, as intended — issues below must be resolved before promotion) SummaryThe overall design is sound:
Cross-cutting notes
|
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23594/wasm-skia-net9/index.html |
|
|
|
Claude finished @MartinZikmund's task in 3m 58s —— View job Code Review
Verdict: fix-first (draft PR, as intended — one significant finding remains open before promotion) Progress since last reviewGood iteration — five of the six prior findings are resolved:
Remaining open findingFinding #4 (Significant): Cross-cutting notes
|
PR review triage — automated passNo code change / no new commit this pass. Branch head remains Reviewed by code inspection only — no build/test was run here; Azure Pipelines CI validates on push. Needs @MartinZikmund input (3) — left openAll three threads below raise the identical point:
Why I did not apply the suggested fix in thread 3:
This is a "needs compiling + real-device validation to trust" change, so per the debugging-discipline rules I've flagged it rather than shipping an unvalidated guess. Nothing is being auto-resolved. |
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23594/wasm-skia-net9/index.html |
|
|
|
Claude finished @morning4coffe-dev's task in 5m 44s —— View job Code Review
Verdict: fix-first (draft PR — one minor correctness finding from the new commit; the first-frame sizing question remains the last gating item before non-draft) Progress since last review (July 14)The new commit
New findings in this pass
Cross-cutting notes
|
uno_window_acquire_next_frame looked up the MTKView through contentViewController.view, which is the plain container NSView holding the rendering view, so the kind check always failed and the render thread never drew or presented a single frame. RenderThreadMetalDraw also sized the swapchain GRBackendRenderTarget from the managed XamlRoot bounds instead of the acquired texture, so any disagreement between the two (window resize) rendered the app into a sub-rect of the drawable. Restore the RetainedLayer indirection used by the legacy draw path and by X11: the app draws into the retained layer at the managed size, and only the blit targets the drawable at its own size. That also keeps the canvas stable across frames, so damage-region rendering stays enabled. Co-authored-by: Copilot <[email protected]> Copilot-Session: 232da7e5-d077-4700-95a3-673fb777537d
The render thread needs a pace, and the only rate that makes sense is the one the compositor recycles drawables at. NSScreen.maximumFramesPerSecond gives it; 0 means unknown, so the caller keeps its configured rate. Falls back to the main screen because a window that was never ordered front has no screen of its own. Also drops a stale comment claiming maximumDrawableCount is 2 — uno_window_create sets 3 — and says what actually matters about nextDrawable: it does not simply block, it gives up after ~1s and returns nil once the pool is exhausted.
…rottle it macOS is the only Skia host whose render thread had no pace. X11 and Win32 both got one in #21299; macOS was left driving frames straight off InvalidateRender, relying on nextDrawable to block until the compositor was ready. That works only while the compositor keeps up. Once the layer's drawable pool is exhausted nextDrawable does not block-and-succeed, it blocks for ~1s and returns nil — so an unpaced loop that acquires as fast as it is signalled outruns the compositor and converts every frame into a one-second stall, then retries into the same wall. On the hosted CI agents this dominated the run. Pace frame requests through FramePacer, exactly as X11 does, so acquisitions happen at most once per refresh interval. A timer drives the pace rather than the display, which keeps the render clock ticking when the display does not — an occluded window, or a headless agent. Retries of an unpresentable frame stay (dropping one permanently latches CompositionTarget's render-requested flag and hangs anything awaiting a frame) but are now paced and back off to 1s, so a window that can never present no longer spins the GPU. The backoff waits on the shutdown event, so Dispose still joins promptly. Also logs the render surface, the screen refresh rate and the resolved pace once per window, and warns when consecutive frames cannot be presented. Nothing currently records whether a drawable was ever vended, which is why this failure mode was invisible for months.
…rdown Dispose stops the pacer before disposing the events, but a timer callback already in flight can still run after Timer.Dispose returns and would then Set a disposed handle. System.Timers.Timer does not swallow that on .NET Core, so it would surface as an unhandled exception on a timer thread while a window is closing — and the runtime-test suite closes secondary windows constantly.
…lure Build 228360 timed out with 801 hard 3.05s +/- 0.05 gaps and emitted zero "could not present" warnings, which proved the previous threshold useless as a diagnostic: it only fired on the fourth consecutive failure, so any pattern of one to three would have looked identical to a healthy run. Time the acquisition instead and report the first call that fails or blocks over 100ms, then at most one report per 5s. That distinguishes "the render thread is stuck in nextDrawable" from "the render thread is idle and the time goes elsewhere" — which the previous run could not.
Reaching the Idle queue should cost microseconds. On the macOS CI leg 475 of 1504 distinct tests deterministically pay a 3.05s gap that throws nothing, which is consistent with WaitForIdle itself blocking: WaitFor only re-evaluates its deadline between awaits, so a slow await never trips the timeout it exists to enforce and the cost stays invisible. Log a throttled line when a pair of idle round-trips exceeds 500ms. This touches the shared harness rather than the macOS host on purpose — the question is whether the Idle queue is starved, which is not a macOS-specific measurement — but it is slow-path only and Linux/Win32 (15.4 and 18.9 min on this build) will not reach it. Addresses the "stalls are undiagnosable" gap in #24006.
UnitTestsControl retries a failed test twice (DefaultRepeatCount = 3) and logs nothing when it does; the retry loop sits inside InvokeTestMethod while the "Running test" line is emitted outside it. A test that fails twice and passes on the third attempt is therefore indistinguishable in the log from one that was simply slow — it just reports as passed with ~3x its real duration. That is very likely what the macOS render-thread leg is showing: 815 inter-test gaps of 3.05s +/- 0.046, which is 3 x WaitFor's 1000ms default timeout, on 475 tests that are deterministically affected while nextDrawable and the Idle queue were both measured healthy. Log the retry (with the exception that caused it) and the WaitFor timeout (with its caller, line, elapsed time and idle round-trip count), both on the failure path only.
…path This is the cause of the branch's macOS CI regression. The non-threaded MetalDraw re-delivers the native window size from every draw until the managed host has subscribed to SizeChanged, because the first native size updates arrive before managed initialization completes (the FIXME for uno-private#319). RenderThreadMetalDraw never had that block, so a size that arrives too early is lost and the window's XamlRoot.Bounds stays 0x0. CoreServices.RequestAdditionalFrame silently does nothing while bounds are zero (CoreServices.cs:67), and it is what schedules OnTick — which runs UpdateLayout and RaiseLoadedEvent. So for an affected window no layout ever runs, ActualWidth and ActualHeight stay 0, and WaitForLoaded's condition can never become true. The visible result was a hard 3.05s quantum on ~32% of test boundaries: WaitFor burns its full 1000ms timeout, the runner silently retries twice (logging nothing), and the test then reports Failed — invisible in CI because ReportTestResult never writes to the console and the run is cancelled before the NUnit XML is written. Tests that pass a larger timeout scale exactly with it (3000ms -> 9.01s, 5000ms -> 15.3s, 30000ms -> 90.2s), which is what identified the retry as the multiplier. UpdateWindowSize raises SizeChanged into the managed tree, so the bootstrap is marshalled to the UI thread; the render thread is asked for another frame while it is pending, and that request is paced so it cannot spin.
Console.WriteLine was the wrong channel for these. UnitTestsControl replaces
Console.Out with a TextWriterDuplicator that overrides only Write(char), so every
console line written during a test is pushed through it one character at a time
and is also captured into that test's recorded output — a poor fit for a
diagnostic that fires on a hot failure path.
Use what the surrounding code already uses: UnitTestsControl's own _log (the
Logger behind the "Running test" lines) and, for the static WindowHelper,
typeof(WindowHelper).Log() as in Given_HotReloadWorkspace. Both respect log-level
filtering and carry a category, and CI already enables them via
AddFilter("Uno.UI.Runtime.Skia", Debug) and the app's Information default.
Build 228902 was green on macOS (23.4 min, third consecutive pass) with two
failures elsewhere, both in code this branch cannot reach:
LinuxFB Given_BitmapIcon.When_Foreground_Changed_With_ShowAsMonochrome_True
(expected FFFF0000, got transparent)
WASM 2 Given_ListViewBase.When_Incremental_Load_ShouldStop
(Actual <7> is not less than <7>)
Master's own LinuxFB leg fails a different pixel test at a similar rate
(1 of 9 sampled builds: Given_FrameworkElement_Opacity.When_Opacity), so these
look like flakes on weak legs rather than a regression. Re-running to confirm:
if LinuxFB passes here, the BitmapIcon failure is flake, not this branch.
6b58c6a to
f236fab
Compare
|
Claude finished @MartinZikmund's task in 5m 13s —— View job Code Review
Verdict: ship — same 14 commits reviewed across prior passes, rebased onto master. macOS CI is now green (21.1 min, 8006 tests, two consecutive successful runs). All blocking and significant findings are resolved. Three pre-existing notes remain open, plus two new note-level findings in this pass. Status of all prior findings
New findings this pass
Cross-cutting notes
|
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-23594/wasm-skia-net9/index.html |
|
|
|
The build 229536 found UI Test snapshots differences: Details
|
unoplatform#23594 pauses the MTKView and returns early from drawInMTKView when paused, but the branch ticks external-present (WebGPU) contexts from drawInMTKView, so after the merge those windows never drew. Switch that view to draw notifications and let its callback through; Skia-on-Metal is unaffected. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01XsQppKuZgijApgJxaTZt81
Moves macOS Metal rendering (draw + GPU flush + present) off the UI thread onto a dedicated render thread, mirroring the existing Win32, X11, and iOS render threads. macOS was the only Skia host still drawing on the UI/main thread, so a slow present or VSync wait directly stalled input and layout.
Driven entirely by master's existing per-host contract —
InvalidateRender()wakes the render thread, which draws the recordedSKPictureviaOnNativePlatformFrameRequestedand presents. No shared-scheduler changes (noOnFramePresented/SupportsRenderThrottle).What changed
MacOSRenderThread(mirrors Win32'sRenderThread): anAutoResetEvent-signalled loop that acquires a drawable, draws,Flush(submit: true), then presents.InvalidateRender→SignalNewFrame()on the Metal path (software path unchanged).CAMetalLayer.nextDrawable(thread-safe, unlikeMTKView.currentDrawablewhich is main-thread-only), wrapped in@autoreleasepool;paused=YES; enableSetNeedsDisplay=NO;maximumDrawableCount = 2.MTKViewnever runs the draw cycle that applies a new drawable size to itsCAMetalLayer, sodrawableSizeWillChange:now applies it explicitly, anduno_window_acquire_next_framereports the acquired texture's own dimensions rather than the layer'sdrawableSize(the two can disagree mid-resize).uno_window_clip_svg) updates marshalled to the main thread (AppKit layer mutation).Measured impact
Workload:
Performance_1000ButtonsContinuousRendering(1000 buttons + foreverColorAnimation). Both builds are the same merged master, differing only insrc/Uno.UI.Runtime.Skia.MacOS/.sampleat 1 ms, two independent runs (40 s + 25 s), Apple M4, 120 Hz display.UI thread availability
Where master's main-thread time went (inclusive, % of main-thread samples)
drawInMTKViewcurrentDrawableMetalDraw(managed)drawInMTKView(12840 samples) ≈currentDrawable(12831) — essentially all of that 39 % is the blocking drawable/VSync wait, which is exactly what this PR removes from the UI thread.Throughput — no regression, better worst case
Both saturate the 120 Hz display; the PR is better on mean and notably better on worst-case frame time. Process CPU was also lower (~22–27 % vs ~29–37 %).
Validation
Validated on macOS 26.2 / Xcode 26.2 / Apple M4 with a locally built
libUnoNativeMac.dylib, runningSamplesApp.Skia.Generic:Icons/FontIconControlTest: 0 differing pixels across the full content area (the only delta was title-bar chrome from window focus state).ContentPresenter/ContentPresenter_NativeEmbedding_ZIndex(overlapping WebViews, animated Z-order): identical clip geometry to master (3 distinct clip paths, 1 update/sec matching the animation, no redundant re-application).__psynch_cvwaitin 1729/1735 samples (99.7 %), ~1 % process CPU while idle; no spin when the window is occluded/minimized andnextDrawablereturns nil.ObjectDisposedException, no crash reports.Not covered
drawableSizeWillChange:funnel), but a hot display switch is untested.