Repository navigation
Make UseNavigation thread-safe by default (#234) - #643
Merged
Alexandre Zollinger Chohfi (azchohfi) merged 8 commits intoJun 24, 2026
Merged
Conversation
Bring the NavigationHandle mutators up to the thread-safety-by-default standard established for UseState/UseReducer in #212. The handle's public mutators (Navigate, GoBack, GoForward, Replace, Reset, PopTo, SetState) mutated the back/forward List<T> stores with no protection, so off-thread calls could corrupt the stacks or silently lose updates. Mirror the #212 marshal-or-throw contract rather than always-locking: - New internal UIThreadMarshal helper reproduces RenderContext's MarshalIfOffUIThread gate so the rest of the hook surface can share it. - NavigationHandle captures the render/UI thread id at construction and gates each mutator. On the UI thread the cost is a single thread-id compare (~1.2 ns, zero allocation); off-thread the whole mutation is auto-marshaled onto the captured UI dispatcher, or throws InvalidOperationException loudly when no dispatcher is available (closing the same silent-failure gap #212 closed for state setters). The short-circuit call shape (IsOffUIThread && MarshalOff(...)) keeps the marshaling closure off the UI-thread fast path, so navigation's hot path allocates less than the #212 state hooks. Adds 10 cross-thread navigation tests; existing hook-ordering and NavigationStress tests stay green. Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
requested a review
from Chris Anderson (codemonkeychris)
as a code owner
June 23, 2026 05:47
- M7: SetState validates Current is null synchronously on the caller thread (before the marshal gate) so an invalid state throws ArgumentException at the call site, not later on the UI thread. - M8: unify the marshal logic — RenderContext.MarshalIfOffUIThread now delegates to a shared UIThreadMarshal.EnqueueOrThrow primitive, so the setter marshal and the navigation gate share one implementation. #212's UseState/UseReducer cross-thread tests stay green. - M6: clarify in <remarks> that an off-thread mutator's bool reports "scheduled", not navigation success. - M9: cover EnqueueOrThrow's no-dispatcher, TryEnqueue==false (shutdown), and accept-and-post branches. - M10: add a pumped-dispatcher selftest fixture asserting an off-thread Navigate/Replace actually marshals and applies (store + rerender), not just the throw path. - M1: CHANGELOG [Unreleased] entry for the off-thread NavigationHandle marshal-or-throw behavior change. - M2/M3/M5/M4: refresh docs that now contradict shipped behavior — the navigation "silent no-op" gotcha, the threading-and-dispatch table + body, and the agent-kit navigation skills. Templates recompiled via mur docs compile. Co-authored-by: Copilot <[email protected]>
Contributor
There was a problem hiding this comment.
Pull request overview
This PR closes #234 by making UseNavigation’s NavigationHandle<TRoute> mutators thread-safe-by-default, aligning navigation with the marshal-or-throw behavior introduced for state hooks in #212. It centralizes UI-thread marshaling logic in a shared helper, updates navigation to auto-marshal off-thread calls (or throw when no live dispatcher exists), and adds unit + selfhost coverage plus documentation updates.
Changes:
- Introduce
UIThreadMarshaland refactorRenderContext’s off-thread setter marshal to reuse the sharedEnqueueOrThrowimplementation. - Gate all
NavigationHandle<TRoute>mutators with a captured UI-thread-id check and marshal-or-throw behavior on off-thread calls. - Add unit tests + selfhost fixture coverage and update docs/skills/changelog to document the new threading contract.
Reviewed changes
Copilot reviewed 13 out of 13 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| tests/Reactor.Tests/ThreadSafeNavigationTests.cs | New unit tests covering off-thread rejection (no dispatcher), UI-thread behavior, and concurrency behavior for navigation mutators. |
| tests/Reactor.AppTests.Host/SelfTest/SelfTestFixtureRegistry.cs | Registers the new selftest fixture name in the registry list and constructor switch. |
| tests/Reactor.AppTests.Host/SelfTest/Fixtures/ThreadSafeNavigationFixtures.cs | New selfhost fixture validating off-thread Navigate/Replace marshals correctly on a real dispatcher and triggers rerender. |
| src/Reactor/Core/UIThreadMarshal.cs | New shared helper implementing the marshal-or-throw primitive (EnqueueOrThrow) and a navigation/state-friendly gate. |
| src/Reactor/Core/RenderContext.cs | Refactors MarshalIfOffUIThread to use UIThreadMarshal.EnqueueOrThrow while preserving existing diagnostics. |
| src/Reactor/Core/Navigation/NavigationHandle.cs | Adds thread-id capture + off-thread gating for all mutators; documents new semantics for off-thread bool return values. |
| skills/navigation.md | Updates navigation skill docs with the new threading behavior and caveats. |
| plugins/reactor/skills/reactor-navigation/SKILL.md | Mirrors the skill doc update in the packaged skill copy. |
| docs/guide/threading-and-dispatch.md | Documents navigation mutator threading behavior and how it relates to the existing setter marshaling contract. |
| docs/guide/navigation.md | Updates navigation guide text to reflect auto-marshal + loud-throw behavior and the “scheduled vs succeeded” caveat. |
| docs/_pipeline/templates/threading-and-dispatch.md.dt | Updates the source template for the threading/dispatch guide to include navigation mutator behavior. |
| docs/_pipeline/templates/navigation.md.dt | Updates the source template for the navigation guide to include navigation mutator behavior. |
| CHANGELOG.md | Adds an entry documenting the new thread-safe-by-default UseNavigation mutators behavior and shared marshal implementation. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- ThreadSafeNavigationFixtures: narrow the two background-task catch clauses from catch (Exception) to catch (InvalidOperationException), the documented marshal throw type (code-quality bot). - NavigationHandle <remarks>: document that off-thread mutators also throw when the captured dispatcher refuses the enqueue (TryEnqueue returns false during shutdown), not only when no dispatcher exists (Copilot review). Co-authored-by: Copilot <[email protected]>
…bool docs Follow-up to the #234 pr-review re-run on PR #643: - M1 (test-coverage): add a MutatorsOffThreadMarshal selftest fixture that drives GoBack/GoForward/PopTo/Reset/SetState off the UI thread on a real pumped DispatcherQueue, asserting each marshals + applies + re-renders. Previously only Navigate/Replace had real-dispatcher happy-path coverage; the other mutators were only covered for the off-thread rejection path. - L2 (api-ergonomics): give the bool-returning NavigationHandle mutators (Navigate/GoBack/GoForward/Replace/Reset/PopTo) a <returns> documenting the off-thread semantics -- an off-thread true means "marshaled + scheduled", not "navigation succeeded" (the UI-thread meaning is unchanged). Moves the per-method false-conditions into <returns> where they belong. No behavior change. Core lib builds clean (0 warnings); ThreadSafeNavigationTests plus #212's ThreadSafeHookTests stay green (31/31), and both nav selftests pass (30/30 checks on a real dispatcher). Co-authored-by: Copilot <[email protected]>
- ThreadSafeNavigationFixtures.cs: revert the three off-thread Task.Run catch clauses from `catch (InvalidOperationException)` back to `catch (Exception)` forwarding to TrySetException. In a test harness the narrow catch lets an unexpected exception (e.g. a setup regression throwing NullReference) escape, leaving the TaskCompletionSource incomplete so the fixture hangs to the 10s timeout and hides the real stack trace. Broad-catch-and-forward surfaces any failure immediately on `await done.Task` and matches the established ThreadSafeHookFixtures.NonThreadSafeAutoMarshal pattern. Added a brief comment at each site documenting the intent so it isn't re-narrowed. - skills/navigation.md + plugins/reactor/skills/reactor-navigation/SKILL.md: the Threading snippet called `nav.Navigate(Route.Detail, result)`, but NavigationHandle.Navigate is `(TRoute route, NavigateOptions? options = null)` — there is no overload taking an arbitrary result, so it wouldn't compile. Carry the loaded data in the route instead via the nested-record form the doc itself documents: `nav.Navigate(new Route.Details(itemId))`. No production behavior change. Both nav selftests pass (30/30 checks) on a real pumped dispatcher. Co-authored-by: Copilot <[email protected]>
github-code-quality flagged the broad `catch (Exception)` clauses in the nav selftest fixtures as fully-generic. Add the house-style exception filter `when (ex is not OutOfMemoryException and not StackOverflowException)` (matching the 5 existing uses in src/Reactor) to all three sites. This keeps the test-diagnostics behavior — any recoverable failure is forwarded to TrySetException and surfaces on `await done.Task` instead of hanging to the 10s timeout — while no longer swallowing process-fatal exceptions. Copilot flagged that SetState validates Current but passes BackStack/ForwardStack straight into RestoreState, which AddRanges both and would throw on a null list (e.g. a deserialized snapshot) later on the UI dispatcher, where an off-thread caller can't observe it. Extend the M7 fail-fast validation to null-check both lists before the marshal gate, and add two unit tests mirroring the null-Current case. Co-authored-by: Copilot <[email protected]>
Copilot flagged that the EnqueueOrThrow tryEnqueue factory at both call sites — UIThreadMarshal.MarshalOffUIThread and RenderContext.MarshalIfOffUIThread — wrote `w => dq.TryEnqueue(() => w())`, which allocates a closure capturing the `w` Action on every off-thread marshal. Since `w` is already an Action, pass the `w.Invoke` method group instead, eliminating the per-enqueue closure allocation. Off-thread-path only; UI-thread fast path and behavior are unchanged. Co-authored-by: Copilot <[email protected]>
NavigationState<TRoute> accepts arbitrary IReadOnlyList stacks, so a caller can pass a live List<T>. The off-thread SetState path marshals the restore onto the UI-thread dispatcher and returns immediately; it previously enqueued () => SetState(state), which read state.BackStack/ForwardStack LATER on the UI thread. A caller mutating their original list in that window would corrupt the applied history versus the snapshot validated at call time. SetState now copies the supplied stacks into arrays before the dispatcher hop (off-thread path only; the UI-thread fast path is untouched). This is symmetric with GetState, which already hands out arrays via ToArray so a snapshot can't alias the live stack. Adds a pumped-dispatcher selftest (SetStateOffThreadFreezesSnapshot) that corrupts the caller's lists inside the marshal window and asserts the restored state matches the call-time snapshot. Surfaced by the pr-review multi-model cross-check. Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi)
deleted the
azchohfi-threadsafe-hooks-234
branch
June 24, 2026 21:02
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #234.
What & why
Issue #234 tracks bringing the rest of the hooks up to the thread-safety-by-default standard that #212 established for
UseState/UseReducer(per Chris Anderson (@codemonkeychris): "UseState and UseReducer were fixed for #212, this issue would track the rest of the hooks"). The maintainer's position is safety over raw performance — authors should not have to predict upfront whether a value will be updated off-thread.After auditing every hook in
src/Reactor/Coreandsrc/Reactor/Hooks, the single genuine remaining gap isUseNavigation. ItsNavigationHandle<TRoute>mutators (Navigate,GoBack,GoForward,Replace,Reset,PopTo,SetState) mutated the internal back/forwardList<T>stores with no protection, so an off-thread call (fromTask.Run, a timer, or afterawait … ConfigureAwait(false)) could corrupt the stacks or silently lose the navigation. Every other hook was already safe (see audit below).The #212 pattern this mirrors
#212 used marshal-or-throw, not always-lock:
ReactorApp.UIDispatcher.TryEnqueue); throwInvalidOperationExceptionloudly if no dispatcher is available or the queue refuses (shutdown), instead of silently racing the reconciler.This PR reproduces that contract:
src/Reactor/Core/UIThreadMarshal.cs(IsOffUIThread+MarshalOffUIThread) so the rest of the hook surface can share one gate.NavigationHandlecaptures the render/UI thread id at construction and gates each mutator:IsOffUIThread && …) keeps the marshaling closure off the UI-thread fast path — so navigation's hot path allocates less than the UseState/UseReducer updates from background threads silently fail in DEBUG and produce non-deterministic UI in RELEASE #212 state hooks.Lock-cost / fast-path measurement (the maintainer explicitly cares)
Micro-benchmark on the UI-thread fast path (ARM64, Release):
NavigationHandle.Replace(full)UseStatedefault setter (#212 reference)The gate cost on the common (UI-thread) case is ~1 ns and zero allocation — well within the "tolerable" bar. Navigation's fast path is lighter than the existing #212 state hooks.
Breaking?
Non-breaking. The gate is additive; on-thread behavior is byte-for-byte identical. The only behavior change is on the previously broken off-thread path: it now marshals (just works) or throws a clear, actionable exception instead of corrupting state. The bool-returning mutators return
truewhen an off-thread call is scheduled (documented in the XML docs).Audit — why only UseNavigation needed changes
UseState/UseReducer/UsePersisted— ✅ done in UseState/UseReducer updates from background threads silently fail in DEBUG and produce non-deterministic UI in RELEASE #212.UseObservable*/UseCollection— ✅ route through the defaultUseReducerforceRender, which auto-marshals.UseResource/UseMutation/UseInfiniteResource— ✅ self-marshal viaIHookDispatcher+threadSafe:truereducer.UseCommand— ✅UseState(threadSafe:true).UseMemo/UseCallback/UseContext/UseEffect— render-phase only, no off-thread setter.UseRef— React-parity escape hatch, never schedules a render (left as-is, by design).UISettingsevents fire off-thread, but rerender already marshals + the field writes are atomic (left as-is to avoid shutdown-crash risk from a throwing marshal).UseNavigation→NavigationHandle— ❌ the gap this PR fixes.RenderContext.MarshalIfOffUIThread(the #212 mechanism) was unified with the newUIThreadMarshal(M8): both now funnel throughUIThreadMarshal.EnqueueOrThrow, so there is a single marshal implementation rather than two near-identical copies. #212'sUseState/UseReducercross-thread tests stay green after the refactor (the exact exception wording, incl.threadSafe: true, is preserved via lazy message factories).Tests
tests/Reactor.Tests/ThreadSafeNavigationTests.cs: every mutator off-thread-with-no-dispatcher throws + leaves the stack untouched (no partial mutation); UI-thread mutators behave normally; rerender fires; a 32-task concurrent off-thread test; M7SetStatenull-Currentfail-fast; theUIThreadMarshal.EnqueueOrThrownull/refused/accept primitive cases.DispatcherQueue:NavigateOffThreadMarshals(Navigate/Replace) +MutatorsOffThreadMarshal(GoBack/GoForward/PopTo/Reset/SetState) prove off-thread calls marshal + apply + re-render end-to-end.Reactor.Testssuite green (the only failure under full-suite load is the pre-existing unrelatedCompilationLoaderTestscold-load timing flake, which passes in isolation).Review follow-ups (after the initial description)
A second
pr-reviewpass produced no critical/high findings; the actionable items landed as follow-up commits:MutatorsOffThreadMarshalselftest that drivesGoBack/GoForward/PopTo/Reset/SetStateoff-thread on a real pumpedDispatcherQueue(the original M10 fixture only exercisedNavigate/Replace). Every mutator now has real-dispatcher happy-path coverage, not just the off-thread-rejection path.<returns>documenting that an off-threadtruemeans scheduled, not succeeded (the UI-thread meaning is unchanged).docs/guide/threading-and-dispatch.mddiff includes ~13 lines of an unrelatedShouldSuppress(Reconciler.ReactorState)overload (issue Coalesce ReactorState DP read in change-event handlers (perf) #207). That is not a change in this PR —mur docs compilere-extracted the current snippet fromsrc/Reactor/Core/ChangeEchoSuppressor.cs(whose source is not touched here; an earlier PR landed the overload without recompiling docs). Flagged so reviewers aren't surprised; the generated content is correct.Co-authored-by: Copilot [email protected]