Skip to content

Make UseNavigation thread-safe by default (#234) - #643

Merged
Alexandre Zollinger Chohfi (azchohfi) merged 8 commits into
mainfrom
azchohfi-threadsafe-hooks-234
Jun 24, 2026
Merged

Alexandre Zollinger Chohfi (azchohfi) merged 8 commits into
mainfrom
azchohfi-threadsafe-hooks-234

Conversation

@azchohfi

@azchohfi Alexandre Zollinger Chohfi (azchohfi) commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator

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/Core and src/Reactor/Hooks, the single genuine remaining gap is UseNavigation. Its NavigationHandle<TRoute> mutators (Navigate, GoBack, GoForward, Replace, Reset, PopTo, SetState) mutated the internal back/forward List<T> stores with no protection, so an off-thread call (from Task.Run, a timer, or after await … 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:

  • UI-thread fast path = a single thread-id compare → run inline.
  • Off-thread = enqueue the work onto the captured UI dispatcher (ReactorApp.UIDispatcher.TryEnqueue); throw InvalidOperationException loudly if no dispatcher is available or the queue refuses (shutdown), instead of silently racing the reconciler.

This PR reproduces that contract:

  • New internal helper src/Reactor/Core/UIThreadMarshal.cs (IsOffUIThread + MarshalOffUIThread) so the rest of the hook surface can share one gate.
  • NavigationHandle captures the render/UI thread id at construction and gates each mutator:
    if (IsOffUIThread && MarshalOff(nameof(Navigate), () => Navigate(route, options))) return true;
    The short-circuit (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):

Path ns/op alloc
Gate (thread-id read + compare) ~1.16 ns delta 0 bytes
NavigationHandle.Replace (full) 20.9 ns 32 bytes (inherent nav-entry work; gate adds none)
UseState default setter (#212 reference) 71 ns 120 bytes

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 true when 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 default UseReducer forceRender, which auto-marshals.
  • UseResource / UseMutation / UseInfiniteResource — ✅ self-marshal via IHookDispatcher + threadSafe:true reducer.
  • 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).
  • Theme/motion hooks — WinRT UISettings events 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 new UIThreadMarshal (M8): both now funnel through UIThreadMarshal.EnqueueOrThrow, so there is a single marshal implementation rather than two near-identical copies. #212's UseState/UseReducer cross-thread tests stay green after the refactor (the exact exception wording, incl. threadSafe: true, is preserved via lazy message factories).

Tests

  • New 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; M7 SetState null-Current fail-fast; the UIThreadMarshal.EnqueueOrThrow null/refused/accept primitive cases.
  • Selftests on a real pumped DispatcherQueue: NavigateOffThreadMarshals (Navigate/Replace) + MutatorsOffThreadMarshal (GoBack/GoForward/PopTo/Reset/SetState) prove off-thread calls marshal + apply + re-render end-to-end.
  • Full Reactor.Tests suite green (the only failure under full-suite load is the pre-existing unrelated CompilationLoaderTests cold-load timing flake, which passes in isolation).

Review follow-ups (after the initial description)

A second pr-review pass produced no critical/high findings; the actionable items landed as follow-up commits:

  • Test coverage: added a MutatorsOffThreadMarshal selftest that drives GoBack/GoForward/PopTo/Reset/SetState off-thread on a real pumped DispatcherQueue (the original M10 fixture only exercised Navigate/Replace). Every mutator now has real-dispatcher happy-path coverage, not just the off-thread-rejection path.
  • API docs: each bool-returning mutator now has a <returns> documenting that an off-thread true means scheduled, not succeeded (the UI-thread meaning is unchanged).
  • Heads-up — benign generated-doc churn: the docs/guide/threading-and-dispatch.md diff includes ~13 lines of an unrelated ShouldSuppress(Reconciler.ReactorState) overload (issue Coalesce ReactorState DP read in change-event handlers (perf) #207). That is not a change in this PR — mur docs compile re-extracted the current snippet from src/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]

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]>
- 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]>

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 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 UIThreadMarshal and refactor RenderContext’s off-thread setter marshal to reuse the shared EnqueueOrThrow implementation.
  • 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]>

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 13 out of 13 changed files in this pull request and generated 5 comments.

Comment thread skills/navigation.md Resolved
- 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]>

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 13 out of 13 changed files in this pull request and generated 1 comment.

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 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 13 out of 13 changed files in this pull request and generated 2 comments.

Comment thread src/Reactor/Core/UIThreadMarshal.cs Resolved
Comment thread src/Reactor/Core/RenderContext.cs Resolved
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]>

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 13 out of 13 changed files in this pull request and generated no new comments.

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]>

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 13 out of 13 changed files in this pull request and generated 1 comment.

@azchohfi
Alexandre Zollinger Chohfi (azchohfi) merged commit c008e5c into main Jun 24, 2026
18 checks passed
@azchohfi
Alexandre Zollinger Chohfi (azchohfi) deleted the azchohfi-threadsafe-hooks-234 branch June 24, 2026 21:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Consider being more threadsafe on hooks & state

2 participants